Repository navigation
fix(editor): confirm a DELETE or UPDATE inside a CTE before running it - #1451
Conversation
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.
There was a problem hiding this comment.
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.
Code Review SummaryStatus: No Issues Found | Recommendation: Merge The latest commit ( Files Reviewed (2 files)
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)
Reviewed by claude-sonnet-5.5 · Input: 246 · Output: 1.3K · Cached: 168.4K Review guidance: REVIEW.md from base branch |
| // not searched. | ||
| function cteBodies(cleaned: string): string[] { | ||
| const bodies: string[] = []; | ||
| const bodyStart = /\bAS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi; |
There was a problem hiding this comment.
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?
| const bodyStart = /\bAS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi; | |
| const bodyStart = /\bAS\s*(?:NOT\s+)?(?:MATERIALIZED\s*)?\(/gi; |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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:
isDestructiveWithoutWhereflagsAS(DELETE …),AS(UPDATE …),AS MATERIALIZED(UPDATE …)and lowercaseas not materialized(delete …), and still allows a filteredAS(DELETE … WHERE id = 1 …).isReadOnlyQueryreturnsfalseforAS(DELETE …),AS(UPDATE …),AS NOT MATERIALIZED(DELETE …)andx(a)AS(UPDATE …), while a read-onlyAS(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
left a comment
There was a problem hiding this comment.
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.
|
Late thanks, @NewtTheWolf. The |
In PostgreSQL, a CTE body can itself be a data-modifying statement, and it runs even when the final statement is a
SELECT:This deletes every row in
users, and the editor runs it without asking. Both checks insqlAnalysis.tsjudge aWITHstatement only by the keyword after its CTE list, here theSELECT:classifyDangerousQueryreturnsnull. On every connection that isn't marked production, Run without a WHERE clause? never appears.isReadOnlyQueryreturnstrue. On a production connection, the Production database prompt never appears either. That's the promptuseQueryGuardsshows there instead of the WHERE one.The same applies to
UPDATE … SET … RETURNINGand toINSERTorMERGEin a CTE body. The existing CTE tests only cover a finalDELETE(WITH ids AS (SELECT …) DELETE FROM users), which is already handled.Fix
A small
cteBodieshelper reads the text inside eachAS (…)of aWITHstatement, includingAS [NOT] MATERIALIZED (…). Both checks now look at those bodies:isReadOnlyQuery): a CTE body that starts withINSERT,UPDATE,DELETEorMERGEmakes the statement a write. That also coversEXPLAIN ANALYZE WITH …, which really runs it.classifyDangerousQuery): a CTE body that runsDELETEorUPDATEwithout its own top-levelWHEREis reported asno-where, the same as a top-level one. AWHEREin a subquery inside the body still doesn't count. A filteredDELETEor anINSERTin 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, andWITH RECURSIVE.There's no matching classifier in
src-tauri, so nothing changes on the backend.Testing
tests/utils/sqlAnalysis.test.ts: four new tests.WHEREcheck: it flagsDELETEorUPDATEwithout aWHEREin a body. That coversAS MATERIALIZED, a second CTE, and aWHEREthat only appears in aUSINGsubquery.WHEREcheck, other direction: it allows a filteredDELETEand anINSERTin a body.isReadOnlyQuerywrites: bodies withDELETE,UPDATE,INSERTandMERGE, plusEXPLAIN ANALYZE WITH …, are not read-only.isReadOnlyQueryreads: read-only CTEs stay read-only.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.pnpm typecheckpassed. ESLint and Prettier passed on the changed files.routing,EditorResultChartandQueryHistoryProviderPause. All three pass when run on their own on this branch.EditorResultChartmocks both guard hooks, so this change doesn't reach it.How to try it
On a PostgreSQL connection with no environment set, create and fill a scratch table in the SQL editor:
Run:
On
mainit returns5straight away, and the table is empty. With this change, Run without a WHERE clause? appears first.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 theDELETEis filtered.Edit the connection and set Environment to Production. Run the statement from step 2 again. On
mainit runs without a prompt. With this change, the Production database confirmation appears.Run
WITH x AS (SELECT 1) SELECT * FROM x;. No prompt appears, on either connection type.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.