Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/endtoend/testdata/analyze_select/sqlite/query.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-- name: ListUsers :many
SELECT * FROM users;
SELECT * FROM users

-- name: CountUsers :one
SELECT count(*) AS total FROM users;
Expand Down
32 changes: 31 additions & 1 deletion internal/engine/sqlite/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sqlite
import (
"errors"
"io"
"strings"

meyer "github.com/sqlc-dev/meyer/ast"
"github.com/sqlc-dev/meyer/parser"
Expand Down Expand Up @@ -31,7 +32,7 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
return nil, err
}
src := string(blob)
parsed, err := parseOptions.ParseString(src)
parsed, err := parseOptions.ParseString(terminateNamedQueries(src))
if err != nil {
return nil, normalizeErr(err)
}
Expand All @@ -58,6 +59,35 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
return stmts, nil
}

// terminateNamedQueries adds a virtual terminator before a subsequent sqlc
// query annotation when the preceding query omitted one. sqlc annotations
// delimit queries for the other engines, and a query file may therefore
// contain multiple valid queries even though the complete SQLite script would
// otherwise be invalid. Replacing the newline immediately before the
// annotation preserves every byte offset reported by the parser.
func terminateNamedQueries(src string) string {
terminated := []byte(src)
for lineStart := 0; lineStart < len(terminated); {
lineEnd := strings.IndexByte(src[lineStart:], '\n')
if lineEnd < 0 {
lineEnd = len(terminated)
} else {
lineEnd += lineStart
}
if lineStart > 0 && strings.HasPrefix(src[lineStart:lineEnd], "-- name: ") {
i := lineStart - 1
for i >= 0 && isSpace(terminated[i]) {
i--
}
if i >= 0 && terminated[i] != ';' {
terminated[lineStart-1] = ';'
}
}
lineStart = lineEnd + 1
}
return string(terminated)
}

// trimTerminator returns the end of stmt with its terminating semicolon, and
// any space before it, removed. A statement's span runs through the
// semicolon, but sqlc's statement text does not include it.
Expand Down
Loading