From 45994784cd0606038a22281aa8aa3b92beeffcba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20Sch=C3=B6ne?= Date: Wed, 25 Nov 2026 15:58:57 +0100 Subject: [PATCH 1/3] fix(sqlite): Convert ORDER BY and LIMIT ... OFFSET clauses into AST --- internal/compiler/find_params.go | 6 ++++++ internal/core/analyzer/dml.go | 24 ++++++++++++++++++++++++ internal/engine/sqlite/convert.go | 27 +++++++++++++++++---------- internal/sql/ast/delete_stmt.go | 16 ++++++++++++++++ internal/sql/ast/update_stmt.go | 16 ++++++++++++++++ internal/sql/astutils/rewrite.go | 6 ++++++ internal/sql/astutils/walk.go | 12 ++++++++++++ 7 files changed, 97 insertions(+), 10 deletions(-) diff --git a/internal/compiler/find_params.go b/internal/compiler/find_params.go index 8199addd33..7e8129ddb2 100644 --- a/internal/compiler/find_params.go +++ b/internal/compiler/find_params.go @@ -68,6 +68,9 @@ func (p paramSearch) Visit(node ast.Node) astutils.Visitor { if n.LimitCount != nil { p.limitCount = n.LimitCount } + if n.LimitOffset != nil { + p.limitOffset = n.LimitOffset + } case *ast.FuncCall: p.parent = node @@ -132,6 +135,9 @@ func (p paramSearch) Visit(node ast.Node) astutils.Visitor { if n.LimitCount != nil { p.limitCount = n.LimitCount } + if n.LimitOffset != nil { + p.limitOffset = n.LimitOffset + } case *ast.RangeVar: p.rangeVar = n diff --git a/internal/core/analyzer/dml.go b/internal/core/analyzer/dml.go index 597723cedd..f3622f5bfd 100644 --- a/internal/core/analyzer/dml.go +++ b/internal/core/analyzer/dml.go @@ -57,6 +57,9 @@ func (a *analyzer) analyzeUpdate(s *ast.UpdateStmt) error { return fmt.Errorf("where: %w", err) } } + if err := a.typeOrderLimit(s.SortClause, s.LimitCount, s.LimitOffset); err != nil { + return err + } return a.projectReturning(s.ReturningList) } @@ -75,6 +78,9 @@ func (a *analyzer) analyzeDelete(s *ast.DeleteStmt) error { return fmt.Errorf("where: %w", err) } } + if err := a.typeOrderLimit(s.SortClause, s.LimitCount, s.LimitOffset); err != nil { + return err + } return a.projectReturning(s.ReturningList) } @@ -209,3 +215,21 @@ func columnType(rel scopeRel, col core.ClassColumn) exprType { sourceTableAlias: rel.alias, } } + +// typeOrderLimit types the ORDER BY and LIMIT ... OFFSET that SQLite accepts +// on an UPDATE or DELETE (MySQL accepts ORDER BY and LIMIT, without OFFSET). +func (a *analyzer) typeOrderLimit(sort *ast.List, count, offset ast.Node) error { + for _, item := range listItems(sort) { + if sb, ok := item.(*ast.SortBy); ok { + if _, err := a.typeExpr(sb.Node); err != nil { + return fmt.Errorf("order by: %w", err) + } + } + } + for _, n := range []ast.Node{count, offset} { + if err := a.typeLimit(n); err != nil { + return fmt.Errorf("limit: %w", err) + } + } + return nil +} diff --git a/internal/engine/sqlite/convert.go b/internal/engine/sqlite/convert.go index dad36d4d1e..32e353155a 100644 --- a/internal/engine/sqlite/convert.go +++ b/internal/engine/sqlite/convert.go @@ -432,22 +432,28 @@ func (c *cc) convertDropStmt(name *meyer.QualifiedName, ifExists bool) ast.Node } func (c *cc) convertDeleteStmt(n *meyer.DeleteStmt) ast.Node { - return &ast.DeleteStmt{ + stmt := &ast.DeleteStmt{ Relations: &ast.List{Items: []ast.Node{parseRangeVar(n.Table, n.Alias)}}, WhereClause: c.convertExpr(n.Where), - LimitCount: c.limitCount(n.Limit), ReturningList: c.convertReturning(n.Returning), WithClause: c.convertWith(n.With), } + stmt.SortClause, stmt.LimitCount, stmt.LimitOffset = c.convertOrderLimit(n.OrderBy, n.Limit) + return stmt } -// limitCount converts the LIMIT of an UPDATE or DELETE. sqlc has no place to -// put the OFFSET or the ORDER BY that can accompany it, so they are dropped. -func (c *cc) limitCount(n *meyer.Limit) ast.Node { - if n == nil { - return nil +// convertOrderLimit converts the ORDER BY and LIMIT ... OFFSET of an UPDATE +// or DELETE, which SQLite accepts when built with +// SQLITE_ENABLE_UPDATE_DELETE_LIMIT. +func (c *cc) convertOrderLimit(orderBy []*meyer.OrderingTerm, limit *meyer.Limit) (sort *ast.List, count, offset ast.Node) { + if len(orderBy) > 0 { + sort = &ast.List{Items: c.convertOrderBy(orderBy)} } - return c.convertExpr(n.Count) + if limit != nil { + count = c.convertExpr(limit.Count) + offset = c.convertExpr(limit.Offset) + } + return sort, count, offset } func (c *cc) convertInsertStmt(n *meyer.InsertStmt) ast.Node { @@ -521,15 +527,16 @@ func (c *cc) convertSetPairs(pairs []*meyer.SetPair) *ast.List { } func (c *cc) convertUpdateStmt(n *meyer.UpdateStmt) ast.Node { - return &ast.UpdateStmt{ + stmt := &ast.UpdateStmt{ Relations: &ast.List{Items: []ast.Node{parseRangeVar(n.Table, n.Alias)}}, TargetList: c.convertSetPairs(n.Set), FromClause: &ast.List{Items: c.convertFrom(n.From)}, WhereClause: c.convertExpr(n.Where), - LimitCount: c.limitCount(n.Limit), ReturningList: c.convertReturning(n.Returning), WithClause: c.convertWith(n.With), } + stmt.SortClause, stmt.LimitCount, stmt.LimitOffset = c.convertOrderLimit(n.OrderBy, n.Limit) + return stmt } func (c *cc) convertReturning(cols []*meyer.ResultColumn) *ast.List { diff --git a/internal/sql/ast/delete_stmt.go b/internal/sql/ast/delete_stmt.go index 5d584b6d0c..e248f66c30 100644 --- a/internal/sql/ast/delete_stmt.go +++ b/internal/sql/ast/delete_stmt.go @@ -8,7 +8,9 @@ type DeleteStmt struct { Relations *List `json:"relations,omitempty"` UsingClause *List `json:"using_clause,omitempty"` WhereClause Node `json:"where_clause,omitempty"` + SortClause *List `json:"sort_clause,omitempty"` LimitCount Node `json:"limit_count,omitempty"` + LimitOffset Node `json:"limit_offset,omitempty"` ReturningList *List `json:"returning_list,omitempty"` WithClause *WithClause `json:"with_clause,omitempty"` // MySQL multi-table DELETE support @@ -74,6 +76,13 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) { buf.condition(n.WhereClause, d) } + if items(n.SortClause) { + buf.beforeClause(n.SortClause, d) + buf.Line() + buf.WriteString("ORDER BY ") + buf.astFormat(n.SortClause, d) + } + if set(n.LimitCount) { buf.beforeClause(n.LimitCount, d) buf.Line() @@ -81,6 +90,13 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) { buf.astFormat(n.LimitCount, d) } + if set(n.LimitOffset) { + buf.beforeClause(n.LimitOffset, d) + buf.Line() + buf.WriteString("OFFSET ") + buf.astFormat(n.LimitOffset, d) + } + if items(n.ReturningList) { buf.beforeClause(n.ReturningList, d) buf.Line() diff --git a/internal/sql/ast/update_stmt.go b/internal/sql/ast/update_stmt.go index 3c92fb929c..0abf00be3c 100644 --- a/internal/sql/ast/update_stmt.go +++ b/internal/sql/ast/update_stmt.go @@ -13,7 +13,9 @@ type UpdateStmt struct { TargetList *List `json:"target_list,omitempty"` WhereClause Node `json:"where_clause,omitempty"` FromClause *List `json:"from_clause,omitempty"` + SortClause *List `json:"sort_clause,omitempty"` LimitCount Node `json:"limit_count,omitempty"` + LimitOffset Node `json:"limit_offset,omitempty"` ReturningList *List `json:"returning_list,omitempty"` WithClause *WithClause `json:"with_clause,omitempty"` // PostgreSQL 18 RETURNING WITH (OLD AS ..., NEW AS ...) aliases @@ -147,6 +149,13 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) { buf.condition(n.WhereClause, d) } + if items(n.SortClause) { + buf.beforeClause(n.SortClause, d) + buf.Line() + buf.WriteString("ORDER BY ") + buf.astFormat(n.SortClause, d) + } + if set(n.LimitCount) { buf.beforeClause(n.LimitCount, d) buf.Line() @@ -154,6 +163,13 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) { buf.astFormat(n.LimitCount, d) } + if set(n.LimitOffset) { + buf.beforeClause(n.LimitOffset, d) + buf.Line() + buf.WriteString("OFFSET ") + buf.astFormat(n.LimitOffset, d) + } + if items(n.ReturningList) { buf.beforeClause(n.ReturningList, d) buf.Line() diff --git a/internal/sql/astutils/rewrite.go b/internal/sql/astutils/rewrite.go index 25b274a16c..451efb9564 100644 --- a/internal/sql/astutils/rewrite.go +++ b/internal/sql/astutils/rewrite.go @@ -685,6 +685,9 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. a.apply(n, "Relations", nil, n.Relations) a.apply(n, "UsingClause", nil, n.UsingClause) a.apply(n, "WhereClause", nil, n.WhereClause) + a.apply(n, "SortClause", nil, n.SortClause) + a.apply(n, "LimitCount", nil, n.LimitCount) + a.apply(n, "LimitOffset", nil, n.LimitOffset) a.apply(n, "ReturningList", nil, n.ReturningList) a.apply(n, "WithClause", nil, n.WithClause) a.apply(n, "Targets", nil, n.Targets) @@ -1174,6 +1177,9 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. a.apply(n, "TargetList", nil, n.TargetList) a.apply(n, "WhereClause", nil, n.WhereClause) a.apply(n, "FromClause", nil, n.FromClause) + a.apply(n, "SortClause", nil, n.SortClause) + a.apply(n, "LimitCount", nil, n.LimitCount) + a.apply(n, "LimitOffset", nil, n.LimitOffset) a.apply(n, "ReturningList", nil, n.ReturningList) a.apply(n, "WithClause", nil, n.WithClause) diff --git a/internal/sql/astutils/walk.go b/internal/sql/astutils/walk.go index 6d5e80bdc3..3828dc7e2c 100644 --- a/internal/sql/astutils/walk.go +++ b/internal/sql/astutils/walk.go @@ -1068,9 +1068,15 @@ func Walk(f Visitor, node ast.Node) { if n.WhereClause != nil { Walk(f, n.WhereClause) } + if n.SortClause != nil { + Walk(f, n.SortClause) + } if n.LimitCount != nil { Walk(f, n.LimitCount) } + if n.LimitOffset != nil { + Walk(f, n.LimitOffset) + } if n.ReturningList != nil { Walk(f, n.ReturningList) } @@ -2068,9 +2074,15 @@ func Walk(f Visitor, node ast.Node) { if n.FromClause != nil { Walk(f, n.FromClause) } + if n.SortClause != nil { + Walk(f, n.SortClause) + } if n.LimitCount != nil { Walk(f, n.LimitCount) } + if n.LimitOffset != nil { + Walk(f, n.LimitOffset) + } if n.ReturningList != nil { Walk(f, n.ReturningList) } From 64e710c4228338e64db7f1e62508c0884f91010b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20Sch=C3=B6ne?= Date: Wed, 25 Nov 2026 16:00:54 +0100 Subject: [PATCH 2/3] test(sqlite): ORDER BY and LIMIT ... OFFSET parameter end-to-end test --- .../sqlite/go/db.go | 31 ++++++++ .../sqlite/go/models.go | 11 +++ .../sqlite/go/query.sql.go | 76 +++++++++++++++++++ .../sqlite/query.sql | 11 +++ .../sqlite/schema.sql | 5 ++ .../sqlite/sqlc.json | 12 +++ 6 files changed, 146 insertions(+) create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/db.go create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/models.go create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/query.sql.go create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/query.sql create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/schema.sql create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/sqlc.json diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/db.go b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/models.go b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/models.go new file mode 100644 index 0000000000..bd18801202 --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/models.go @@ -0,0 +1,11 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +type T struct { + ID int64 + Name string + Score int64 +} diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/query.sql.go b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/query.sql.go new file mode 100644 index 0000000000..49bbcf8e0f --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/go/query.sql.go @@ -0,0 +1,76 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const deleteLimitOffset = `-- name: DeleteLimitOffset :exec +DELETE FROM t WHERE name = ? ORDER BY score DESC LIMIT ? OFFSET ? +` + +type DeleteLimitOffsetParams struct { + Name string + Limit int64 + Offset int64 +} + +func (q *Queries) DeleteLimitOffset(ctx context.Context, arg DeleteLimitOffsetParams) error { + _, err := q.db.ExecContext(ctx, deleteLimitOffset, arg.Name, arg.Limit, arg.Offset) + return err +} + +const deleteOrderByParam = `-- name: DeleteOrderByParam :exec +DELETE FROM t WHERE name = ? ORDER BY abs(score - ?) LIMIT ? +` + +type DeleteOrderByParamParams struct { + Name string + Score int64 + Limit int64 +} + +func (q *Queries) DeleteOrderByParam(ctx context.Context, arg DeleteOrderByParamParams) error { + _, err := q.db.ExecContext(ctx, deleteOrderByParam, arg.Name, arg.Score, arg.Limit) + return err +} + +const updateLimitOffset = `-- name: UpdateLimitOffset :exec +UPDATE t SET score = ? WHERE name = ? ORDER BY id LIMIT ? OFFSET ? +` + +type UpdateLimitOffsetParams struct { + Score int64 + Name string + Limit int64 + Offset int64 +} + +func (q *Queries) UpdateLimitOffset(ctx context.Context, arg UpdateLimitOffsetParams) error { + _, err := q.db.ExecContext(ctx, updateLimitOffset, + arg.Score, + arg.Name, + arg.Limit, + arg.Offset, + ) + return err +} + +const updateOrderByParam = `-- name: UpdateOrderByParam :exec +UPDATE t SET score = ? WHERE name = ? ORDER BY abs(score - ?) LIMIT 1 +` + +type UpdateOrderByParamParams struct { + Score int64 + Name string + Score_2 int64 +} + +func (q *Queries) UpdateOrderByParam(ctx context.Context, arg UpdateOrderByParamParams) error { + _, err := q.db.ExecContext(ctx, updateOrderByParam, arg.Score, arg.Name, arg.Score_2) + return err +} diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/query.sql b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/query.sql new file mode 100644 index 0000000000..013c71d819 --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/query.sql @@ -0,0 +1,11 @@ +-- name: DeleteLimitOffset :exec +DELETE FROM t WHERE name = ? ORDER BY score DESC LIMIT ? OFFSET ?; + +-- name: DeleteOrderByParam :exec +DELETE FROM t WHERE name = ? ORDER BY abs(score - ?) LIMIT ?; + +-- name: UpdateLimitOffset :exec +UPDATE t SET score = ? WHERE name = ? ORDER BY id LIMIT ? OFFSET ?; + +-- name: UpdateOrderByParam :exec +UPDATE t SET score = ? WHERE name = ? ORDER BY abs(score - ?) LIMIT 1; diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/schema.sql b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/schema.sql new file mode 100644 index 0000000000..717c4b82ac --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/schema.sql @@ -0,0 +1,5 @@ +CREATE TABLE t ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + score INTEGER NOT NULL +); diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/sqlc.json b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/sqlc.json new file mode 100644 index 0000000000..1f9d43df5d --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "engine": "sqlite", + "path": "go", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} From 832f0adb6bc17ead3cdc801e1d2a7fdacba15d80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20Sch=C3=B6ne?= Date: Wed, 25 Nov 2026 17:47:31 +0100 Subject: [PATCH 3/3] test(sqlite): Expect SQLite logic errors for managed-db tests The CI uses a SQLite database built without the SQLITE_ENABLE_UPDATE_DELETE_LIMIT option enabled. Therefore, the syntax is not recognized and is expected to fail. --- .../sqlite/stderr/managed-db.txt | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 internal/endtoend/testdata/update_delete_order_by_limit/sqlite/stderr/managed-db.txt diff --git a/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/stderr/managed-db.txt b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/stderr/managed-db.txt new file mode 100644 index 0000000000..d7234b6262 --- /dev/null +++ b/internal/endtoend/testdata/update_delete_order_by_limit/sqlite/stderr/managed-db.txt @@ -0,0 +1,5 @@ +# package querytest +query.sql:1:1: sqlite3: SQL logic error: near "ORDER": syntax error +query.sql:5:1: sqlite3: SQL logic error: near "ORDER": syntax error +query.sql:8:1: sqlite3: SQL logic error: near "ORDER": syntax error +query.sql:11:1: sqlite3: SQL logic error: near "ORDER": syntax error