Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(pg): preserve separator when clamping LIMIT (#21019)

nlimpid41249d305706
diff --git a/backend/plugin/parser/pg/limit.go b/backend/plugin/parser/pg/limit.go
index b8deb7f308..db1dff86c7 100644
--- a/backend/plugin/parser/pg/limit.go
+++ b/backend/plugin/parser/pg/limit.go
@@ -64,8 +64,10 @@ func rewriteSelectLimit(sql string, sel *ast.SelectStmt, limitCount int) (string
if isInteger && existingLimit >= 0 && existingLimit <= limitCount {
return sql, nil // existing limit is already lower or equal, keep it
}
- if isInteger && loc.Start >= 0 && loc.End > loc.Start && loc.End <= len(sql) {
- return sql[:loc.Start] + fmt.Sprintf("%d", limitCount) + sql[loc.End:], nil
+ if isInteger {
+ if end, ok := integerLiteralEnd(sql, loc); ok {
+ return sql[:loc.Start] + fmt.Sprintf("%d", limitCount) + sql[end:], nil
+ }
}
// ALL/NULL and non-constant limits lack reliable replacement spans.
// Cap them with the outer query instead of rewriting their text.
@@ -134,3 +136,14 @@ func nodeLocOf(node ast.Node) ast.Loc {
return ast.Loc{Start: -1, End: -1}
}
}
+
+// integerLiteralEnd returns the exclusive end byte offset of the integer
+// literal. The AST span may include whitespace before the next token, which
+// must remain when replacing the literal.
+func integerLiteralEnd(sql string, loc ast.Loc) (int, bool) {
+ if loc.Start < 0 || loc.End <= loc.Start || loc.End > len(sql) {
+ return 0, false
+ }
+ literal := strings.TrimRight(sql[loc.Start:loc.End], " \t\r\n\f\v")
+ return loc.Start + len(literal), true
+}
diff --git a/backend/plugin/parser/pg/limit_test.go b/backend/plugin/parser/pg/limit_test.go
index 43d5acfe4c..2058af4a04 100644
--- a/backend/plugin/parser/pg/limit_test.go
+++ b/backend/plugin/parser/pg/limit_test.go
@@ -229,6 +229,12 @@ func TestGetStatementWithResultLimitInline(t *testing.T) {
limit: 5,
want: "SELECT * FROM t LIMIT 0",
},
+ {
+ name: "over-max LIMIT preserves separator before OFFSET",
+ statement: "SELECT 1 LIMIT 2000 OFFSET 0;",
+ limit: 1000,
+ want: "SELECT 1 LIMIT 1000 OFFSET 0;",
+ },
{
name: "CTE with lateral and ORDER BY",
statement: `WITH params AS (