You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2026/03/17 16:13:36 UTC

(superset) branch sqlite-syntax-validation created (now ec36fd27cde)

This is an automated email from the ASF dual-hosted git repository.

beto pushed a change to branch sqlite-syntax-validation
in repository https://gitbox.apache.org/repos/asf/superset.git


      at ec36fd27cde feat(sqllab): syntax validation for sqlite-based DB engine specs

This branch includes the following new commits:

     new ec36fd27cde feat(sqllab): syntax validation for sqlite-based DB engine specs

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(superset) 01/01: feat(sqllab): syntax validation for sqlite-based DB engine specs

Posted by be...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

beto pushed a commit to branch sqlite-syntax-validation
in repository https://gitbox.apache.org/repos/asf/superset.git

commit ec36fd27cdee44d481c5362ac7fc6d37c314cbab
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Tue Mar 17 12:13:17 2026 -0400

    feat(sqllab): syntax validation for sqlite-based DB engine specs
---
 pyproject.toml                                 |   3 +-
 requirements/base.txt                          |   2 +
 requirements/development.txt                   |   4 +
 superset/sql_validators/__init__.py            |   3 +-
 superset/sql_validators/sqlite.py              | 109 +++++++++++++++++++++
 tests/unit_tests/sql_validators/sqlite_test.py | 126 +++++++++++++++++++++++++
 6 files changed, 245 insertions(+), 2 deletions(-)

diff --git a/pyproject.toml b/pyproject.toml
index 12d5224cb38..575865f5079 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -83,6 +83,7 @@ dependencies = [
     "paramiko>=3.4.0",
     "pgsanity",
     "Pillow>=11.0.0, <13",
+    "syntaqlite>=0.1.0",
     "polyline>=2.0.0, <3.0",
     "pydantic>=2.8.0",
     "pyparsing>=3.0.6, <4",
@@ -238,7 +239,7 @@ combine_as_imports = true
 include_trailing_comma = true
 line_length = 88
 known_first_party = "superset, apache-superset-core, apache-superset-extensions-cli"
-known_third_party = "alembic, apispec, backoff, celery, click, colorama, cron_descriptor, croniter, cryptography, dateutil, deprecation, flask, flask_appbuilder, flask_babel, flask_caching, flask_compress, flask_jwt_extended, flask_login, flask_migrate, flask_sqlalchemy, flask_talisman, flask_testing, flask_wtf, freezegun, geohash, geopy, holidays, humanize, isodate, jinja2, jwt, markdown, markupsafe, marshmallow, marshmallow-union, msgpack, nh3, numpy, pandas, parameterized, parsedateti [...]
+known_third_party = "alembic, apispec, backoff, celery, click, colorama, cron_descriptor, croniter, cryptography, dateutil, deprecation, flask, flask_appbuilder, flask_babel, flask_caching, flask_compress, flask_jwt_extended, flask_login, flask_migrate, flask_sqlalchemy, flask_talisman, flask_testing, flask_wtf, freezegun, geohash, geopy, holidays, humanize, isodate, jinja2, jwt, markdown, markupsafe, marshmallow, marshmallow-union, msgpack, nh3, numpy, pandas, parameterized, parsedateti [...]
 multi_line_output = 3
 order_by_type = false
 
diff --git a/requirements/base.txt b/requirements/base.txt
index 240cf7d4eb1..5e0afea2d61 100644
--- a/requirements/base.txt
+++ b/requirements/base.txt
@@ -410,6 +410,8 @@ sqlglot==28.10.0
     #   apache-superset-core
 sshtunnel==0.4.0
     # via apache-superset (pyproject.toml)
+syntaqlite==0.1.0
+    # via apache-superset (pyproject.toml)
 tabulate==0.9.0
     # via apache-superset (pyproject.toml)
 trio==0.30.0
diff --git a/requirements/development.txt b/requirements/development.txt
index 2b9fffd474b..d0348897367 100644
--- a/requirements/development.txt
+++ b/requirements/development.txt
@@ -992,6 +992,10 @@ starlette==0.49.1
     # via mcp
 statsd==4.0.1
     # via apache-superset
+syntaqlite==0.1.0
+    # via
+    #   -c requirements/base-constraint.txt
+    #   apache-superset
 tabulate==0.9.0
     # via
     #   -c requirements/base-constraint.txt
diff --git a/superset/sql_validators/__init__.py b/superset/sql_validators/__init__.py
index 0298cf32edb..2bc1170a934 100644
--- a/superset/sql_validators/__init__.py
+++ b/superset/sql_validators/__init__.py
@@ -16,7 +16,7 @@
 # under the License.
 from typing import Optional
 
-from . import base, postgres, presto_db
+from . import base, postgres, presto_db, sqlite
 from .base import SQLValidationAnnotation  # noqa: F401
 
 
@@ -24,4 +24,5 @@ def get_validator_by_name(name: str) -> Optional[type[base.BaseSQLValidator]]:
     return {
         "PrestoDBSQLValidator": presto_db.PrestoDBSQLValidator,
         "PostgreSQLValidator": postgres.PostgreSQLValidator,
+        "SQLiteSQLValidator": sqlite.SQLiteSQLValidator,
     }.get(name)
diff --git a/superset/sql_validators/sqlite.py b/superset/sql_validators/sqlite.py
new file mode 100644
index 00000000000..f8f283bfb04
--- /dev/null
+++ b/superset/sql_validators/sqlite.py
@@ -0,0 +1,109 @@
+# 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 __future__ import annotations
+
+import logging
+import re
+import subprocess
+
+from syntaqlite import get_binary_path
+
+from superset.models.core import Database
+from superset.sql_validators.base import BaseSQLValidator, SQLValidationAnnotation
+
+logger = logging.getLogger(__name__)
+
+DIAGNOSTIC_RE = re.compile(
+    r"^(?:error|warning): (.+)\n"
+    r" --> .+?:(\d+):(\d+)\n"
+    r" +\|\n"
+    r"\d+ \| .+\n"
+    r" +\| +\^(~*)",
+    re.MULTILINE,
+)
+
+
+class SQLiteSQLValidator(BaseSQLValidator):  # pylint: disable=too-few-public-methods
+    """Validate SQL queries using the syntaqlite binary"""
+
+    name = "SQLiteSQLValidator"
+
+    @classmethod
+    def validate(
+        cls,
+        sql: str,
+        catalog: str | None,
+        schema: str | None,
+        database: Database,
+    ) -> list[SQLValidationAnnotation]:
+        annotations: list[SQLValidationAnnotation] = []
+
+        try:
+            result = subprocess.run(  # noqa: S603
+                [
+                    get_binary_path(),
+                    "--no-config",
+                    "validate",
+                    "--allow",
+                    "schema",
+                    "-e",
+                    sql,
+                ],
+                capture_output=True,
+                text=True,
+                timeout=10,
+            )
+        except FileNotFoundError:
+            logger.exception("syntaqlite binary not found")
+            raise
+        except subprocess.TimeoutExpired:
+            logger.warning("syntaqlite timed out validating SQL")
+            return annotations
+
+        if result.returncode == 0:
+            return annotations
+
+        output = result.stderr or result.stdout
+        for match in DIAGNOSTIC_RE.finditer(output):
+            message = match.group(1)
+            line_number = int(match.group(2))
+            start_column = int(match.group(3))
+            # The caret (^) plus tildes (~) span the error token
+            end_column = start_column + len(match.group(4))
+
+            annotations.append(
+                SQLValidationAnnotation(
+                    message=message,
+                    line_number=line_number,
+                    start_column=start_column,
+                    end_column=end_column,
+                )
+            )
+
+        # If we couldn't parse the output but got a non-zero exit, add a generic error
+        if not annotations and result.returncode != 0:
+            annotations.append(
+                SQLValidationAnnotation(
+                    message=output.strip() or "SQL syntax validation failed",
+                    line_number=None,
+                    start_column=None,
+                    end_column=None,
+                )
+            )
+
+        return annotations
diff --git a/tests/unit_tests/sql_validators/sqlite_test.py b/tests/unit_tests/sql_validators/sqlite_test.py
new file mode 100644
index 00000000000..181b83fbfcb
--- /dev/null
+++ b/tests/unit_tests/sql_validators/sqlite_test.py
@@ -0,0 +1,126 @@
+# 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 __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from superset.sql_validators.sqlite import SQLiteSQLValidator
+
+
+def test_valid_syntax() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="SELECT 1, col FROM my_table",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert annotations == []
+
+
+def test_invalid_syntax_single_error() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="SELEC * FROM foo",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert len(annotations) == 1
+    annotation = annotations[0]
+    assert annotation.line_number == 1
+    assert annotation.start_column == 1
+    assert "SELEC" in annotation.message
+
+
+def test_invalid_syntax_multiple_errors() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="SELEC * FROM foo; SELEC * FROM bar",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert len(annotations) >= 1
+    # First error should reference SELEC
+    assert "SELEC" in annotations[0].message
+
+
+def test_multiline_error_reports_correct_line() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="SELECT 1;\nSELEC * FROM foo",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert len(annotations) == 1
+    assert annotations[0].line_number == 2
+
+
+def test_empty_sql() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert annotations == []
+
+
+def test_valid_complex_query() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql=(
+            "SELECT a, COUNT(*) AS cnt "
+            "FROM my_table "
+            "WHERE b > 10 "
+            "GROUP BY a "
+            "HAVING cnt > 1 "
+            "ORDER BY cnt DESC "
+            "LIMIT 100"
+        ),
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert annotations == []
+
+
+def test_annotation_to_dict() -> None:
+    mock_database = MagicMock()
+    annotations = SQLiteSQLValidator.validate(
+        sql="SELEC * FROM foo",
+        catalog=None,
+        schema="",
+        database=mock_database,
+    )
+    assert len(annotations) == 1
+    result = annotations[0].to_dict()
+    assert "line_number" in result
+    assert "start_column" in result
+    assert "end_column" in result
+    assert "message" in result
+
+
+def test_get_validator_by_name() -> None:
+    from superset.sql_validators import get_validator_by_name
+
+    validator = get_validator_by_name("SQLiteSQLValidator")
+    assert validator is SQLiteSQLValidator