-
Notifications
You must be signed in to change notification settings - Fork 1
Support sql check #44
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
Merged
Merged
Changes from all commits
Commits
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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,18 +1,11 @@ | ||
| from abc import abstractmethod | ||
| from typing import Optional | ||
|
|
||
| from datapilot.core.insights.base.insight import Insight | ||
| from datapilot.schemas.sql import Dialect | ||
| from datapilot.core.platforms.dbt.insights.checks.base import ChecksInsight | ||
|
|
||
|
|
||
| class SqlInsight(Insight): | ||
| class SqlInsight(ChecksInsight): | ||
| NAME = "SqlInsight" | ||
|
|
||
| def __init__(self, sql: str, dialect: Optional[Dialect], *args, **kwargs): | ||
| self.sql = sql | ||
| self.dialect = dialect | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| @abstractmethod | ||
| def generate(self, *args, **kwargs) -> dict: | ||
| pass |
This file contains hidden or 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 hidden or 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 hidden or 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
Empty file.
This file contains hidden or 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,23 @@ | ||
| from abc import abstractmethod | ||
| from typing import Tuple | ||
|
|
||
| from datapilot.core.platforms.dbt.insights.base import DBTInsight | ||
|
|
||
|
|
||
| class SqlInsight(DBTInsight): | ||
| TYPE = "governance" | ||
|
|
||
| @abstractmethod | ||
| def generate(self, *args, **kwargs) -> dict: | ||
| pass | ||
|
|
||
| @classmethod | ||
| def has_all_required_data(cls, has_manifest: bool, **kwargs) -> Tuple[bool, str]: | ||
| """ | ||
| Check if all required data is available for the insight to run. | ||
| :param has_manifest: A boolean indicating if manifest is available. | ||
| :return: A boolean indicating if all required data is available. | ||
| """ | ||
| if not has_manifest: | ||
| return False, "manifest is required for insight to run." | ||
| return True, "" | ||
101 changes: 101 additions & 0 deletions
101
src/datapilot/core/platforms/dbt/insights/sql/sql_check.py
This file contains hidden or 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,101 @@ | ||
| import inspect | ||
| from typing import List | ||
|
|
||
| from sqlglot import parse_one | ||
| from sqlglot.optimizer.eliminate_ctes import eliminate_ctes | ||
| from sqlglot.optimizer.eliminate_joins import eliminate_joins | ||
| from sqlglot.optimizer.eliminate_subqueries import eliminate_subqueries | ||
| from sqlglot.optimizer.normalize import normalize | ||
| from sqlglot.optimizer.pushdown_projections import pushdown_projections | ||
| from sqlglot.optimizer.qualify import qualify | ||
| from sqlglot.optimizer.unnest_subqueries import unnest_subqueries | ||
|
|
||
| from datapilot.core.insights.sql.base.insight import SqlInsight | ||
| from datapilot.core.insights.utils import get_severity | ||
| from datapilot.core.platforms.dbt.insights.schema import DBTInsightResult | ||
| from datapilot.core.platforms.dbt.insights.schema import DBTModelInsightResponse | ||
|
|
||
| RULES = ( | ||
| pushdown_projections, | ||
| normalize, | ||
| unnest_subqueries, | ||
| eliminate_subqueries, | ||
| eliminate_joins, | ||
| eliminate_ctes, | ||
| ) | ||
|
|
||
|
|
||
| class SqlCheck(SqlInsight): | ||
| """ | ||
| This class identifies DBT models with SQL optimization issues. | ||
| """ | ||
|
|
||
| NAME = "sql optimization issues" | ||
| ALIAS = "check_sql_optimization" | ||
| DESCRIPTION = "Checks if the model has SQL optimization issues. " | ||
| REASON_TO_FLAG = "The query can be optimized." | ||
| FAILURE_MESSAGE = "The query for model `{model_unique_id}` has optimization opportunities:\n{rule_name}. " | ||
| RECOMMENDATION = "Please adapt the query of the model `{model_unique_id}` as in following example:\n{optimized_sql}" | ||
|
|
||
| def _build_failure_result(self, model_unique_id: str, rule_name: str, optimized_sql: str) -> DBTInsightResult: | ||
| """ | ||
| Constructs a failure result for a given model with sql optimization issues. | ||
| :param model_unique_id: The unique id of the dbt model. | ||
| :param rule_name: The rule that generated this failure result. | ||
| :param optimized_sql: The optimized sql. | ||
| :return: An instance of DBTInsightResult containing failure details. | ||
| """ | ||
| failure_message = self.FAILURE_MESSAGE.format(model_unique_id=model_unique_id, rule_name=rule_name) | ||
| recommendation = self.RECOMMENDATION.format(model_unique_id=model_unique_id, optimized_sql=optimized_sql) | ||
| return DBTInsightResult( | ||
| type=self.TYPE, | ||
| name=self.NAME, | ||
| message=failure_message, | ||
| recommendation=recommendation, | ||
| reason_to_flag=self.REASON_TO_FLAG, | ||
| metadata={"model_unique_id": model_unique_id, "rule_name": rule_name}, | ||
| ) | ||
|
|
||
| def generate(self, *args, **kwargs) -> List[DBTModelInsightResponse]: | ||
| """ | ||
| Generates insights for each DBT model in the project, focusing on sql optimization issues. | ||
|
|
||
| :return: A list of DBTModelInsightResponse objects with insights for each model. | ||
| """ | ||
| self.logger.debug("Generating sql insights for DBT models") | ||
mdesmet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| insights = [] | ||
|
|
||
| possible_kwargs = { | ||
| "db": None, | ||
| "catalog": None, | ||
| "dialect": self.adapter_type, | ||
| "isolate_tables": True, # needed for other optimizations to perform well | ||
| "quote_identifiers": False, | ||
| **kwargs, | ||
| } | ||
| for node_id, node in self.nodes.items(): | ||
| try: | ||
| compiled_query = node.compiled_code | ||
| if compiled_query: | ||
| parsed_query = parse_one(compiled_query, dialect=self.adapter_type) | ||
| qualified = qualify(parsed_query, **possible_kwargs) | ||
| changed = qualified.copy() | ||
| for rule in RULES: | ||
| original = changed.copy() | ||
| rule_params = inspect.getfullargspec(rule).args | ||
| rule_kwargs = {param: possible_kwargs[param] for param in rule_params if param in possible_kwargs} | ||
| changed = rule(changed, **rule_kwargs) | ||
| if changed.sql() != original.sql(): | ||
| insights.append( | ||
| DBTModelInsightResponse( | ||
| unique_id=node_id, | ||
| package_name=node.package_name, | ||
| path=node.original_file_path, | ||
| original_file_path=node.original_file_path, | ||
| insight=self._build_failure_result(node_id, rule.__name__, changed.sql()), | ||
| severity=get_severity(self.config, self.ALIAS, self.DEFAULT_SEVERITY), | ||
| ) | ||
| ) | ||
| except Exception as e: | ||
| self.logger.error(e) | ||
| return insights | ||
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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.
The
has_all_required_datamethod is a duplicate of the method inDBTGovernanceInsight. Consider using the existing method to avoid duplication.has_all_required_data(base.py)