Skip to content

fix(editor): confirm a DELETE or UPDATE inside a CTE before running it - #1451

Merged
NewtTheWolf merged 2 commits into
TabularisDB:mainfrom
parthchilwerwar:fix/guards-data-modifying-cte
Nov 10, 2026
Merged

NewtTheWolf merged 2 commits into
TabularisDB:mainfrom
parthchilwerwar:fix/guards-data-modifying-cte

Conversation

@parthchilwerwar

@parthchilwerwar parthchilwerwar commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

In PostgreSQL, a CTE body can itself be a data-modifying statement, and it runs even when the final statement is a SELECT:

WITH gone AS (DELETE FROM users RETURNING *)
SELECT count(*) FROM gone;

This deletes every row in users, and the editor runs it without asking. Both checks in sqlAnalysis.ts judge a WITH statement only by the keyword after its CTE list, here the SELECT:

  • classifyDangerousQuery returns null. On every connection that isn't marked production, Run without a WHERE clause? never appears.
  • isReadOnlyQuery returns true. On a production connection, the Production database prompt never appears either. That's the prompt useQueryGuards shows there instead of the WHERE one.

The same applies to UPDATE … SET … RETURNING and to INSERT or MERGE in a CTE body. The existing CTE tests only cover a final DELETE (WITH ids AS (SELECT …) DELETE FROM users), which is already handled.

Fix

A small cteBodies helper reads the text inside each AS (…) of a WITH statement, including AS [NOT] MATERIALIZED (…). Both checks now look at those bodies:

  • The production check (isReadOnlyQuery): a CTE body that starts with INSERT, UPDATE, DELETE or MERGE makes the statement a write. That also covers EXPLAIN ANALYZE WITH …, which really runs it.
  • The WHERE check (classifyDangerousQuery): a CTE body that runs DELETE or UPDATE without its own top-level WHERE is reported as no-where, the same as a top-level one. A WHERE in a subquery inside the body still doesn't count. A filtered DELETE or an INSERT in a body is not flagged.

PostgreSQL only allows data-modifying statements at the top level of a WITH, so one level of bodies is enough. Read-only CTEs are classified as before. That includes column lists (x(a) AS (…)), CAST(… AS numeric(10, 2)) inside a body, keywords inside string literals, and WITH RECURSIVE.

There's no matching classifier in src-tauri, so nothing changes on the backend.

Testing

  • tests/utils/sqlAnalysis.test.ts: four new tests.
    • The WHERE check: it flags DELETE or UPDATE without a WHERE in a body. That covers AS MATERIALIZED, a second CTE, and a WHERE that only appears in a USING subquery.
    • The WHERE check, other direction: it allows a filtered DELETE and an INSERT in a body.
    • isReadOnlyQuery writes: bodies with DELETE, UPDATE, INSERT and MERGE, plus EXPLAIN ANALYZE WITH …, are not read-only.
    • isReadOnlyQuery reads: read-only CTEs stay read-only.
  • Against main: the two "flags …" tests fail there for exactly the reported reason, and both pass with this change. The other two pass either way, which shows nothing new gets flagged.
  • Checks: pnpm typecheck passed. ESLint and Prettier passed on the changed files.
  • Full web-ui suite on Windows: 8,340 passed and 16 skipped. Three unrelated files failed during the full run: routing, EditorResultChart and QueryHistoryProviderPause. All three pass when run on their own on this branch. EditorResultChart mocks both guard hooks, so this change doesn't reach it.

How to try it

  1. On a PostgreSQL connection with no environment set, create and fill a scratch table in the SQL editor:

    CREATE TABLE cte_guard_demo (id int);
    INSERT INTO cte_guard_demo SELECT generate_series(1, 5);
  2. Run:

    WITH gone AS (DELETE FROM cte_guard_demo RETURNING *) SELECT count(*) FROM gone;

    On main it returns 5 straight away, and the table is empty. With this change, Run without a WHERE clause? appears first.

  3. Refill the table. Run WITH gone AS (DELETE FROM cte_guard_demo WHERE id = 1 RETURNING *) SELECT * FROM gone;. It runs without a prompt, because the DELETE is filtered.

  4. Edit the connection and set Environment to Production. Run the statement from step 2 again. On main it runs without a prompt. With this change, the Production database confirmation appears.

  5. Run WITH x AS (SELECT 1) SELECT * FROM x;. No prompt appears, on either connection type.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

In PostgreSQL a CTE body can be a data-modifying statement that runs even
when the final statement is a SELECT, as in
`WITH gone AS (DELETE FROM users RETURNING *) SELECT count(*) FROM gone`.
Both query guards judged a WITH statement only by its final keyword, so
this skipped the "Run without a WHERE clause?" prompt on every connection
and the production write prompt on production connections.

Read each CTE body: one that starts with INSERT, UPDATE, DELETE or MERGE
makes the statement a write, and a body that runs DELETE or UPDATE
without its own top-level WHERE is reported as no-where.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@kilo-code-bot

kilo-code-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: No Issues Found | Recommendation: Merge

The latest commit (ad15596) makes the CTE body pattern accept zero whitespace before the parenthesis (AS(, AS MATERIALIZED(, x(a)AS(), which resolves the earlier reviewer comments. The regex change is correct and the new tests cover both guards, including a filtered AS(DELETE ... WHERE ...) that stays allowed and a read-only AS(SELECT CAST(a AS integer) ...).

Files Reviewed (2 files)
  • packages/web-ui/src/utils/sqlAnalysis.ts
  • packages/web-ui/tests/utils/sqlAnalysis.test.ts
Previous Review Summary (commit 80272b2)

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

Previous review (commit 80272b2)

Status: No Issues Found | Recommendation: Merge

Files Reviewed (2 files)
  • packages/web-ui/src/utils/sqlAnalysis.ts
  • packages/web-ui/tests/utils/sqlAnalysis.test.ts

Reviewed by claude-sonnet-5.5 · Input: 246 · Output: 1.3K · Cached: 168.4K

Review guidance: REVIEW.md from base branch main

// not searched.
function cteBodies(cleaned: string): string[] {
const bodies: string[] = [];
const bodyStart = /\bAS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should this also match when there is no whitespace before the paren? Postgres accepts WITH gone AS(DELETE FROM users RETURNING *) SELECT count(*) FROM gone and deletes every row, but \s+ doesn't match AS( (or AS MATERIALIZED(), so cteBodies returns nothing and both isDestructiveWithoutWhere and isReadOnlyQuery treat it as a plain SELECT. I ran the PR's sqlAnalysis.ts against that query and got false / true. Maybe something like this, plus an AS( case in the tests?

Suggested change
const bodyStart = /\bAS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi;
const bodyStart = /\bAS\s*(?:NOT\s+)?(?:MATERIALIZED\s*)?\(/gi;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thank you. Applied your suggested pattern as-is in ad15596, with AS( and AS MATERIALIZED( cases in the tests for both guards.

@NewtTheWolf NewtTheWolf 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 for extending both query guards to inspect data-modifying CTE bodies. The 56 targeted tests pass, and the spaced AS (DELETE ...) example is detected correctly.

One valid PostgreSQL spelling still bypasses both guards: WITH gone AS(DELETE FROM cte_guard_demo RETURNING *) SELECT count(*) FROM gone;. On this revision, classifyDangerousQuery returns null and isReadOnlyQuery returns true. I confirmed PostgreSQL 17 accepts it and deletes all five rows in a disposable fixture. The new regular expression requires whitespace after AS, so it skips that body.

Please accept the punctuation-delimited AS( form and add DELETE/UPDATE regressions for both classifiers. This is a remaining gap in the bug being fixed, rather than a claim that the PR introduced the original unguarded execution.

// not searched.
function cteBodies(cleaned: string): string[] {
const bodies: string[] = [];
const bodyStart = /\bAS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi;

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.

[P1] Recognize AS( as a CTE body as well. PostgreSQL accepts WITH gone AS(DELETE FROM cte_guard_demo RETURNING *) SELECT count(*) FROM gone;, but \s+ skips the body, leaving classifyDangerousQuery(...) === null and isReadOnlyQuery(...) === true. An unfiltered DELETE therefore runs without either warning. Allow zero whitespace here and cover DELETE/UPDATE without a space in both guard tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for checking this against PostgreSQL 17, you're right. Fixed in ad15596: the CTE body pattern now allows no whitespace before the parenthesis, so AS(, AS MATERIALIZED(, AS NOT MATERIALIZED( and x(a)AS( are all read as bodies.

New regressions in both guard tests:

  • isDestructiveWithoutWhere flags AS(DELETE …), AS(UPDATE …), AS MATERIALIZED(UPDATE …) and lowercase as not materialized(delete …), and still allows a filtered AS(DELETE … WHERE id = 1 …).
  • isReadOnlyQuery returns false for AS(DELETE …), AS(UPDATE …), AS NOT MATERIALIZED(DELETE …) and x(a)AS(UPDATE …), while a read-only AS(SELECT CAST(a AS integer) …) stays read-only.

Both new tests fail on the previous commit and pass now. sqlAnalysis plus the guard hook tests pass (406), and typecheck, ESLint and Prettier are clean.

PostgreSQL also accepts `WITH gone AS(DELETE FROM t RETURNING *) SELECT 1`,
and `AS MATERIALIZED(`, with no whitespace before the parenthesis. The
CTE body pattern required whitespace after AS, so these bodies were not
read and both guards still let an unfiltered DELETE run. Allow zero
whitespace there and cover DELETE and UPDATE in both guard tests.

@NewtTheWolf NewtTheWolf 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 for adding the punctuation-delimited CTE cases. I rechecked ad15596, including AS(, AS MATERIALIZED(, AS NOT MATERIALIZED( and a column list immediately followed by AS(. Both guards now detect the writing bodies, while the read-only and filtered-write cases retain their expected behavior.

The 54 SQL-analysis tests, TypeScript check and targeted source lint pass. This resolves my previous blocker. Approved.

@NewtTheWolf
NewtTheWolf merged commit 39b34b1 into TabularisDB:main Nov 10, 2026
11 checks passed
@parthchilwerwar

Copy link
Copy Markdown
Contributor Author

Late thanks, @NewtTheWolf. The AS( spelling without a space was a good catch, I had only tried the spaced form. Thanks for rechecking the MATERIALIZED variants too.

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.

4 participants