Skip to content

fix(core): preserve declared T-SQL local variables - #940

Merged
cofin merged 2 commits into
litestar-org:mainfrom
abhishekrajv7-cmd:fix/declared-local-variables
Nov 27, 2026
Merged

cofin merged 2 commits into
litestar-org:mainfrom
abhishekrajv7-cmd:fix/declared-local-variables

Conversation

@abhishekrajv7-cmd

Copy link
Copy Markdown
Contributor

Summary

Fixes #939 by skipping @var identifiers declared via T-SQL DECLARE statements during parameter extraction so local variables are preserved as SQL rather than rewritten as bind placeholders.

Changes

  • Split T-SQL family dialects (tsql, mssql, sqlserver, sybase, ase, sqlanywhere) into _SCANNER_TSQL (still using BRACKET_PARAMETER_REGEX) in sqlspec/core/parameters/_validator.py.
  • Added _tsql_declared_variable_positions() (invoked for _SCANNER_TSQL and None dialects) to track @var names introduced by DECLARE statements outside string literals, comments, and quoted/bracketed identifiers, including multi-variable declarations, table variables, CASE initializers, and statement boundaries without semicolons, while keeping bind parameters in RHS initializers intact.
  • Added unit tests in tests/unit/core/parameters/test_tsql_declared_variables.py covering extraction, compilation, static script compilation, and mixed bind/local variable queries.

Verification

  • ruff check and ruff format --check passed on modified and added files.
  • mypy and pyright passed with 0 errors on sqlspec/core/parameters and tests/unit/core/parameters/test_tsql_declared_variables.py.
  • slotscheck passed on sqlspec/core/parameters.
  • pytest passed all 522 tests across tests/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, and test_statement_parameter_merge.py.

Closes #939

@cofin cofin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Existing test regression: tests/unit/core/test_parameters.py::test_non_snowflake_dialects_share_parameter_cache_entries expects sqlite and tsql to share one cache entry (size == 4). Splitting _SCANNER_TSQL into its own partition is the right design, so that test needs to be updated to expect size == 5.
  2. State machine drops real bind parameters after non-declaration declare: _TSQL_DECLARE_SCAN_REGEX ignores operators (=, +, <>, etc.) and numeric literals, and ( / ) clear expecting_decl_var without clearing in_declare. As a result, queries like SELECT * FROM t WHERE declare = @val, SELECT declare = @a, @b FROM t, or SELECT declare(1), @x FROM t silently swallow real bind parameters.
  3. Scope to _SCANNER_TSQL only (not dialect=None) & mirror BRACKET_PARAMETER_REGEX literals: Both SQLGlot (read=None raises ParseError on DECLARE @x int) and every other dialect-specific rule in ParameterValidator (MySQL SET @x, Snowflake @stage/$1, T-SQL [...], Oracle Q'...') require the dialect to be declared. Restricting this to normalized_dialect == _SCANNER_TSQL keeps dialect rules consistent, avoids leaking T-SQL behavior onto unknown dialects, and eliminates the backslash-escaping mismatch with PARAMETER_REGEX. Inside _TSQL_DECLARE_SCAN_REGEX, please also align literal skipping and flags with BRACKET_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.

Comment on lines +189 to +190
_BRACKET_STRING_DIALECTS: Final[frozenset[str]] = frozenset({"sqlite"})
_TSQL_STRING_DIALECTS: Final[frozenset[str]] = frozenset({"tsql", "mssql", "sqlserver", "sybase", "ase", "sqlanywhere"})

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) calls extract_parameters("SELECT ?", dialect="sqlite") and dialect="tsql" and asserts validator.cache_stats()["size"] == 4. With _SCANNER_TSQL, size is now 5.

Please update that test to reflect the new _SCANNER_TSQL partition (and verify that tsql/mssql/sybase share one entry while sqlite stays separate).

Comment on lines +259 to +273
_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,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are two related state-machine bugs here that cause non-declaration identifiers named declare to swallow real bind parameters:

  1. Untokenized operators/literals: _TSQL_DECLARE_SCAN_REGEX only captures at_var, word, and punct ([(),;]), silently skipping operators (=, +, <>, etc.) and numeric literals. Because DECLARE sets in_declare = True; expecting_decl_var = True anywhere at paren_depth == 0, expecting_decl_var stays True across 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-SQL alias = expr syntax) → drops both @a and @b ([])
    • SELECT declare + @offset FROM t → drops @offset ([])
  2. ( / ) don't exit in_declare when expecting_decl_var is True (lines 761–767):
    • SELECT declare(1), @x FROM t; → ( clears expecting_decl_var but leaves in_declare = True, so , after ) re-arms expecting_decl_var and drops @x ([]). Same for SELECT declare(a, b), @x, @y FROM t; (drops both @x and @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 the upper == "DECLARE" handling so SELECT 1 AS declare\nDECLARE @x int; still works.
  • Whenever expecting_decl_var is True, any non-comment token other than at_var (or word == "DECLARE" at paren_depth == 0)—including (, ), literals, and [^\s]—should reset both in_declare = False and expecting_decl_var = False (while still tracking paren_depth for ( / )).

Comment thread sqlspec/core/parameters/_validator.py Outdated
Comment on lines +481 to +482
elif normalized_dialect is None or normalized_dialect == _SCANNER_TSQL:
skipped_at_positions = _tsql_declared_variable_positions(sql)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please restrict this to elif normalized_dialect == _SCANNER_TSQL: (dropping normalized_dialect is None):

  1. Consistent with SQLGlot and SQLSpec dialect rules: SQLGlot itself requires dialect="tsql" to parse DECLARE @x int (read=None raises ParseError), and every other dialect-specific rule in ParameterValidator (MySQL SET @x = 1, Snowflake @stage/$1, T-SQL [...] brackets, Oracle Q'...') 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 its StatementConfig, and standalone SQL(...) callers can pass a T-SQL StatementConfig.
  2. Avoids leaking onto None / unknown dialects and lexical drift: Unknown dialects (like redshift) also resolve to None, and PARAMETER_REGEX (dialect=None) uses backslash-escaped quotes (\', \") while _TSQL_DECLARE_SCAN_REGEX does not—causing SELECT 'a\' DECLARE @x int; \'', @x to close the string early and drop the live @x.
  3. Mirror BRACKET_PARAMETER_REGEX literals and flags in _TSQL_DECLARE_SCAN_REGEX: Just as _MYSQL_ASSIGN_SCAN_REGEX mirrors MYSQL_PARAMETER_REGEX, _TSQL_DECLARE_SCAN_REGEX should skip the same literal forms as BRACKET_PARAMETER_REGEX (E'...', Q'[...]', and _DOLLAR_QUOTED_PATTERN) and compile with _REGEX_FLAGS (so E'/Q'/(?!sqlspec_) case-insensitivity and \\. match). Currently, under dialect="tsql", SELECT $$DECLARE @x int;$$, @x, SELECT E'a\' DECLARE @x int; \'', @x, and SELECT Q'[it's DECLARE @x int; it's]', @x all suppress the trailing @x.

Comment thread sqlspec/core/parameters/_validator.py Outdated
Comment on lines +772 to +797
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few minor edge cases in _tsql_declared_variable_positions:

  • Line 772 (elif in_declare and paren_depth == 0:): Guarding with and case_depth == 0 ensures a comma inside a CASE block can't re-arm expecting_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_PATTERNS and _MYSQL_ASSIGN_SCAN_REGEX.
  • GO batch boundaries (optional follow-up): driver.execute_script() splits on GO before 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 @x in declared_vars across GO. (If you add clearing on GO, only clear on a line-standalone GO so inline identifiers like SELECT go, @x FROM t aren't affected.)
  • _resolve_scanner docstring (lines 809–814): Worth a quick update to mention the bracket and T-SQL scanners.

Comment on lines +58 to +78
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good real-pipeline test structure here. Alongside the fixes above, could you update/add tests covering:

  1. Dialect-gating (dialect=None): Remove None from the line 12 parametrize list and the default_sql assertion at lines 76–78 (replacing with StatementConfig(dialect="tsql") if desired), and assert in test_extract_parameters_does_not_skip_declare_in_non_tsql_dialects that dialect=None preserves @x as bind parameters (matching sqlite and mysql).
  2. Shared-validator cache isolation: Reuse one ParameterValidator() instance on "DECLARE @x int; SELECT @x;" across "sqlite", "tsql", and None to verify _parameter_cache partitions cleanly.
  3. 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;, and SELECT 1 AS declare\nDECLARE @x int; SELECT @x;.
  4. BRACKET_PARAMETER_REGEX literal parity: SELECT $$DECLARE @x int;$$, @x and SELECT E'a\' DECLARE @x int; \'', @x under dialect="tsql".
  5. sqlanywhere compile coverage: Include sqlanywhere alongside mssql_python, pymssql, and sybase in test_compile_preserves_declared_tsql_local_variables since it's in _TSQL_STRING_DIALECTS.

@codecov-commenter

codecov-commenter commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.63014% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 84.98%. Comparing base (db26abd) to head (d9a13e3).

Files with missing lines Patch % Lines
sqlspec/core/parameters/_validator.py 98.63% 0 Missing and 1 partial ⚠️
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           
Flag Coverage Δ
cloud-adbc-storage 29.81% <12.32%> (-0.01%) ⬇️
integration 56.43% <57.53%> (-0.01%) ⬇️
mssql-db2 30.70% <54.79%> (+<0.01%) ⬆️
mysql-mariadb-embedded 38.02% <13.69%> (-0.02%) ⬇️
oracle 30.13% <9.58%> (-0.02%) ⬇️
postgres-cockroach 39.68% <10.95%> (-0.02%) ⬇️
py3.11 84.83% <98.63%> (+<0.01%) ⬆️
py3.12 84.84% <98.63%> (+<0.01%) ⬆️
py3.13 84.84% <98.63%> (+0.15%) ⬆️
py3.14 84.58% <98.63%> (+<0.01%) ⬆️
unit 82.35% <98.63%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
sqlspec/core/parameters/_validator.py 90.68% <98.63%> (+1.60%) ⬆️

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cofin
cofin merged commit 16b9fbd into litestar-org:main Nov 27, 2026
43 checks passed
cofin added a commit that referenced this pull request Nov 27, 2026
## 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: declared local variables are treated as bind parameters

3 participants