Files
supabase/apps/studio/lib/ai/tools/cap-read-query.ts
Joshen Lim 922937f6f7 Fix auto limit handling of limit all and limit null (#51917)
## Context

Resolves https://github.com/supabase/supabase/issues/51836

Resolves FE-4666

The auto limit logic in the SQL Editor doesn't handle correctly when the
query contains a `LIMIT ALL` or `LIMIT NULL` and will append another
`LIMIT x` at the end of the query, so this PR fixes that

Also added a fix to ensure that auto limit applies for select statements
in CTEs

## To test
- [ ] Verify that result does not have auto limit applied if running
`select 1 limit all` or `select 1 limit null` in SQL Editor
- [ ] Verify that there's auto limit for a CTE statement like `WITH
numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM
numbers;`
2026-10-20 11:21:08 +08:00

34 lines
1.7 KiB
TypeScript

import { literal, safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
import { applyAutoLimit, stripLiteralsAndComments, trimTrailingSemicolons } from '@/data/sql/utils'
const WRAPPABLE_START = /^\s*(\(|select\b|with\b|values\b|table\b)/i
// Statements that can't live inside a subquery (or that write), so they're left untouched
const UNWRAPPABLE = /\b(insert|update|delete|merge|into|for\s+(no\s+key\s+)?(update|share))\b/i
/**
* Caps a read query at `limit` rows inside the database. Falls back to wrapping the query in a
* subquery when `applyAutoLimit` can't append a limit (e.g. an explicit large LIMIT or
* FETCH FIRST, CTEs, trailing comments). Anything that can't be wrapped safely — multiple
* statements, writes, or text we can't confidently classify — is returned unchanged, so callers
* must still slice the result.
*/
export function capReadQuery(
sql: SafeSqlFragment,
limit: number
): { sql: SafeSqlFragment; isCappedInDatabase: boolean } {
const auto = applyAutoLimit(sql, limit)
if (auto.appendAutoLimit) return { sql: auto.sql, isCappedInDatabase: true }
const core = trimTrailingSemicolons(sql.trim() as SafeSqlFragment)
const tokens = stripLiteralsAndComments(core)
// Any remaining `;` means multiple statements (or a literal containing one): don't guess
if (tokens.includes(';') || !WRAPPABLE_START.test(tokens) || UNWRAPPABLE.test(tokens)) {
return { sql, isCappedInDatabase: false }
}
// Newlines around the query keep a trailing `--` comment from swallowing the closing paren
const wrapped = safeSql`select * from (\n${core}\n) as capped_result limit ${literal(limit)};`
return { sql: wrapped, isCappedInDatabase: true }
}