Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Fix auto limit handling of limit all and limit null (#51917)

Joshen Lim922937f6f7c8
diff --git a/apps/studio/data/sql/__tests__/utils.test.ts b/apps/studio/data/sql/__tests__/utils.test.ts
index b74389effdb..1c8df476865 100644
--- a/apps/studio/data/sql/__tests__/utils.test.ts
+++ b/apps/studio/data/sql/__tests__/utils.test.ts
@@ -1,4 +1,4 @@
-import { safeSql } from '@supabase/pg-meta'
+import { safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
import { describe, expect, it, test } from 'vitest'
import { applyAutoLimit, getSqlErrorLines, trimTrailingSemicolons } from '../utils'
@@ -118,6 +118,46 @@ describe('applyAutoLimit', () => {
const { appendAutoLimit } = applyAutoLimit(sql, limit)
expect(appendAutoLimit).toBe(false)
})
+ test.each([
+ 'select * from countries limit all;',
+ 'select * from countries limit all',
+ 'SELECT * FROM countries LIMIT ALL ;',
+ 'select * from countries limit null;',
+ 'select * from countries limit all offset 5;',
+ 'select * from countries offset 5 limit null',
+ ])('Should return false if query already has LIMIT ALL / LIMIT NULL: %s', (query) => {
+ const { sql, appendAutoLimit } = applyAutoLimit(query as SafeSqlFragment, 100)
+ expect(appendAutoLimit).toBe(false)
+ expect(sql).toBe(query)
+ })
+ test('Should append the limit to a CTE query', () => {
+ const sql = safeSql`WITH numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM numbers;`
+ const result = applyAutoLimit(sql, 100)
+ expect(result.appendAutoLimit).toBe(true)
+ expect(result.sql).toBe(
+ 'WITH numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM numbers limit 100;'
+ )
+ })
+ test('Should append the limit to a recursive CTE query when the inner query has its own limit', () => {
+ const sql = safeSql`with recursive t as (select 1 as n limit 5) select * from t`
+ expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(true)
+ })
+ test('Should return false if a CTE query already has a limit', () => {
+ const sql = safeSql`with t as (select 1) select * from t limit 10`
+ expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(false)
+ })
+ test('Should append the limit to a read-only CTE whose literals or identifiers contain write keywords', () => {
+ const sql = safeSql`with t as (select 'update' as "delete") select * from t`
+ expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(true)
+ })
+ test.each([
+ 'with d as (delete from t returning *) select * from d',
+ 'with s as (select 1) insert into t select * from s',
+ 'with s as (select 1) update t set a = 1',
+ 'with t as (select 1) select * into new_t from t',
+ ])('Should return false for a CTE query that writes: %s', (query) => {
+ expect(applyAutoLimit(query as SafeSqlFragment, 100).appendAutoLimit).toBe(false)
+ })
test('Should return false if query already has a limit (check for case-insensitiveness)', () => {
const sql = safeSql`SELECT * FROM countries LIMIT 10;`
const limit = 100
diff --git a/apps/studio/data/sql/utils.ts b/apps/studio/data/sql/utils.ts
index 541e59b8561..d628a749abd 100644
--- a/apps/studio/data/sql/utils.ts
+++ b/apps/studio/data/sql/utils.ts
@@ -30,6 +30,15 @@ export function trimTrailingSemicolons(sql: SafeSqlFragment): SafeSqlFragment {
return sql.replace(/;+\s*$/, '') as SafeSqlFragment
}
+// Quoted text and comments, matched left to right so a quote inside a comment (or the reverse)
+// can't desync the scan: E'..' strings, '..' strings, "..." identifiers, $tag$..$tag$ bodies,
+// -- line comments and /* */ block comments
+const LITERALS_AND_COMMENTS =
+ /\be'(?:[^'\\]|\\.|'')*'|'(?:[^']|'')*'|"(?:[^"]|"")*"|(\$[a-z_]*\$)[\s\S]*?\1|--[^\n]*|\/\*[\s\S]*?\*\//gi
+
+/** Keeps only the SQL tokens, so keywords inside literals and comments aren't mistaken for syntax. */
+export const stripLiteralsAndComments = (sql: string) => sql.replace(LITERALS_AND_COMMENTS, ' ')
+
// [Joshen] Just FYI as well the checks here on whether to append limit is quite restricted
// This is to prevent dashboard from accidentally appending limit to the end of a query
// thats not supposed to have any, since there's too many cases to cover.
@@ -59,17 +68,26 @@ export function applyAutoLimit(
const hasMultipleQueries =
queries.length > 1 || (indexSemiColon > 0 && indexSemiColon !== cleanedSql.length - 1)
+ // A CTE query can end in a write (`with x as (...) insert/update/delete ...`), where a trailing
+ // limit is invalid, so only treat `with` as a select if no write keyword appears outside literals
+ const lowerSql = cleanedSql.toLowerCase()
+ const isSelectLike =
+ lowerSql.startsWith('select') ||
+ (/^with\b/.test(lowerSql) &&
+ !/\b(insert|update|delete|merge|into)\b/.test(stripLiteralsAndComments(lowerSql)))
+
// Check if need to auto limit rows
const appendAutoLimit =
limit > 0 &&
!hasComments &&
!hasMultipleQueries &&
- cleanedSql.toLowerCase().startsWith('select') &&
+ isSelectLike &&
!cleanedSql.toLowerCase().match(/fetch\s+(first|next)/i) &&
!cleanedSql.match(/limit$/i) &&
!cleanedSql.match(/limit;$/i) &&
!cleanedSql.match(/limit [0-9]* offset [0-9]*\s*[;]?$/i) &&
- !cleanedSql.match(/limit [0-9]*\s*[;]?$/i)
+ !cleanedSql.match(/limit [0-9]*\s*[;]?$/i) &&
+ !cleanedSql.match(/limit (all|null)( offset [0-9]+)?\s*[;]?$/i)
if (!appendAutoLimit) return { sql, appendAutoLimit: false }
diff --git a/apps/studio/lib/ai/tools/cap-read-query.ts b/apps/studio/lib/ai/tools/cap-read-query.ts
index 0f967b9a09e..87040c1d52b 100644
--- a/apps/studio/lib/ai/tools/cap-read-query.ts
+++ b/apps/studio/lib/ai/tools/cap-read-query.ts
@@ -1,22 +1,11 @@
import { literal, safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
-import { applyAutoLimit, trimTrailingSemicolons } from '@/data/sql/utils'
+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
-// applyAutoLimit doesn't recognise `LIMIT ALL` and would append a second LIMIT
-const HAS_LIMIT_ALL = /\blimit\s+all\b/i
const UNWRAPPABLE = /\b(insert|update|delete|merge|into|for\s+(no\s+key\s+)?(update|share))\b/i
-// Quoted text and comments, matched left to right so a quote inside a comment (or the reverse)
-// can't desync the scan: E'..' strings, '..' strings, "..." identifiers, $tag$..$tag$ bodies,
-// -- line comments and /* */ block comments
-const LITERALS_AND_COMMENTS =
- /\be'(?:[^'\\]|\\.|'')*'|'(?:[^']|'')*'|"(?:[^"]|"")*"|(\$[a-z_]*\$)[\s\S]*?\1|--[^\n]*|\/\*[\s\S]*?\*\//gi
-
-/** Keeps only the SQL tokens, so keywords inside literals and comments aren't mistaken for syntax. */
-const stripLiteralsAndComments = (sql: string) => sql.replace(LITERALS_AND_COMMENTS, ' ')
-
/**
* 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
@@ -28,10 +17,8 @@ export function capReadQuery(
sql: SafeSqlFragment,
limit: number
): { sql: SafeSqlFragment; isCappedInDatabase: boolean } {
- const auto = HAS_LIMIT_ALL.test(stripLiteralsAndComments(sql))
- ? undefined
- : applyAutoLimit(sql, limit)
- if (auto?.appendAutoLimit) return { sql: auto.sql, isCappedInDatabase: true }
+ 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)