You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "john-bodley (via GitHub)" <gi...@apache.org> on 2024/03/12 01:01:38 UTC

[PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

john-bodley opened a new pull request, #27470:
URL: https://github.com/apache/superset/pull/27470

   <!---
   Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
   Example:
   fix(dashboard): load charts correctly
   -->
   
   ### SUMMARY
   
   This is an alternative formulation to https://github.com/apache/superset/pull/27464 by performing a two-phase approach for extracting tables from SQL which may contain Jinja templating which can result in non-parsable SQL from SQLGlot's perspective. 
   
   The logic is outlined in https://github.com/apache/superset/pull/27464#issuecomment-1989433700.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   ### TESTING INSTRUCTIONS
   
   Added unit tests.
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on PR #27470:
URL: https://github.com/apache/superset/pull/27470#issuecomment-2004785843

   Closing in favor of https://github.com/apache/superset/pull/27464.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "betodealmeida (via GitHub)" <gi...@apache.org>.
betodealmeida commented on PR #27470:
URL: https://github.com/apache/superset/pull/27470#issuecomment-1992304250

   See the approach I suggested here: https://github.com/apache/superset/pull/27464#issuecomment-1991531350
   
   It does a better job decoupling Jinja rendering from SQL parsing, which is my main concern with this approach, together with the fact that `ParsedQuery` is going to be removed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #27470:
URL: https://github.com/apache/superset/pull/27470#discussion_r1521289635


##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL

Review Comment:
   ```suggestion
           Due to Jinja templating, a multiphase approach is necessary as the referenced SQL
   ```



##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL
+        statement is likely ill-defined (due to the presence of the Jinja macros) and
+        thus non-parsable by SQLGlot.
+
+        Firstly, we extract any tables referenced within the confines of specific Jinja
+        macros. Secondly, we replace these non-SQL Jinja calls with a pseudo-benign SQL
+        expression to help ensure that the resulting SQL statements are parsable by
+        SQLGlot.
         """
+
+        from superset.jinja_context import (  # pylint: disable=import-outside-toplevel
+            get_template_processor,
+        )
+
+        tables = set()
+        sql = self.stripped()
+
+        # Mock the required database as the processor signature is exposed publically.
+        processor = get_template_processor(database=Mock(backend=self._dialect))
+        template = processor.env.parse(sql)
+
+        for node in template.find_all(nodes.Call):
+            if isinstance(node.node, nodes.Getattr) and node.node.attr in (
+                "latest_partition",
+                "latest_sub_partition",
+            ):
+                # Extract the table referenced in the macro.
+                tables.add(
+                    Table(
+                        *[
+                            remove_quotes(part)
+                            for part in node.args[0].value.split(".")[::-1]
+                            if len(node.args) == 1
+                        ]
+                    )
+                )
+
+                # Replace the potentially problematic Jinja macro with benign SQL.
+                node.__class__ = nodes.TemplateData
+                node.fields = nodes.TemplateData.fields
+                node.data = "NULL"
+
+        sql = processor.process_template(template)
+
         try:
-            statements = parse(self.stripped(), dialect=self._dialect)
+            tables.update(
+                [
+                    table
+                    for statement in parse(sql, dialect=self._dialect)
+                    for table in self._extract_tables_from_statement(statement)
+                    if statement
+                ]
+            )
         except SqlglotError:
-            logger.warning("Unable to parse SQL (%s): %s", self._dialect, self.sql)
-            return set()
+            logger.warning("Unable to parse SQL (%s): %s", self._dialect, sql)

Review Comment:
   I think we should throw an exception if a sqlglot or Jinja parsing error occurs instead of returning an empty set. The main reason is because we can have a valid SQL query with no tables, which would also evaluate to an empty set. This is a distinct situation from the inability to determine the existence of tables, and the implications can vary. I think it's the responsibility of the caller to deal with both scenarios.



##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL
+        statement is likely ill-defined (due to the presence of the Jinja macros) and
+        thus non-parsable by SQLGlot.
+
+        Firstly, we extract any tables referenced within the confines of specific Jinja
+        macros. Secondly, we replace these non-SQL Jinja calls with a pseudo-benign SQL
+        expression to help ensure that the resulting SQL statements are parsable by
+        SQLGlot.
         """
+
+        from superset.jinja_context import (  # pylint: disable=import-outside-toplevel
+            get_template_processor,
+        )
+
+        tables = set()
+        sql = self.stripped()
+
+        # Mock the required database as the processor signature is exposed publically.
+        processor = get_template_processor(database=Mock(backend=self._dialect))
+        template = processor.env.parse(sql)
+
+        for node in template.find_all(nodes.Call):
+            if isinstance(node.node, nodes.Getattr) and node.node.attr in (

Review Comment:
   Do we need to consider other possible [Jinja macros](https://superset.apache.org/docs/installation/sql-templating/) such as  `{{ url_param('custom_variable') }}`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on code in PR #27470:
URL: https://github.com/apache/superset/pull/27470#discussion_r1522006662


##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL
+        statement is likely ill-defined (due to the presence of the Jinja macros) and
+        thus non-parsable by SQLGlot.
+
+        Firstly, we extract any tables referenced within the confines of specific Jinja
+        macros. Secondly, we replace these non-SQL Jinja calls with a pseudo-benign SQL
+        expression to help ensure that the resulting SQL statements are parsable by
+        SQLGlot.
         """
+
+        from superset.jinja_context import (  # pylint: disable=import-outside-toplevel
+            get_template_processor,
+        )
+
+        tables = set()
+        sql = self.stripped()
+
+        # Mock the required database as the processor signature is exposed publically.
+        processor = get_template_processor(database=Mock(backend=self._dialect))
+        template = processor.env.parse(sql)
+
+        for node in template.find_all(nodes.Call):
+            if isinstance(node.node, nodes.Getattr) and node.node.attr in (

Review Comment:
   @michael-s-molina see https://github.com/apache/superset/pull/27464#issuecomment-1992376478.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #27470:
URL: https://github.com/apache/superset/pull/27470#issuecomment-1989722702

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/27470?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   All modified and coverable lines are covered by tests :white_check_mark:
   > Project coverage is 59.70%. Comparing base [(`b1adede`)](https://app.codecov.io/gh/apache/superset/commit/b1adede1ee670ad800c07aeb76f2f73799228960?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) to head [(`53a9687`)](https://app.codecov.io/gh/apache/superset/pull/27470?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   > Report is 1 commits behind head on master.
   
   
   <details><summary>Additional details and impacted files</summary>
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #27470      +/-   ##
   ==========================================
   - Coverage   67.36%   59.70%   -7.67%     
   ==========================================
     Files        1909     1909              
     Lines       74670    74683      +13     
     Branches     8324     8324              
   ==========================================
   - Hits        50304    44591    -5713     
   - Misses      22315    28041    +5726     
     Partials     2051     2051              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `53.68% <69.56%> (?)` | |
   | [python](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `62.37% <100.00%> (-15.89%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/27470/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.59% <95.65%> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/27470?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on code in PR #27470:
URL: https://github.com/apache/superset/pull/27470#discussion_r1520652745


##########
superset/jinja_context.py:
##########
@@ -479,11 +479,11 @@ def __init__(
         self._applied_filters = applied_filters
         self._removed_filters = removed_filters
         self._context: dict[str, Any] = {}
-        self._env = SandboxedEnvironment(undefined=DebugUndefined)

Review Comment:
   Given that this PR (and other logic) references `_env` I thought it should be made "public"—in Presto's pseudo public/private naming sense.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on PR #27470:
URL: https://github.com/apache/superset/pull/27470#issuecomment-2013332918

   @betodealmeida and @michael-s-molina I reopened this PR to address https://github.com/apache/superset/issues/27581 and now should be ready for review.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley merged PR #27470:
URL: https://github.com/apache/superset/pull/27470


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on code in PR #27470:
URL: https://github.com/apache/superset/pull/27470#discussion_r1521869662


##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL
+        statement is likely ill-defined (due to the presence of the Jinja macros) and
+        thus non-parsable by SQLGlot.
+
+        Firstly, we extract any tables referenced within the confines of specific Jinja
+        macros. Secondly, we replace these non-SQL Jinja calls with a pseudo-benign SQL
+        expression to help ensure that the resulting SQL statements are parsable by
+        SQLGlot.
         """
+
+        from superset.jinja_context import (  # pylint: disable=import-outside-toplevel
+            get_template_processor,
+        )
+
+        tables = set()
+        sql = self.stripped()
+
+        # Mock the required database as the processor signature is exposed publically.
+        processor = get_template_processor(database=Mock(backend=self._dialect))
+        template = processor.env.parse(sql)
+
+        for node in template.find_all(nodes.Call):
+            if isinstance(node.node, nodes.Getattr) and node.node.attr in (
+                "latest_partition",
+                "latest_sub_partition",
+            ):
+                # Extract the table referenced in the macro.
+                tables.add(
+                    Table(
+                        *[
+                            remove_quotes(part)
+                            for part in node.args[0].value.split(".")[::-1]
+                            if len(node.args) == 1
+                        ]
+                    )
+                )
+
+                # Replace the potentially problematic Jinja macro with benign SQL.
+                node.__class__ = nodes.TemplateData
+                node.fields = nodes.TemplateData.fields
+                node.data = "NULL"
+
+        sql = processor.process_template(template)
+
         try:
-            statements = parse(self.stripped(), dialect=self._dialect)
+            tables.update(
+                [
+                    table
+                    for statement in parse(sql, dialect=self._dialect)
+                    for table in self._extract_tables_from_statement(statement)
+                    if statement
+                ]
+            )
         except SqlglotError:
-            logger.warning("Unable to parse SQL (%s): %s", self._dialect, self.sql)
-            return set()
+            logger.warning("Unable to parse SQL (%s): %s", self._dialect, sql)

Review Comment:
   @michael-s-molina this case is being handled in @betodealmeida's https://github.com/apache/superset/pull/26748.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley commented on code in PR #27470:
URL: https://github.com/apache/superset/pull/27470#discussion_r1522006662


##########
superset/sql_parse.py:
##########
@@ -284,19 +286,64 @@ def _extract_tables_from_sql(self) -> set[Table]:
         Extract all table references in a query.
 
         Note: this uses sqlglot, since it's better at catching more edge cases.
+
+        Due to Jinja templating a multiphase approach is necessary as the referenced SQL
+        statement is likely ill-defined (due to the presence of the Jinja macros) and
+        thus non-parsable by SQLGlot.
+
+        Firstly, we extract any tables referenced within the confines of specific Jinja
+        macros. Secondly, we replace these non-SQL Jinja calls with a pseudo-benign SQL
+        expression to help ensure that the resulting SQL statements are parsable by
+        SQLGlot.
         """
+
+        from superset.jinja_context import (  # pylint: disable=import-outside-toplevel
+            get_template_processor,
+        )
+
+        tables = set()
+        sql = self.stripped()
+
+        # Mock the required database as the processor signature is exposed publically.
+        processor = get_template_processor(database=Mock(backend=self._dialect))
+        template = processor.env.parse(sql)
+
+        for node in template.find_all(nodes.Call):
+            if isinstance(node.node, nodes.Getattr) and node.node.attr in (

Review Comment:
   @michael-s-molina see https://github.com/apache/superset/pull/27464#issuecomment-1992376478. The templated SQL will be rendered and thus these macros will be evaluated.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(sql_parse): Ensure table extraction handles Jinja templating [superset]

Posted by "john-bodley (via GitHub)" <gi...@apache.org>.
john-bodley closed pull request #27470: fix(sql_parse): Ensure table extraction handles Jinja templating
URL: https://github.com/apache/superset/pull/27470


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org