-
Notifications
You must be signed in to change notification settings - Fork 13.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add support for Azure Data Explorer (Kusto) db engine spec #17898
Merged
Merged
Changes from 6 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
04c4354
Add two Kusto engine specs: KQL and SQL. Some minor changes in core c…
xneg c08cf90
Remove redundant imports and logging.
xneg 28f3f64
docs: Kusto sqlalchemy docs
bef6bea
fix: Fix mypy and linting errors
Ceridan 15bee79
fix: Handle Black vs Pylint checks
Ceridan 992f64c
fix: isort problem
Ceridan ea386d6
refactor: Merge kustosql and kustokql in the single kusto module
Ceridan 235d5ae
test: Add tests for Kusto db spec
Ceridan 8092fac
feat: Schema override does not require in KQL anymore
Ceridan d663b1b
Merge pull request #2 from Ceridan/add-kusto-engine-support
xneg 1d37226
Removed redundant imports.
xneg e208800
Added ".show" queries to readonly query determination.
xneg 9a6598b
Fixed some bugs.
xneg 793d504
Fixed major sqlalchemy-kusto version.
xneg 4fa2914
Fixed by isort.
xneg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
--- | ||
name: Kusto | ||
menu: Connecting to Databases | ||
route: /docs/databases/kusto | ||
index: 32 | ||
version: 1 | ||
--- | ||
|
||
## Kusto | ||
|
||
The recommended connector library for Kusto is | ||
[sqlalchemy-kusto](https://pypi.org/project/sqlalchemy-kusto/1.0.1/)>=1.0.1. | ||
|
||
The connection string for Kusto looks like this: | ||
|
||
``` | ||
kustosql+https://{cluster_url}/{database}?azure_ad_client_id={azure_ad_client_id}&azure_ad_client_secret={azure_ad_client_secret}&azure_ad_tenant_id={azure_ad_tenant_id}&msi=False | ||
``` | ||
|
||
Make sure the user has privileges to access and use all required | ||
databases/tables/views. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
from datetime import datetime | ||
from typing import Any, Dict, List, Optional, Type | ||
|
||
from sqlalchemy.engine import Engine | ||
|
||
from superset.db_engine_specs.base import BaseEngineSpec, LimitMethod | ||
from superset.db_engine_specs.exceptions import ( | ||
SupersetDBAPIDatabaseError, | ||
SupersetDBAPIOperationalError, | ||
SupersetDBAPIProgrammingError, | ||
) | ||
from superset.models.core import Database | ||
from superset.sql_parse import ParsedQuery | ||
from superset.utils import core as utils | ||
|
||
|
||
class KustoKqlEngineSpec(BaseEngineSpec): # pylint: disable=abstract-method | ||
limit_method = LimitMethod.WRAP_SQL | ||
engine = "kustokql" | ||
engine_name = "KustoKQL" | ||
time_groupby_inline = True | ||
time_secondary_columns = True | ||
allows_joins = True | ||
allows_subqueries = True | ||
allows_sql_comments = False | ||
run_multiple_statements_as_one = True | ||
|
||
_time_grain_expressions = { | ||
None: "{col}", | ||
"PT1S": "{col}/ time(1s)", | ||
"PT1M": "{col}/ time(1min)", | ||
"PT1H": "{col}/ time(1h)", | ||
"P1D": "{col}/ time(1d)", | ||
"P1M": "datetime_diff('month',CreateDate, datetime(0001-01-01 00:00:00))+1", | ||
"P1Y": "datetime_diff('year',CreateDate, datetime(0001-01-01 00:00:00))+1", | ||
} | ||
|
||
type_code_map: Dict[int, str] = {} # loaded from get_datatype only if needed | ||
|
||
@classmethod | ||
def get_dbapi_exception_mapping(cls) -> Dict[Type[Exception], Type[Exception]]: | ||
# pylint: disable=import-outside-toplevel,import-error | ||
import sqlalchemy_kusto.errors as kusto_exceptions | ||
|
||
return { | ||
kusto_exceptions.DatabaseError: SupersetDBAPIDatabaseError, | ||
kusto_exceptions.OperationalError: SupersetDBAPIOperationalError, | ||
kusto_exceptions.ProgrammingError: SupersetDBAPIProgrammingError, | ||
} | ||
|
||
@classmethod | ||
def convert_dttm( | ||
cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None | ||
) -> Optional[str]: | ||
if target_type.upper() == utils.TemporalType.DATETIME: | ||
return f"""datetime({dttm.isoformat(timespec="seconds")})""" | ||
return None | ||
|
||
@classmethod | ||
def is_readonly_query(cls, parsed_query: ParsedQuery) -> bool: | ||
"""Pessimistic readonly, 100% sure statement won't mutate anything""" | ||
return not parsed_query.sql.startswith(".") | ||
|
||
@classmethod | ||
def select_star( # pylint: disable=too-many-arguments | ||
cls, | ||
database: Database, | ||
table_name: str, | ||
engine: Engine, | ||
schema: Optional[str] = None, | ||
limit: int = 100, | ||
show_cols: bool = False, | ||
indent: bool = True, | ||
latest_partition: bool = True, | ||
cols: Optional[List[Dict[str, Any]]] = None, | ||
) -> str: | ||
return super().select_star( | ||
database, | ||
table_name, | ||
engine, | ||
None, | ||
limit, | ||
show_cols, | ||
indent, | ||
latest_partition, | ||
cols, | ||
) | ||
|
||
@classmethod | ||
def is_select_query(cls, parsed_query: ParsedQuery) -> bool: | ||
return not parsed_query.sql.startswith(".") | ||
villebro marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@classmethod | ||
def execute(cls, cursor: Any, query: str, **kwargs: Any) -> None: | ||
return super().execute(cursor, query, **kwargs) | ||
|
||
@classmethod | ||
def parse_sql(cls, sql: str) -> List[str]: | ||
return [sql] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
villebro marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
from datetime import datetime | ||
from typing import Any, Dict, Optional, Type | ||
|
||
from superset.db_engine_specs.base import BaseEngineSpec, LimitMethod | ||
from superset.db_engine_specs.exceptions import ( | ||
SupersetDBAPIDatabaseError, | ||
SupersetDBAPIOperationalError, | ||
SupersetDBAPIProgrammingError, | ||
) | ||
from superset.sql_parse import ParsedQuery | ||
from superset.utils import core as utils | ||
|
||
|
||
class KustoSqlEngineSpec(BaseEngineSpec): # pylint: disable=abstract-method | ||
limit_method = LimitMethod.WRAP_SQL | ||
engine = "kustosql" | ||
engine_name = "KustoSQL" | ||
time_groupby_inline = True | ||
time_secondary_columns = True | ||
allows_joins = True | ||
allows_subqueries = True | ||
allows_sql_comments = False | ||
|
||
_time_grain_expressions = { | ||
None: "{col}", | ||
"PT1S": "DATEADD(second, DATEDIFF(second, '2000-01-01', {col}), '2000-01-01')", | ||
"PT1M": "DATEADD(minute, DATEDIFF(minute, 0, {col}), 0)", | ||
"PT5M": "DATEADD(minute, DATEDIFF(minute, 0, {col}) / 5 * 5, 0)", | ||
"PT10M": "DATEADD(minute, DATEDIFF(minute, 0, {col}) / 10 * 10, 0)", | ||
"PT15M": "DATEADD(minute, DATEDIFF(minute, 0, {col}) / 15 * 15, 0)", | ||
"PT0.5H": "DATEADD(minute, DATEDIFF(minute, 0, {col}) / 30 * 30, 0)", | ||
"PT1H": "DATEADD(hour, DATEDIFF(hour, 0, {col}), 0)", | ||
"P1D": "DATEADD(day, DATEDIFF(day, 0, {col}), 0)", | ||
"P1W": "DATEADD(day, -1, DATEADD(week, DATEDIFF(week, 0, {col}), 0))", | ||
"P1M": "DATEADD(month, DATEDIFF(month, 0, {col}), 0)", | ||
"P0.25Y": "DATEADD(quarter, DATEDIFF(quarter, 0, {col}), 0)", | ||
"P1Y": "DATEADD(year, DATEDIFF(year, 0, {col}), 0)", | ||
"1969-12-28T00:00:00Z/P1W": "DATEADD(day, -1," | ||
" DATEADD(week, DATEDIFF(week, 0, {col}), 0))", | ||
"1969-12-29T00:00:00Z/P1W": "DATEADD(week," | ||
" DATEDIFF(week, 0, DATEADD(day, -1, {col})), 0)", | ||
} | ||
|
||
type_code_map: Dict[int, str] = {} # loaded from get_datatype only if needed | ||
|
||
@classmethod | ||
def get_dbapi_exception_mapping(cls) -> Dict[Type[Exception], Type[Exception]]: | ||
# pylint: disable=import-outside-toplevel,import-error | ||
import sqlalchemy_kusto.errors as kusto_exceptions | ||
|
||
return { | ||
kusto_exceptions.DatabaseError: SupersetDBAPIDatabaseError, | ||
kusto_exceptions.OperationalError: SupersetDBAPIOperationalError, | ||
kusto_exceptions.ProgrammingError: SupersetDBAPIProgrammingError, | ||
} | ||
|
||
@classmethod | ||
def convert_dttm( | ||
cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None | ||
) -> Optional[str]: | ||
tt = target_type.upper() | ||
if tt == utils.TemporalType.DATE: | ||
return f"CONVERT(DATE, '{dttm.date().isoformat()}', 23)" | ||
if tt == utils.TemporalType.DATETIME: | ||
datetime_formatted = dttm.isoformat(timespec="milliseconds") | ||
return f"""CONVERT(DATETIME, '{datetime_formatted}', 126)""" | ||
if tt == utils.TemporalType.SMALLDATETIME: | ||
datetime_formatted = dttm.isoformat(sep=" ", timespec="seconds") | ||
return f"""CONVERT(SMALLDATETIME, '{datetime_formatted}', 20)""" | ||
return None | ||
|
||
@classmethod | ||
def is_readonly_query(cls, parsed_query: ParsedQuery) -> bool: | ||
"""Pessimistic readonly, 100% sure statement won't mutate anything""" | ||
return parsed_query.sql.lower().startswith("select") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just in case, could we restrict to the current major version?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, sounds good to me. We will add this restriction.