Repository navigation
feat!: run every built-in Rule on SQLQuack's located syntax tree - #98
Merged
Merged
Conversation
All 53 built-in Rules now read the syntax tree SQLQuack records positions in, instead of scanning
tokens. The Rules live in `sqlclean-rules`, which depends on `sqlquack-syntax` alone: it can reach
no tokenizer or parser, and `make check-rust` fails if a dependency ever brings one in. A Rule is
handed the located statements and returns edits at tree positions, which the engine renders on the
SQL. The lint engine and its Rules came over from SQLQuack's `sqlquack-lint`, which SQLQuack no
longer ships; every test that came with them still passes unchanged.
Findings and fixes change as follows. Each change is pinned by a test case in
`crates/sqlclean-lint/src/lint/tests/test_rule_misreads.rs` or `test_rule_pins.rs`; an example is
given for each. Unless a dialect list is given, the example holds on Snowflake, DuckDB, PostgreSQL,
SQLite, BigQuery and Databricks.
SQLCLEAN001 (comparison with NULL)
- The fix writes valid SQL without spaces around the operator: `total=NULL` becomes
`total IS NULL` (it used to become `totalISNULL`), `total<>NULL` becomes `total IS NOT NULL`,
`total=(NULL)` and `total = (NULL)` become `total IS NULL`, and `(total=NULL)AND id>0` becomes
`(total IS NULL)AND id>0`. `total <> NULL` becomes `total IS NOT NULL`.
- No fix where NULL is followed by an operator: `total = NULL + 1` used to become `IS NULL + 1`.
SQLCLEAN002 (comma join)
- No finding for the comma before `TABLE(FLATTEN(...))`, `TABLE(SPLIT_TO_TABLE(...))` or a table
function over a window (Snowflake), a correlated `UNNEST(orders.items)` (DuckDB, PostgreSQL,
BigQuery), an array path `orders AS o, o.items` (BigQuery), a function in FROM such as
`jsonb_array_elements(o.items)` (PostgreSQL) or `generate_series(1, o.quantity)` (DuckDB,
PostgreSQL), the comma between named windows (`WINDOW w1 AS (...), w2 AS (...)`, DuckDB and
PostgreSQL), or a comma inside DECLARE CURSOR (DuckDB, SQLite; see below).
- A comma after a join is flagged: `FROM orders o JOIN customers c ON ..., regions r`, with no fix.
- No fix where an outer join follows, because JOIN binds tighter than the comma:
`FROM orders o, customers c RIGHT JOIN regions r ON ...`.
- The fix keeps names of one character and of multi-byte characters whole (`FROM a, b` and
`FROM a, 注文` become `a CROSS JOIN b` and `a CROSS JOIN 注文`), and is withheld over a comment
after the comma (Snowflake, PostgreSQL).
SQLCLEAN003 (join without a meaningful condition)
- No finding for `ASOF JOIN ... MATCH_CONDITION (...)` (Snowflake), `LEFT JOIN LATERAL (...) ON
TRUE` (PostgreSQL, DuckDB), or a join whose condition follows a nested join
(`JOIN customers c JOIN regions r ON ... ON o.customer_id = c.id`; it used to be flagged with a
fix).
- An always-true condition inside a parenthesised join is flagged:
`JOIN (customers c JOIN regions r ON TRUE) ON ...`.
- `STRAIGHT_JOIN` without a condition is flagged (Snowflake, DuckDB, SQLite).
SQLCLEAN004 (nondeterministic row selection)
- Flagged after a parenthesised set operation, `(SELECT ... UNION ALL SELECT ...) LIMIT 10`
(Snowflake, DuckDB), and after a star EXCEPT, `SELECT * EXCEPT (secret) FROM customers LIMIT 5`
(BigQuery, Databricks).
SQLCLEAN005 (unreachable CTE)
- Flagged and removed for a CTE with a column list, `WITH unused(a) AS (...) SELECT 1`, and where
only another schema's table has the CTE's name, `WITH paid AS (...) SELECT id FROM sales.paid`.
SQLCLEAN007 (positional set operation)
- No finding for multiplication in a branch (`qty * price AS amount`), a star EXCEPT
(BigQuery, Databricks), or a parenthesised branch beside a later CTE's star (Snowflake, DuckDB).
- Flagged for a written star over VALUES, `... UNION ALL SELECT * FROM VALUES (2)` (Snowflake),
TABLE branches, `TABLE orders UNION ALL TABLE returns` (PostgreSQL, BigQuery, Databricks), and
FROM-first branches, `FROM orders UNION ALL FROM returns` (DuckDB).
SQLCLEAN008 (bare UNION)
- A bare `UNION BY NAME` is flagged and fixed to `UNION DISTINCT BY NAME` (Snowflake, DuckDB).
- No finding for UNION as a type, `CAST(x AS UNION(a INT, b VARCHAR))` (Snowflake, DuckDB,
SQLite), whose fix broke the SQL.
SQLCLEAN009 (duplicated table alias)
- Flagged for an implicit alias used twice, `FROM orders x JOIN customers x` (Snowflake).
SQLCLEAN010 (duplicated output alias)
- No finding for quoted names that differ by case, `AS "a", AS "A"` (Snowflake, PostgreSQL).
SQLCLEAN011 (positional and named references mixed)
- No finding for an expression that starts with a number, `GROUP BY 1 + qty, region`.
SQLCLEAN012 (ELSE NULL)
- No finding for `ELSE NULL::VARCHAR` (Snowflake, DuckDB, PostgreSQL) or `ELSE NULL + 1`, whose
fix changed what the CASE returns.
- Flagged and fixed: `ELSE (NULL)`, and an `ELSE NULL` of a CASE inside a THEN.
- No fix over a comment inside the clause, `ELSE /* unknown */ NULL` (Snowflake, PostgreSQL).
SQLCLEAN013 (DISTINCT written as a function)
- No finding for `UNION DISTINCT (SELECT id FROM returns)` (all but SQLite).
SQLCLEAN014 (identical constants compared)
- No finding where arithmetic binds first, so no constants are compared: `qty - 1 = 1`,
`qty * 100 = 100`.
SQLCLEAN016 (expression aliased to its own name)
- Flagged where the dialect folds the name: `id AS "ID"` (Snowflake).
SQLCLEAN018 (ROW_NUMBER without ORDER BY)
- Flagged over a named window without an order, `ROW_NUMBER() OVER w ... WINDOW w AS (PARTITION BY
region)` (DuckDB, PostgreSQL), and when written with spaces, `ROW_NUMBER ( ) OVER (...)`.
- The finding covers the function's name as the tree records it. A typed window function whose
name the tree does not record, such as `LAST_VALUE(x ORDER BY x IGNORE NULLS) OVER (...)`
(Snowflake, DuckDB, SQLite), is reported over its whole call and window instead of a range
computed from the name's length.
SQLCLEAN019 (NULL in NOT IN)
- Flagged with NOT before the column, `WHERE NOT status IN (1, NULL)`.
SQLCLEAN020 (column counts of set-operation branches)
- No finding for `UNION ALL BY NAME` (Snowflake, DuckDB), ORDER BY commas in a last branch without
FROM, another CTE's columns counted for a branch (Snowflake, DuckDB), or `COLUMNS('a.*')`
(DuckDB).
- Flagged for parenthesised branches, `(SELECT a, b FROM x) UNION ALL (SELECT c FROM y)`
(Snowflake, DuckDB, PostgreSQL), and where a multiplication hid the count,
`SELECT a * 2 AS a, b FROM t UNION ALL SELECT c FROM u`.
SQLCLEAN021 (uncontrolled column shape)
- A qualified star with modifiers is reported over the whole item, `o . * EXCEPT (total)`
(Snowflake, DuckDB, BigQuery, Databricks); the position of its asterisk is no longer computed
from the qualifier's length.
SQLCLEAN022 (unaliased calculation)
- No finding for a fully qualified column, `SELECT sales.orders.id` (Snowflake, DuckDB,
PostgreSQL).
- Flagged inside a SQLite trigger program, `CREATE TRIGGER r ... BEGIN SELECT 1 + 1; END` (SQLite).
SQLCLEAN023 (table alias never referenced)
- No removal in a self-join with USING, `FROM orders o JOIN orders p USING (id)`, where both
names are needed apart (Snowflake, DuckDB, PostgreSQL); both are still reported.
- An unused quoted LATERAL alias with a doubled quote, `LATERAL FLATTEN(input => s.items) "a""b"`
(Snowflake) or `LATERAL generate_series(1, 2) "a""b"` (PostgreSQL), is reported over `"a""b"`
and removed whole; the old fix left a stray quote.
SQLCLEAN024 (WHERE undoing a LEFT JOIN)
- No finding for a predicate in QUALIFY (Snowflake) or HAVING (Snowflake, PostgreSQL).
SQLCLEAN025 (implicit JOIN type)
- No finding for `INNER DIRECTED JOIN`, whose fix wrote `INNER DIRECTED INNER JOIN` (Snowflake).
SQLCLEAN026 (explicit and implicit ORDER BY directions mixed)
- Judged by direction, not by NULLS: `ORDER BY region DESC NULLS LAST, id DESC` is no longer
flagged, and `ORDER BY region DESC NULLS LAST, id` is (Snowflake, DuckDB, PostgreSQL).
SQLCLEAN027 and SQLCLEAN028 (unqualified and mixed-qualification columns)
- Columns inside calls are read: `SUM(total)` in a join, and `ABS(total)` beside `o.id`, are
flagged.
SQLCLEAN029 (qualifier names no relation in scope)
- No finding for a schema-qualified function, `util.parse_day(raw)` (all but SQLite).
SQLCLEAN030 (CASE that only converts a condition to TRUE or FALSE)
- Flagged and fixed with a CASE inside the condition:
`CASE WHEN CASE WHEN a = 1 THEN 1 END = 1 THEN TRUE ELSE FALSE END` becomes
`COALESCE(CASE WHEN a = 1 THEN 1 END = 1, FALSE)`.
- No fix over a `//` comment (Snowflake) or a `#` comment (BigQuery), which commented out the end
of the rewrite.
SQLCLEAN031 (CASE nested directly inside ELSE)
- Flagged for `ELSE (CASE ... END)`; no finding where the CASE is only part of the ELSE value,
`ELSE CASE ... END + 1`.
SQLCLEAN032 (joined relation contributes no referenced values)
- A keyword argument such as `DATEADD(day, 1, ...)` in the select list no longer turns the Rule off
(Snowflake).
SQLCLEAN034 and SQLCLEAN035 (logic outside top-level CTEs; terminal SELECT)
- No finding for a terminal `SELECT * EXCEPT (x) FROM final` (BigQuery, Databricks).
SQLCLEAN036 (CTE nested inside another query)
- No finding for `WITH OFFSET` (BigQuery), `WITH ORDINALITY` and `WITH TIES` (PostgreSQL), or the
CTEs of a view or insert query, `CREATE VIEW v AS WITH c AS (...) SELECT ...` and
`INSERT INTO t (id) WITH c AS (...) SELECT ...` (Snowflake, DuckDB, PostgreSQL).
SQLCLEAN041 (CTE named final)
- The CTEs before a VALUES statement are read, `WITH a AS (SELECT 1) VALUES (1)` (DuckDB, SQLite,
PostgreSQL).
SQLCLEAN042 (CTE column never read)
- Read in a root set operation's CTEs, and fixed (Snowflake, DuckDB).
SQLCLEAN047 (CASE WHEN NULL or IN (NULL))
- Flagged for `IN (NULL, NULL)`.
SQLCLEAN048 (division by a literal zero)
- No finding for a stage path ending in zero, `FROM @stage/2024/0` (Snowflake).
Across a corpus of 66,525 statements from PostgreSQL's and sqllogictest's test suites, sqlglot's
fixtures and SQLQuack's and SQLClean's own tests, read on all six dialects against the previous
engine, the same causes account for every other changed finding. Every changed finding was read.
The 14,448 statements that cover each change and each kind of result are now a CI test:
`crates/sqlclean-lint/src/lint/tests/fixtures/` holds them, the findings accepted for each
dialect and their sources' notices. A change to any finding fails the test until it is accepted
with `make accept-lint-corpus`, so a SQLQuack bump shows every finding it moves.
Where SQL is kept as text, Rules stay silent. A DECLARE CURSOR body on DuckDB and SQLite, and a
trigger body on DuckDB and Snowflake, stay text: none of those engines parses them as SQL. The
previous engine reported findings inside them, across the corpus 002 3 times, 004 5, 021 37,
022 7, 025 1, 027 2, 028 1, 034 46, 035 1, 036 1, 039 1 and 048 1 inside DECLARE CURSOR, and 022
and 034 6 times each inside triggers; those are no longer reported. PostgreSQL's DECLARE CURSOR
body and SQLite's trigger programs, which their engines run, are read and linted.
`SELECT 1 AS ''` on DuckDB is reported by 022: DuckDB itself treats `AS ''` as no alias.
BREAKING CHANGE: findings and fixes of the built-in Rules change as listed above, so a CI step
that compares SQLClean's output, or an allowlist of findings, needs updating. SQLClean now builds
on SQLQuack's located trees, which needs the SQLQuack release that removes `sqlquack-lint` and
moves its tokenizer into `sqlquack-tokenize`.
Deploying sqlclean with
|
| Latest commit: |
c430a94
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://f494728c.sqlclean.pages.dev |
| Branch Preview URL: | https://feat-located-tree-rules.sqlclean.pages.dev |
Git for Windows checks text out with CRLF by default, so the Windows job read lint_corpus_accepted.tsv with a carriage return on every line and saw all 86,688 accepted lines changed. The fixtures are read byte for byte, so .gitattributes now pins everything under tests/fixtures to LF.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Why
Rules scanned tokens and misread SQL whose structure the scan could not see: commas before table functions read as cartesian joins,
qty - 1 = 1read as constants compared, broken fixes such astotalISNULLfromtotal=NULL. SQLQuack 0.23.0 records every position a Rule needs in its located tree, so the Rules can read structure instead of guessing it.Changes
sqlclean-rules, which depends onsqlquack-syntaxalone;make check-rustfails if that crate ever reaches a tokenizer or parser.test_rule_misreads.rsortest_rule_pins.rsand listed in the commit message.make accept-lint-corpusaccepts a reviewed change.7a8501a).BREAKING CHANGE: built-in Rules' findings and fixes change as listed in the commit message.
Verification
make verify(check-ci incl. fensu, check-docs-skill, check-rust;cargo test --all; pytest, 95 passed) on the same tree with SQLQuack's gated pre-release commit.cargo test --locked --workspacepassed, corpus test included.cargo +1.88.0 check --workspace --all-targets --locked, clippy on 1.95.0,make release-rehearsalwith uv 0.12.9.