Skip to content

fix(explain): default Analyze off for every data-modifying statement - #900

Merged
debba merged 2 commits into
TabularisDB:mainfrom
TonyWu2333:fix/explain-data-modifying-detection
Oct 8, 2026
Merged

debba merged 2 commits into
TabularisDB:mainfrom
TonyWu2333:fix/explain-data-modifying-detection

Conversation

@TonyWu2333

Copy link
Copy Markdown

Closes #884

Problem

Visual Explain turns Analyze on by default unless isDataModifyingQuery says the statement writes. That function only checked whether the trimmed, upper-cased text started with INSERT/UPDATE/DELETE/DROP/ALTER/TRUNCATE, so these were treated as read-only, got ANALYZE ticked with no warning, and were actually executed when the plan was fetched:

  • REPLACE INTO … and MERGE INTO …
  • data-modifying CTEs, e.g. WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d
  • any write statement preceded by a comment (-- note\nDELETE …)

Fix

In src/utils/sql.ts, isDataModifyingQuery now:

  • reads the first keyword with the existing leadingKeyword helper from sqlSplitter/classify.ts, which already skips leading comments and parentheses (sqlAnalysis.ts imports it the same way);
  • checks it against a wider set: INSERT, UPDATE, DELETE, MERGE, REPLACE, UPSERT, TRUNCATE, CREATE, DROP, ALTER, GRANT, REVOKE, CALL, EXEC, EXECUTE;
  • for WITH, looks for a whole-word INSERT/UPDATE/DELETE/MERGE anywhere outside string literals and comments. Strings and comments are masked with maskNonCode from queryParameters.ts (now exported). The hook doesn't know the connection's dialect, so the text is masked twice, with the generic rules and the MySQL rules, and a match under either one counts. The two disagree on backslash escapes ('it\'s'), and each can misread where the other's literal ends and hide a keyword.

The callers (useExplainAnalyze, and through it VisualExplainModal and the notebook explain cell) are unchanged; they already default Analyze off and show the existing warning when this returns true.

Trade-offs

The CTE check is a keyword scan, not a parser, so it errs towards "modifies data". For example, a read-only CTE with a FOR UPDATE locking clause, or an unquoted identifier that happens to be named like one of those keywords, now defaults Analyze off. The user can still tick it, so I preferred that over executing a write by accident. REPLACE is deliberately not part of the CTE scan so the replace() string function in a read-only query is not flagged.

Testing

Added cases to tests/utils/sql.test.ts for each statement type above, their lowercase and leading-comment variants, data-modifying CTEs (in a CTE body and as the main statement), write keywords inside strings/comments/quoted identifiers that must not count, the MySQL backslash-escape case, and read-only SELECT / WITH … SELECT / TABLE / parenthesized UNION that must still default to Analyze on. The 24 new positive cases fail on main and pass with this change.

  • pnpm test (vitest run): 329 files, 5169 tests passed
  • pnpm typecheck and tsc -p tsconfig.app.json --noEmit: clean
  • pnpm lint: clean

No Rust changes.

isDataModifyingQuery only checked the first keyword after trimming
whitespace, so REPLACE, MERGE, data-modifying CTEs and statements behind
a leading comment were treated as read-only. Visual Explain then turned
ANALYZE on by default and really executed them.

Read the leading keyword with leadingKeyword (which skips comments and
parentheses), widen the keyword set, and for WITH look for INSERT,
UPDATE, DELETE or MERGE outside strings and comments.

Closes TabularisDB#884
@kilo-code-bot

kilo-code-bot Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Files Reviewed (2 files)
  • src/utils/sql.ts - masks with the union of all six dialects (postgres dollar-quoting/E-strings, MySQL backslash escapes, T-SQL bracket identifiers, Oracle q-quoting), adds SELECT ... INTO detection, and documents the side-effecting-function limitation; addresses the CHANGES_REQUESTED review feedback (dollar quoting, E-strings, brackets, SELECT INTO, docblock note)
  • tests/utils/sql.test.ts - 12 new cases: cross-dialect literal regressions from review feedback, SELECT ... INTO variants, and read-only negatives (string literal, comment, partial-identifier words)
Previous Review Summary (commit 61dba51)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 61dba51)

Status: No Issues Found | Recommendation: Merge

Files Reviewed (3 files)
  • src/utils/queryParameters.ts - 1 change (export maskNonCode)
  • src/utils/sql.ts - isDataModifyingQuery rewrite (leadingKeyword, widened keyword set, CTE scan)
  • tests/utils/sql.test.ts - 24 new test cases

Reviewed by free · Input: 73.4K · Output: 11.1K · Cached: 255.7K

@debba debba left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hey @TonyWu2333, thank you for picking this up! This is a real safety issue and your approach is a big step up from main: routing through leadingKeyword, catching REPLACE/MERGE/UPSERT, CTE writes, comments and lowercase, and keeping string literals out of it. The full suite is green on your branch (5169 tests).

There's one thing I need fixed before merging though, because it's exactly the failure this PR is meant to prevent.

isDataModifyingQuery (src/utils/sql.ts:55) masks only with the generic and mysql dialects. Neither lexes Postgres dollar quoting, E-strings or T-SQL [bracket] identifiers, so an apostrophe inside one of those opens a fake string that runs to the end of the text and hides the write keyword. All of these return false on your branch:

WITH c AS (SELECT $$it's$$ AS a) DELETE FROM t
WITH c AS (SELECT $tag$don't$tag$ AS a) UPDATE t SET a = 1
WITH c AS (SELECT E'\'' AS a, 'C:\' AS b) DELETE FROM t WHERE x = 'y'
WITH c AS (SELECT 1 AS [it's]) DELETE FROM t

I tried the first one on a local Postgres 16: Analyze is on by default, and EXPLAIN ANALYZE really deleted the rows.

The simplest fix is to take the union over every dialect the splitter knows (postgres, mysql, mssql, sqlite, oracle, generic): each dialect lexes its own text correctly, so the keyword stays visible under at least the real one. Alternatively you could pass the connection's driver into the hook (VisualExplainModal already computes effectiveDriver). Either way, please add the four cases above as regression tests.

Non-blocking notes:

  1. SELECT ... INTO new_table (and WITH ... SELECT ... INTO) is still not detected, and on Postgres EXPLAIN ANALYZE does create the table. It was already broken on main, so fine as a follow-up, but then the title "every data-modifying statement" is a bit too broad.
  2. useExplainPlan rejects anything outside EXPLAINABLE_KEYWORDS, so CREATE/GRANT/REVOKE/CALL/EXEC in the new keyword set can never reach this check. Harmless, just dead entries.
  3. A one-line note in the docblock that side-effecting functions (SELECT nextval(...), SELECT fn_that_deletes()) can't be detected would set expectations.

Since this is your first contribution to Tabularis: this week there's a giveaway on our Discord with 3 Claude seats in our Claude Team up for grabs. If you'd like to join, you're very welcome: https://discord.com/invite/K2hmhfHRSt

The write scan masked strings only under the generic and MySQL rules,
which lex neither Postgres dollar quoting and E-strings nor T-SQL bracket
identifiers. An apostrophe inside one of those opened a string that ran to
the end of the text and hid the write, so EXPLAIN ANALYZE executed it.
Mask under every dialect the splitter knows and count a match under any
of them: the real dialect always lexes its own literals.

Also treat SELECT ... INTO as a write, since it creates the target table,
and note that side-effecting functions are not detected.
@TonyWu2333

Copy link
Copy Markdown
Author

Thanks for the thorough review and the repro on Postgres, that one was a real miss.

Pushed 86967a5:

  • isDataModifyingQuery now masks under every dialect the splitter knows (postgres, mysql, mssql, sqlite, oracle, generic) and counts a match under any of them. Your four cases are in as regression tests, and they fail without the change.
  • (1) SELECT ... INTO and WITH ... SELECT ... INTO are now detected, so the title holds. The union can flag a few read-only statements, such as SELECT $$ into $$ under MySQL rules. That only turns the Analyze default off, which is the safe side.
  • (3) Added the note about side-effecting functions to the docblock.
  • (2) I left DROP/ALTER/TRUNCATE and the rest in the set. main already had the first three, and the helper answers a general "does this change data" question. Happy to trim it to the explainable writes if you'd prefer.

@debba debba left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks a lot @TonyWu2333, that was quick! I re-checked 86967a5: the four cases from my review, plus SELECT ... INTO and WITH ... SELECT ... INTO, are all detected now, the full suite is green (5181/5181), and typecheck and lint are clean.

One tiny observation, not blocking: since a match under any dialect counts, something like SELECT $$ into $$ FROM t is now flagged as modifying (non-Postgres lexers don't know dollar quoting). That only means Analyze starts unchecked, which is the safe direction, so I'm happy with the trade-off.

Approving. I'll run some e2e tests shortly to verify it directly.

@debba
debba merged commit 0c00a4a into TabularisDB:main Oct 8, 2026
1 check 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]: Visual Explain enables ANALYZE by default for REPLACE, MERGE and data-modifying CTEs

2 participants