Repository navigation
fix(core): preserve declared T-SQL local variables - #940
Conversation
cofin
left a comment
There was a problem hiding this comment.
Thanks for tackling #939 — splitting T-SQL dialects into _SCANNER_TSQL for cache isolation and handling multi-variable / TABLE / CASE declarations is a clean foundation.
There are three blocking issues to address before merging:
- Existing test regression:
tests/unit/core/test_parameters.py::test_non_snowflake_dialects_share_parameter_cache_entriesexpectssqliteandtsqlto share one cache entry (size == 4). Splitting_SCANNER_TSQLinto its own partition is the right design, so that test needs to be updated to expectsize == 5. - State machine drops real bind parameters after non-declaration
declare:_TSQL_DECLARE_SCAN_REGEXignores operators (=,+,<>, etc.) and numeric literals, and(/)clearexpecting_decl_varwithout clearingin_declare. As a result, queries likeSELECT * FROM t WHERE declare = @val,SELECT declare = @a, @b FROM t, orSELECT declare(1), @x FROM tsilently swallow real bind parameters. - Scope to
_SCANNER_TSQLonly (notdialect=None) & mirrorBRACKET_PARAMETER_REGEXliterals: Both SQLGlot (read=NoneraisesParseErroronDECLARE @x int) and every other dialect-specific rule inParameterValidator(MySQLSET @x, Snowflake@stage/$1, T-SQL[...], OracleQ'...') require the dialect to be declared. Restricting this tonormalized_dialect == _SCANNER_TSQLkeeps dialect rules consistent, avoids leaking T-SQL behavior onto unknown dialects, and eliminates the backslash-escaping mismatch withPARAMETER_REGEX. Inside_TSQL_DECLARE_SCAN_REGEX, please also align literal skipping and flags withBRACKET_PARAMETER_REGEX.
I've left inline comments with reproducers and suggested fixes, plus a few minor edge-case and test suggestions. Please also run pytest tests/unit/core/test_parameters.py tests/unit/core/parameters/ -q after updating.
| _BRACKET_STRING_DIALECTS: Final[frozenset[str]] = frozenset({"sqlite"}) | ||
| _TSQL_STRING_DIALECTS: Final[frozenset[str]] = frozenset({"tsql", "mssql", "sqlserver", "sybase", "ase", "sqlanywhere"}) |
There was a problem hiding this comment.
Splitting T-SQL dialects out of _BRACKET_STRING_DIALECTS into _SCANNER_TSQL is the right call for cache isolation, but it breaks an existing test in tests/unit/core/test_parameters.py:
test_non_snowflake_dialects_share_parameter_cache_entries(lines 3367–3388) callsextract_parameters("SELECT ?", dialect="sqlite")anddialect="tsql"and assertsvalidator.cache_stats()["size"] == 4. With_SCANNER_TSQL,sizeis now5.
Please update that test to reflect the new _SCANNER_TSQL partition (and verify that tsql/mssql/sybase share one entry while sqlite stays separate).
| _TSQL_DECLARE_SCAN_REGEX: Final[re.Pattern[str]] = re.compile( | ||
| r""" | ||
| "(?:""|[^"])*(?:"|\Z) | | ||
| '(?:''|[^'])*(?:'|\Z) | | ||
| \[(?:\]\]|[^\]])*(?:\]|\Z) | | ||
| --[^\r\n]* | | ||
| /\*(?:[^*]|\*(?!/))*(?:\*/|\Z) | | ||
| @@[A-Za-z_]\w* | | ||
| \.[A-Za-z_][A-Za-z0-9_$]* | | ||
| (?P<at_var>(?<![A-Za-z0-9_])@(?!sqlspec_)\w+) | | ||
| (?P<word>[A-Za-z_][A-Za-z0-9_$]*) | | ||
| (?P<punct>[(),;]) | ||
| """, | ||
| re.VERBOSE, | ||
| ) |
There was a problem hiding this comment.
There are two related state-machine bugs here that cause non-declaration identifiers named declare to swallow real bind parameters:
- Untokenized operators/literals:
_TSQL_DECLARE_SCAN_REGEXonly capturesat_var,word, andpunct([(),;]), silently skipping operators (=,+,<>, etc.) and numeric literals. BecauseDECLAREsetsin_declare = True; expecting_decl_var = Trueanywhere atparen_depth == 0,expecting_decl_varstaysTrueacross operators:SELECT * FROM t WHERE declare = @val→ drops@val([])UPDATE t SET declare = @val WHERE id = @id→ drops@val(["@id"])SELECT declare = @a, @b FROM t(valid T-SQLalias = exprsyntax) → drops both@aand@b([])SELECT declare + @offset FROM t→ drops@offset([])
(/)don't exitin_declarewhenexpecting_decl_varisTrue(lines 761–767):SELECT declare(1), @x FROM t;→(clearsexpecting_decl_varbut leavesin_declare = True, so,after)re-armsexpecting_decl_varand drops@x([]). Same forSELECT declare(a, b), @x, @y FROM t;(drops both@xand@y).
In T-SQL, only whitespace and comments can appear between DECLARE (or a declaration-list ,) and @var. Suggested fix:
- Capture comments in a dedicated
(?P<comment>...)group (if group_name == "comment": continue), and append an uncaptured[^\s]catch-all at the end of_TSQL_DECLARE_SCAN_REGEX. - Guard the keyword branch explicitly with
if group_name == "word":(instead of an implicit fallthrough), keeping theupper == "DECLARE"handling soSELECT 1 AS declare\nDECLARE @x int;still works. - Whenever
expecting_decl_varisTrue, any non-comment token other thanat_var(orword == "DECLARE"atparen_depth == 0)—including(,), literals, and[^\s]—should reset bothin_declare = Falseandexpecting_decl_var = False(while still trackingparen_depthfor(/)).
| elif normalized_dialect is None or normalized_dialect == _SCANNER_TSQL: | ||
| skipped_at_positions = _tsql_declared_variable_positions(sql) |
There was a problem hiding this comment.
Please restrict this to elif normalized_dialect == _SCANNER_TSQL: (dropping normalized_dialect is None):
- Consistent with SQLGlot and SQLSpec dialect rules: SQLGlot itself requires
dialect="tsql"to parseDECLARE @x int(read=NoneraisesParseError), and every other dialect-specific rule inParameterValidator(MySQLSET @x = 1, Snowflake@stage/$1, T-SQL[...]brackets, OracleQ'...') only runs when its dialect is declared. Every T-SQL-family adapter (mssql_python,pymssql,sybase,sqlanywhere,arrow_odbc,adbc) already sets a T-SQL dialect on itsStatementConfig, and standaloneSQL(...)callers can pass a T-SQLStatementConfig. - Avoids leaking onto
None/ unknown dialects and lexical drift: Unknown dialects (likeredshift) also resolve toNone, andPARAMETER_REGEX(dialect=None) uses backslash-escaped quotes (\',\") while_TSQL_DECLARE_SCAN_REGEXdoes not—causingSELECT 'a\' DECLARE @x int; \'', @xto close the string early and drop the live@x. - Mirror
BRACKET_PARAMETER_REGEXliterals and flags in_TSQL_DECLARE_SCAN_REGEX: Just as_MYSQL_ASSIGN_SCAN_REGEXmirrorsMYSQL_PARAMETER_REGEX,_TSQL_DECLARE_SCAN_REGEXshould skip the same literal forms asBRACKET_PARAMETER_REGEX(E'...',Q'[...]', and_DOLLAR_QUOTED_PATTERN) and compile with_REGEX_FLAGS(soE'/Q'/(?!sqlspec_)case-insensitivity and\\.match). Currently, underdialect="tsql",SELECT $$DECLARE @x int;$$, @x,SELECT E'a\' DECLARE @x int; \'', @x, andSELECT Q'[it's DECLARE @x int; it's]', @xall suppress the trailing@x.
| elif in_declare and paren_depth == 0: | ||
| expecting_decl_var = True | ||
| continue | ||
| upper = lexeme.upper() | ||
| if expecting_decl_var: | ||
| if upper == "DECLARE" and paren_depth == 0: | ||
| in_declare = True | ||
| expecting_decl_var = True | ||
| case_depth = 0 | ||
| else: | ||
| in_declare = False | ||
| expecting_decl_var = False | ||
| elif upper == "DECLARE" and paren_depth == 0: | ||
| in_declare = True | ||
| expecting_decl_var = True | ||
| case_depth = 0 | ||
| elif in_declare and paren_depth == 0: | ||
| if upper == "CASE": | ||
| case_depth += 1 | ||
| elif upper == "END" and case_depth > 0: | ||
| case_depth -= 1 | ||
| elif upper == "ELSE" and case_depth > 0: | ||
| continue | ||
| elif upper in _TSQL_STATEMENT_BOUNDARY_KEYWORDS: | ||
| in_declare = False | ||
| case_depth = 0 |
There was a problem hiding this comment.
A few minor edge cases in _tsql_declared_variable_positions:
- Line 772 (
elif in_declare and paren_depth == 0:): Guarding withand case_depth == 0ensures a comma inside aCASEblock can't re-armexpecting_decl_var. - Lines 266 & 268 (
@@and@): Aligning@@[A-Za-z_]\w*→@@\w+and(?<![A-Za-z0-9_])→(?<![A-Za-z0-9_@])keeps parity with_PLACEHOLDER_PATTERNSand_MYSQL_ASSIGN_SCAN_REGEX. GObatch boundaries (optional follow-up):driver.execute_script()splits onGObefore extraction, so normal script execution is isolated per batch, but unsplit multi-batch calls (DECLARE @x int = 1; SELECT @x;\nGO\nSELECT * FROM users WHERE id = @x;) keep@xindeclared_varsacrossGO. (If you add clearing onGO, only clear on a line-standaloneGOso inline identifiers likeSELECT go, @x FROM taren't affected.)_resolve_scannerdocstring (lines 809–814): Worth a quick update to mention the bracket and T-SQL scanners.
| def test_extract_parameters_does_not_skip_declare_in_non_tsql_dialects() -> None: | ||
| validator = ParameterValidator() | ||
| sql = "DECLARE @x int; SELECT @x;" | ||
| assert [info.placeholder_text for info in validator.extract_parameters(sql, dialect="sqlite")] == ["@x", "@x"] | ||
| assert [info.placeholder_text for info in validator.extract_parameters(sql, dialect="mysql")] == ["@x", "@x"] | ||
|
|
||
|
|
||
| def test_compile_preserves_declared_tsql_local_variables() -> None: | ||
| sql = "DECLARE @x int; SET @x = 1; SELECT @x;" | ||
| for config in (mssql_python_config, pymssql_config, sybase_config): | ||
| compiled_sql, compiled_params = SQL(sql, statement_config=config).compile() | ||
| assert compiled_sql == sql | ||
| assert not compiled_params | ||
|
|
||
| script_sql, script_params = SQL(sql, statement_config=config).as_script().compile() | ||
| assert script_sql == sql | ||
| assert not script_params | ||
|
|
||
| default_sql, default_params = SQL(sql).compile() | ||
| assert default_sql == sql | ||
| assert not default_params |
There was a problem hiding this comment.
Good real-pipeline test structure here. Alongside the fixes above, could you update/add tests covering:
- Dialect-gating (
dialect=None): RemoveNonefrom the line 12 parametrize list and thedefault_sqlassertion at lines 76–78 (replacing withStatementConfig(dialect="tsql")if desired), and assert intest_extract_parameters_does_not_skip_declare_in_non_tsql_dialectsthatdialect=Nonepreserves@xas bind parameters (matchingsqliteandmysql). - Shared-validator cache isolation: Reuse one
ParameterValidator()instance on"DECLARE @x int; SELECT @x;"across"sqlite","tsql", andNoneto verify_parameter_cachepartitions cleanly. - State-machine regressions:
SELECT * FROM t WHERE declare = @val,UPDATE t SET declare = @val WHERE id = @id,SELECT declare = @a, @b FROM t,SELECT declare(1), @x FROM t;, andSELECT 1 AS declare\nDECLARE @x int; SELECT @x;. BRACKET_PARAMETER_REGEXliteral parity:SELECT $$DECLARE @x int;$$, @xandSELECT E'a\' DECLARE @x int; \'', @xunderdialect="tsql".sqlanywherecompile coverage: Includesqlanywherealongsidemssql_python,pymssql, andsybaseintest_compile_preserves_declared_tsql_local_variablessince it's in_TSQL_STRING_DIALECTS.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #940 +/- ##
=======================================
Coverage 84.98% 84.98%
=======================================
Files 643 643
Lines 143153 143222 +69
Branches 30824 30846 +22
=======================================
+ Hits 121652 121722 +70
+ Misses 14948 14947 -1
Partials 6553 6553
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
## Summary Prepare the `v0.74.2` patch release with dependency upgrades and changelog updates. ## Changes - Upgraded locked dependencies via `make upgrade` (`sqlglot` 30.35.0, `mssql-python` 1.18.0, `arrow-odbc` 10.7.1, `fastapi` 0.165.0, `ruff` 0.17.6, `prek` 0.5.11, `zensical` 0.1.2, and companion packages) and updated Prek hook revisions in `.pre-commit-config.yaml`. - Bumped package version from `0.74.1` to `0.74.2` via `make release bump=patch` (`pyproject.toml`, `uv.lock`). - Added the `v0.74.2` release entry to `docs/changelog.md` covering #939 / #940 and dependency updates. - Updated `tests/unit/core/test_compiler.py::test_unparsable_row_returning_statements_stay_non_read_only` to use a genuinely unparsable expression (`(SELECT FROM)`) now that `sqlglot` 30.35.0 parses PostgreSQL unary `@` (`(@ -5)`). ## Verification - `make docs` and `make build` passed via `make release bump=patch`. - `ruff check`, `ruff format --check`, `mypy`, `pyright`, `slotscheck`, and `zizmor` all passed with 0 errors. - Unit test suite verified against upgraded dependencies (`tests/unit/core/test_compiler.py`: 120 passed; core/builder/dialects/extensions/loader/adapters/driver/storage/utils suites passed).
Summary
Fixes #939 by skipping
@varidentifiers declared via T-SQLDECLAREstatements during parameter extraction so local variables are preserved as SQL rather than rewritten as bind placeholders.Changes
tsql,mssql,sqlserver,sybase,ase,sqlanywhere) into_SCANNER_TSQL(still usingBRACKET_PARAMETER_REGEX) insqlspec/core/parameters/_validator.py._tsql_declared_variable_positions()(invoked for_SCANNER_TSQLandNonedialects) to track@varnames introduced byDECLAREstatements outside string literals, comments, and quoted/bracketed identifiers, including multi-variable declarations, table variables,CASEinitializers, and statement boundaries without semicolons, while keeping bind parameters in RHS initializers intact.tests/unit/core/parameters/test_tsql_declared_variables.pycovering extraction, compilation, static script compilation, and mixed bind/local variable queries.Verification
ruff checkandruff format --checkpassed on modified and added files.mypyandpyrightpassed with 0 errors onsqlspec/core/parametersandtests/unit/core/parameters/test_tsql_declared_variables.py.slotscheckpassed onsqlspec/core/parameters.pytestpassed all 522 tests acrosstests/unit/core/parameters/test_tsql_declared_variables.py,test_declared.py,test_static_literals.py,test_declared_params_carriage.py,test_parameter_regex_performance.py,test_statement.py,test_declared_param_validation.py, andtest_statement_parameter_merge.py.Closes #939