Silin-Chen's picture
CrossSWE-Bench: current 171-instance release
0e239c6
Raw History Blame Contribute Delete
99.4 kB
diff --git a/docs/howto/fmt.md b/docs/howto/fmt.md
new file mode 100644
index 000000000..1d874b40b
--- /dev/null
+++ b/docs/howto/fmt.md
@@ -0,0 +1,68 @@
+# `fmt` - Formatting queries
+
+`sqlc fmt` rewrites the query files referenced by your configuration file in a
+canonical format. Each query is parsed with the engine's parser and printed
+back from the syntax tree, so formatting never depends on how the query was
+written — only on what it means.
+
+Like `gofmt`, the formatter does not impose a maximum line width. A statement
+written on a single line stays on a single line, and a statement the author
+broke across lines keeps its breaks: the printer notices which clause
+boundaries (`FROM`, `WHERE`, `ORDER BY`, ...) and list boundaries the author
+broke at and preserves them, normalizing indentation and spacing around them.
+
+Comments inside a statement are formatted along with it: each comment is
+anchored to the code around it by source position and printed back there —
+a comment trailing a select-list item stays with that item, a comment above
+a clause stays above its keyword — and a comment that runs to the end of its
+line breaks the statement open around it. Any statement that cannot be
+proven to survive formatting unchanged is left exactly as written.
+
+## Usage
+
+```sh
+sqlc fmt [--diff]
+```
+
+Without flags, the query files are rewritten in place. With `--diff`, the
+changes are printed to standard output instead and no files are modified.
+
+## Examples
+
+Given this query file:
+
+```sql
+-- name: GetAuthor :one
+select id,name , bio
+from authors
+where id = ? limit 1;
+
+-- name: SearchAuthors :many
+SELECT id, -- the primary key
+ name, bio, created_at FROM authors WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? ORDER BY name;
+```
+
+running `sqlc fmt` rewrites it to:
+
+```sql
+-- name: GetAuthor :one
+SELECT id, name, bio
+FROM authors
+WHERE id = ?
+LIMIT 1;
+
+-- name: SearchAuthors :many
+SELECT
+ id, -- the primary key
+ name,
+ bio,
+ created_at
+FROM authors
+WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ?
+ORDER BY name;
+```
+
+`GetAuthor` keeps the line breaks its author wrote; had it been written on
+one line, it would stay on one line. In `SearchAuthors`, the line comment
+cannot share a line with the code after it, so the statement breaks open
+around it, while the `WHERE` chain — written on one line — stays on one.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index b0cf1eb77..286467a81 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -10,6 +10,7 @@ Available Commands:
completion Generate the autocompletion script for the specified shell
createdb Create an ephemeral database
diff Compare the generated files to the existing files
+ fmt Format SQL queries
generate Generate source code from SQL
help Help about any command
init Create an empty sqlc.yaml settings file
diff --git a/docs/toc.yaml b/docs/toc.yaml
index 4cbdbcd15..464fe334d 100644
--- a/docs/toc.yaml
+++ b/docs/toc.yaml
@@ -20,6 +20,7 @@ sections:
- title: Commands
pages:
- howto/analyze.md
+ - howto/fmt.md
- howto/generate.md
- howto/parse.md
- howto/push.md
diff --git a/go.mod b/go.mod
index 06691e59d..eeef23c0e 100644
--- a/go.mod
+++ b/go.mod
@@ -20,7 +20,7 @@ require (
github.com/spf13/pflag v1.0.10
github.com/sqlc-dev/doubleclick v1.0.0
github.com/sqlc-dev/marino v0.3.0
- github.com/sqlc-dev/meyer v0.1.1
+ github.com/sqlc-dev/meyer v0.1.2
github.com/sqlc-dev/oliphant v0.1.0
github.com/sqlc-dev/teesql v1.1.0
github.com/sqlc-dev/zetajones v0.1.0
diff --git a/go.sum b/go.sum
index 104d4cb9b..069391b24 100644
--- a/go.sum
+++ b/go.sum
@@ -69,8 +69,8 @@ github.com/sqlc-dev/doubleclick v1.0.0 h1:2/OApfQ2eLgcfa/Fqs8WSMA6atH0G8j9hHbQIg
github.com/sqlc-dev/doubleclick v1.0.0/go.mod h1:ODHRroSrk/rr5neRHlWMSRijqOak8YmNaO3VAZCNl5Y=
github.com/sqlc-dev/marino v0.3.0 h1:e9cinBXJFFa3yRpokYNNinWvkewgd6XVDgnlG0bOmTw=
github.com/sqlc-dev/marino v0.3.0/go.mod h1:mQxC2dgDE0DWHMb2B5jZNk7KToJuS6wnxnffBfYnq08=
-github.com/sqlc-dev/meyer v0.1.1 h1:BAeZcfgLyTnk9f90DyGEKXPrHxtgvVD/DTM6awq2kUY=
-github.com/sqlc-dev/meyer v0.1.1/go.mod h1:pS4USCRf/SLjWtaMcnTo4YrEEFKBj8CyyqlxcVUJQH8=
+github.com/sqlc-dev/meyer v0.1.2 h1:40Ng9Glnx7CTf3yOYV7jfvDIN7voIFjrStkIULS+uws=
+github.com/sqlc-dev/meyer v0.1.2/go.mod h1:pS4USCRf/SLjWtaMcnTo4YrEEFKBj8CyyqlxcVUJQH8=
github.com/sqlc-dev/oliphant v0.1.0 h1:RAsO6BMitIzB2+swx/qzUR5nf6w4cQ1abgHIu+Fgppo=
github.com/sqlc-dev/oliphant v0.1.0/go.mod h1:fRM/t4FutRddTIq2YCuS4O9o+2rRwSwELRvLMqtPloo=
github.com/sqlc-dev/teesql v1.1.0 h1:3sVYQ9FGxQVcqrqQOQ27bk0aF4c4yN1H1zLL79uaSxQ=
diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go
index 770c7c184..4b14751a5 100644
--- a/internal/cmd/cmd.go
+++ b/internal/cmd/cmd.go
@@ -43,6 +43,7 @@ func Do(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) int
rootCmd.AddCommand(createDBCmd)
rootCmd.AddCommand(diffCmd)
rootCmd.AddCommand(genCmd)
+ rootCmd.AddCommand(newFmtCmd())
rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(newParseCmd())
rootCmd.AddCommand(newAnalyzeCmd())
diff --git a/internal/cmd/fmt.go b/internal/cmd/fmt.go
new file mode 100644
index 000000000..0b76e2e89
--- /dev/null
+++ b/internal/cmd/fmt.go
@@ -0,0 +1,446 @@
+package cmd
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime/trace"
+ "sort"
+ "strings"
+
+ "github.com/cubicdaiya/gonp"
+ "github.com/spf13/cobra"
+
+ "github.com/sqlc-dev/sqlc/internal/config"
+ "github.com/sqlc-dev/sqlc/internal/engine/sqlite"
+ "github.com/sqlc-dev/sqlc/internal/sql/ast"
+ "github.com/sqlc-dev/sqlc/internal/sql/format"
+ "github.com/sqlc-dev/sqlc/internal/sql/sqlpath"
+)
+
+// noLineLimit renders without a maximum line width: like gofmt, fmt never
+// rewraps a line on its own. Breaks come from the author's own line breaks
+// at the boundaries the printer models, and from comments, which cannot
+// share a line with the code after them.
+const noLineLimit = 1 << 30
+
+// queryFormatter is what the fmt command needs from an engine: a parser
+// that surfaces the comments its lexer already scans (so statements and
+// comments come from one pass, and interior comments format along with
+// their statements) plus dialect-aware formatting. Comments cannot be
+// reprinted without parser support, so ParseFile is the price of admission.
+type queryFormatter interface {
+ ParseFile(io.Reader) (*ast.File, error)
+ format.Dialect
+}
+
+// newQueryFormatter returns the formatter for engines fmt supports —
+// SQLite today. An engine joins by teaching its parser to surface comments
+// (meyer's ParseFile is the template) and adding its case here.
+func newQueryFormatter(engine config.Engine) queryFormatter {
+ switch engine {
+ case config.EngineSQLite:
+ return sqlite.NewParser()
+ default:
+ return nil
+ }
+}
+
+func newFmtCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "fmt",
+ Short: "Format SQL queries",
+ Long: `Format the SQL query files referenced by the configuration file.
+
+Each query is parsed with the engine's parser and printed back in a canonical
+form, with its comments kept where they were written. A statement that cannot
+be proven to survive formatting unchanged is left exactly as written. Files
+are rewritten in place; pass --diff to print the changes to stdout instead.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ defer trace.StartRegion(cmd.Context(), "fmt").End()
+ stderr := cmd.ErrOrStderr()
+ stdout := cmd.OutOrStdout()
+ showDiff, err := cmd.Flags().GetBool("diff")
+ if err != nil {
+ return err
+ }
+ dir, name := getConfigPath(stderr, cmd.Flag("file"))
+ output, err := Format(cmd.Context(), dir, name, &Options{
+ Env: ParseEnv(cmd),
+ Stderr: stderr,
+ })
+ if err != nil {
+ os.Exit(1)
+ }
+
+ filenames := make([]string, 0, len(output))
+ for filename := range output {
+ filenames = append(filenames, filename)
+ }
+ sort.Strings(filenames)
+
+ for _, filename := range filenames {
+ existing, err := os.ReadFile(filename)
+ if err != nil {
+ fmt.Fprintf(stderr, "%s: %s\n", filename, err)
+ return err
+ }
+ source := output[filename]
+ if string(existing) == source {
+ continue
+ }
+ if showDiff {
+ diff := gonp.New(getLines(existing), getLines([]byte(source)))
+ diff.Compose()
+ uniHunks := filterHunks(diff.UnifiedHunks())
+ if len(uniHunks) == 0 {
+ continue
+ }
+ rel := filepath.ToSlash(strings.TrimPrefix(filename, dir))
+ fmt.Fprintf(stdout, "--- a%s\n", rel)
+ fmt.Fprintf(stdout, "+++ b%s\n", rel)
+ diff.FprintUniHunks(stdout, uniHunks)
+ continue
+ }
+ if err := os.WriteFile(filename, []byte(source), 0644); err != nil {
+ fmt.Fprintf(stderr, "%s: %s\n", filename, err)
+ return err
+ }
+ }
+ return nil
+ },
+ }
+ cmd.Flags().Bool("diff", false, "display diffs instead of rewriting files")
+ return cmd
+}
+
+// Format formats every query file referenced by the configuration with its
+// engine's SQL formatter. It returns the formatted contents of each file,
+// keyed by absolute path. Query files for engines without a formatter are
+// skipped.
+func Format(ctx context.Context, dir, filename string, o *Options) (map[string]string, error) {
+ defer trace.StartRegion(ctx, "format").End()
+ stderr := o.Stderr
+
+ configPath, conf, err := o.ReadConfig(dir, filename)
+ if err != nil {
+ return nil, err
+ }
+ base := filepath.Base(configPath)
+ if err := config.Validate(conf); err != nil {
+ fmt.Fprintf(stderr, "error validating %s: %s\n", base, err)
+ return nil, err
+ }
+
+ engines := map[string]config.Engine{}
+ var files []string
+ for _, sql := range conf.SQL {
+ joined := make([]string, 0, len(sql.Queries))
+ for _, q := range sql.Queries {
+ joined = append(joined, filepath.Join(dir, q))
+ }
+ list, err := sqlpath.Glob(joined)
+ if err != nil {
+ fmt.Fprintf(stderr, "error listing queries: %s\n", err)
+ return nil, err
+ }
+ for _, file := range list {
+ if _, ok := engines[file]; ok {
+ continue
+ }
+ engines[file] = sql.Engine
+ files = append(files, file)
+ }
+ }
+
+ output := map[string]string{}
+ unsupported := map[config.Engine]bool{}
+ for _, file := range files {
+ f := newQueryFormatter(engines[file])
+ if f == nil {
+ if !unsupported[engines[file]] {
+ unsupported[engines[file]] = true
+ fmt.Fprintf(stderr, "sqlc fmt does not yet support the %s engine; query files left unchanged\n", engines[file])
+ }
+ continue
+ }
+ rel, err := filepath.Rel(dir, file)
+ if err != nil {
+ rel = file
+ }
+ contents, err := os.ReadFile(file)
+ if err != nil {
+ fmt.Fprintf(stderr, "%s: skipped: %s\n", rel, err)
+ continue
+ }
+ formatted, err := formatQueries(f, string(contents))
+ if err != nil {
+ // Not every query file parses without the compiler's help — for
+ // example, some engines only accept sqlc.slice() after
+ // preprocessing. Leave those files as they are.
+ fmt.Fprintf(stderr, "%s: skipped: %s\n", rel, err)
+ continue
+ }
+ // File-level belt for the reprinter path: no formatting result may
+ // change the file's comments. A violation is a formatter bug; keep
+ // the file as written and say so.
+ before, err1 := f.ParseFile(strings.NewReader(string(contents)))
+ after, err2 := f.ParseFile(strings.NewReader(formatted))
+ if err1 == nil && (err2 != nil || !sameComments(before.Comments, after.Comments)) {
+ fmt.Fprintf(stderr, "%s: skipped: formatting would alter comments (this is a bug in sqlc fmt)\n", rel)
+ continue
+ }
+ output[file] = formatted
+ }
+ return output, nil
+}
+
+// formatQueries formats each statement in a query file. The comments above
+// every statement (that's where the "-- name:" annotation lives) are kept
+// as written; comments inside a statement are threaded through the printer
+// by position.
+func formatQueries(f queryFormatter, src string) (string, error) {
+ // The parser hands over statements and comments from one lexer pass;
+ // statement bodies slice the comment list by span.
+ file, err := f.ParseFile(strings.NewReader(src))
+ if err != nil {
+ return "", err
+ }
+ stmts, fileComments := file.Stmts, file.Comments
+ var blocks []string
+ prevEnd := 0
+ for _, stmt := range stmts {
+ if stmt.Raw == nil {
+ continue
+ }
+ start := stmt.Raw.StmtLocation
+ length := stmt.Raw.StmtLen
+ if length == 0 {
+ // An unterminated final statement is reported with a zero length.
+ length = len(src) - start
+ }
+ if start < 0 || start+length > len(src) {
+ return "", fmt.Errorf("statement location out of bounds")
+ }
+ // Engines differ on whether a statement's span covers the comments
+ // above it, so start each segment where the previous one ended: the
+ // gap holds nothing but the previous terminator, whitespace and
+ // comments.
+ segStart := prevEnd
+ if start < segStart {
+ segStart = start
+ }
+ if start+length <= prevEnd {
+ continue
+ }
+ prevEnd = start + length
+ seg := src[segStart : start+length]
+ segOff := segStart
+ // A comment on the same line as the previous statement's terminator
+ // belongs to that statement, not to this one's header.
+ if len(blocks) > 0 {
+ if trailing, remainder := splitTrailingComment(seg); trailing != "" {
+ blocks[len(blocks)-1] += " " + trailing
+ segOff += len(seg) - len(remainder)
+ seg = remainder
+ }
+ }
+ orig := strings.TrimSpace(strings.TrimLeft(seg, "; \t\r\n"))
+ if orig == "" {
+ continue
+ }
+ header, rest := splitLeadingComments(orig)
+ // The statement body's own file offset, so its interior comments
+ // can be sliced out of the file's comment list in the same
+ // coordinates the parser stamped on the nodes.
+ restOff := segOff + strings.Index(seg, orig) + len(orig) - len(rest)
+ var interior []ast.Comment
+ for _, c := range fileComments {
+ if c.Start >= restOff && c.End <= start+length {
+ interior = append(interior, c)
+ }
+ }
+ block := append([]string{}, header...)
+ block = append(block, formatStmt(f, stmt.Raw, rest, interior, src))
+ blocks = append(blocks, strings.Join(block, "\n"))
+ }
+ // Everything after the last statement is its terminator, whitespace and
+ // trailing comments; keep the comments.
+ tailSeg := src[prevEnd:]
+ if len(blocks) > 0 {
+ if trailing, remainder := splitTrailingComment(tailSeg); trailing != "" {
+ blocks[len(blocks)-1] += " " + trailing
+ tailSeg = remainder
+ }
+ }
+ if tail := strings.TrimSpace(strings.TrimLeft(tailSeg, "; \t\r\n")); tail != "" {
+ blocks = append(blocks, tail)
+ }
+ if len(blocks) == 0 {
+ return src, nil
+ }
+ return strings.Join(blocks, "\n\n") + "\n", nil
+}
+
+// splitTrailingComment splits a comment sitting on the same line as the
+// previous statement's terminator off the front of the text between two
+// statements, returning the comment (or "") and the remaining text.
+func splitTrailingComment(seg string) (string, string) {
+ k := 0
+ for k < len(seg) && (seg[k] == ';' || seg[k] == ' ' || seg[k] == '\t' || seg[k] == '\r') {
+ k++
+ }
+ rest := seg[k:]
+ line, _, _ := strings.Cut(rest, "\n")
+ trimmed := strings.TrimSpace(line)
+ switch {
+ case strings.HasPrefix(trimmed, "--"):
+ return trimmed, seg[k+len(line):]
+ case strings.HasPrefix(trimmed, "/*") &&
+ strings.HasSuffix(trimmed, "*/") && strings.Count(trimmed, "*/") == 1:
+ // A block comment contained on the terminator's line.
+ return trimmed, seg[k+len(line):]
+ }
+ return "", seg
+}
+
+// splitLeadingComments splits a statement's text into the comment lines above
+// it and the statement itself. Comment lines are returned with surrounding
+// whitespace trimmed (block comment continuation lines keep their leading
+// whitespace); blank lines between comments are kept.
+func splitLeadingComments(text string) ([]string, string) {
+ var header []string
+ rest := text
+ for rest != "" {
+ line, remainder, found := strings.Cut(rest, "\n")
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "/*") && !strings.Contains(trimmed, "*/") {
+ // A block comment spanning several lines: commit it to the
+ // header only when its closing line arrives with nothing after
+ // it. Otherwise leave the whole block with the statement.
+ block := []string{trimmed}
+ blockRest := remainder
+ for closed := false; !closed; {
+ if !found || blockRest == "" {
+ return header, rest
+ }
+ var blockLine string
+ blockLine, blockRest, found = strings.Cut(blockRest, "\n")
+ if end := strings.TrimSpace(blockLine); strings.Contains(end, "*/") {
+ if !strings.HasSuffix(end, "*/") || strings.Count(end, "*/") != 1 {
+ return header, rest
+ }
+ closed = true
+ }
+ block = append(block, strings.TrimRight(blockLine, " \t\r"))
+ }
+ header = append(header, block...)
+ rest = blockRest
+ continue
+ }
+ if !isCommentLine(trimmed) {
+ break
+ }
+ header = append(header, trimmed)
+ if !found {
+ rest = ""
+ break
+ }
+ rest = remainder
+ }
+ // A statement never ends with a comment-only line here (the parser found a
+ // statement in this segment), but drop any blank lines left at the end of
+ // the header so comments sit directly above their query.
+ for len(header) > 0 && header[len(header)-1] == "" {
+ header = header[:len(header)-1]
+ }
+ return header, rest
+}
+
+func isCommentLine(line string) bool {
+ switch {
+ case line == "":
+ // A blank line between comments.
+ return true
+ case strings.HasPrefix(line, "--"):
+ return true
+ case strings.HasPrefix(line, "/*") && strings.HasSuffix(line, "*/") && strings.Count(line, "*/") == 1:
+ // A block comment contained on a single line.
+ return true
+ default:
+ return false
+ }
+}
+
+// formatStmt returns the canonical form of a single statement, or the
+// original text when formatting cannot be proven to preserve the query.
+func formatStmt(f queryFormatter, raw *ast.RawStmt, orig string, interior []ast.Comment, src string) string {
+ fallback := strings.TrimSuffix(strings.TrimSpace(orig), ";") + ";"
+ if out, ok := formatWithComments(f, raw, interior, src); ok {
+ return out
+ }
+ return fallback
+}
+
+// formatWithComments pretty-prints a statement with its interior comments
+// and proves the result faithful three ways before accepting it: every
+// comment survives (multiset equality after reparsing the output), the SQL
+// still parses as one statement, and the output is a fixed point (printing
+// the reparsed statement with its reparsed comments reproduces it).
+func formatWithComments(f queryFormatter, raw *ast.RawStmt, interior []ast.Comment, src string) (string, bool) {
+ out := prettyCommented(raw, f, interior, src)
+ if strings.TrimSpace(strings.TrimSuffix(out, ";")) == "" {
+ return "", false
+ }
+ file, err := f.ParseFile(strings.NewReader(out))
+ if err != nil || len(file.Stmts) != 1 || file.Stmts[0].Raw == nil {
+ return "", false
+ }
+ if !sameComments(interior, file.Comments) {
+ return "", false
+ }
+ again := prettyCommented(file.Stmts[0].Raw, f, file.Comments, out)
+ if !strings.EqualFold(again, out) {
+ return "", false
+ }
+ return out, true
+}
+
+// prettyCommented attaches a statement's comments to its nodes and renders
+// it, returning "" when the printer panics or fails to place every comment.
+func prettyCommented(raw *ast.RawStmt, f queryFormatter, comments []ast.Comment, src string) (out string) {
+ defer func() {
+ if r := recover(); r != nil {
+ out = ""
+ }
+ }()
+ ct := ast.AttachComments(raw, f, comments, src)
+ out = ast.PrettyWithComments(raw, f, noLineLimit, ct)
+ if !ct.Exhausted() {
+ return ""
+ }
+ return out
+}
+
+// sameComments reports whether two comment lists carry the same comment
+// texts, as multisets, ignoring surrounding whitespace.
+func sameComments(a, b []ast.Comment) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ counts := make(map[string]int, len(a))
+ for _, c := range a {
+ counts[strings.TrimSpace(c.Text)]++
+ }
+ for _, c := range b {
+ counts[strings.TrimSpace(c.Text)]--
+ }
+ for _, n := range counts {
+ if n != 0 {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/endtoend/endtoend_test.go b/internal/endtoend/endtoend_test.go
index 5c261dc7a..1196ea717 100644
--- a/internal/endtoend/endtoend_test.go
+++ b/internal/endtoend/endtoend_test.go
@@ -316,11 +316,12 @@ func TestReplay(t *testing.T) {
}
case "vet":
err = cmd.Vet(ctx, path, "", &opts)
- case "parse", "analyze":
- // These commands are config-less and flag-driven. Run them
- // through the real CLI entry point from inside the test
- // directory so file arguments resolve and the output stays
- // independent of the absolute path.
+ case "parse", "analyze", "fmt":
+ // These commands are flag-driven (fmt cases pass --diff so
+ // nothing is rewritten). Run them through the real CLI
+ // entry point from inside the test directory so file
+ // arguments resolve and the output stays independent of
+ // the absolute path.
var stdout bytes.Buffer
wd, werr := os.Getwd()
if werr != nil {
diff --git a/internal/endtoend/fmt_test.go b/internal/endtoend/fmt_test.go
index afcf1db10..3420a8d0b 100644
--- a/internal/endtoend/fmt_test.go
+++ b/internal/endtoend/fmt_test.go
@@ -169,6 +169,12 @@ func TestFormat(t *testing.T) {
}
out := ast.Format(stmt.Raw, formatter)
+ // An empty rendering is the formatter's signal that
+ // the statement carries syntax the AST does not
+ // model; sqlc fmt keeps such statements as written.
+ if strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(out), ";")) == "" {
+ t.Skip("statement has no faithful rendering")
+ }
actual, err := fingerprint(out)
if err != nil {
t.Error(err)
diff --git a/internal/endtoend/testdata/fmt/mysql/exec.json b/internal/endtoend/testdata/fmt/mysql/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/exec.json
@@ -0,0 +1,5 @@
+{
+ "command": "fmt",
+ "args": ["--diff"],
+ "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/mysql/query.sql b/internal/endtoend/testdata/fmt/mysql/query.sql
new file mode 100644
index 000000000..fa565aeb9
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/query.sql
@@ -0,0 +1,15 @@
+-- name: GetAuthor :one
+select id,name , bio from authors
+where id = ? limit 1;
+
+# hash comment
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name DESC;
+
+-- name: CreateAuthor :execresult
+insert into authors (
+ name, bio
+) values (
+ ?, ?
+);
diff --git a/internal/endtoend/testdata/fmt/mysql/schema.sql b/internal/endtoend/testdata/fmt/mysql/schema.sql
new file mode 100644
index 000000000..0fb289c16
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/schema.sql
@@ -0,0 +1,5 @@
+CREATE TABLE authors (
+ id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+ name varchar(255) NOT NULL,
+ bio text
+);
diff --git a/internal/endtoend/testdata/fmt/mysql/sqlc.yaml b/internal/endtoend/testdata/fmt/mysql/sqlc.yaml
new file mode 100644
index 000000000..b843ef55e
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+ - engine: "mysql"
+ schema: "schema.sql"
+ queries: "query.sql"
+ gen:
+ go:
+ package: "querytest"
+ out: "go"
diff --git a/internal/endtoend/testdata/fmt/mysql/stderr.txt b/internal/endtoend/testdata/fmt/mysql/stderr.txt
new file mode 100644
index 000000000..69bf0841d
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/stderr.txt
@@ -0,0 +1 @@
+sqlc fmt does not yet support the mysql engine; query files left unchanged
diff --git a/internal/endtoend/testdata/fmt/mysql/stdout.txt b/internal/endtoend/testdata/fmt/mysql/stdout.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/internal/endtoend/testdata/fmt/postgresql/exec.json b/internal/endtoend/testdata/fmt/postgresql/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/exec.json
@@ -0,0 +1,5 @@
+{
+ "command": "fmt",
+ "args": ["--diff"],
+ "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/postgresql/query.sql b/internal/endtoend/testdata/fmt/postgresql/query.sql
new file mode 100644
index 000000000..a843f7647
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/query.sql
@@ -0,0 +1,30 @@
+-- name: GetAuthor :one
+select id,name , bio
+from authors
+where id = $1 limit 1; -- the primary lookup
+
+/* This listing powers the admin page.
+ Keep it ordered by name so the UI stays stable. */
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name;
+
+-- name: CreateAuthor :one
+INSERT INTO authors (
+ name, bio
+) VALUES (
+ $1, $2
+)
+RETURNING *;
+
+-- name: PickyQuery :many
+SELECT id, -- the primary key
+ name
+FROM authors
+WHERE id > $1;
+
+-- name: SearchAuthors :many
+SELECT id, name, bio, created_at FROM authors WHERE name LIKE $1 AND bio IS NOT NULL AND id > $2 AND name <> $3 ORDER BY name, id LIMIT $4;
+
+-- name: DeleteAuthor :exec
+DELETE FROM authors WHERE id = @id
diff --git a/internal/endtoend/testdata/fmt/postgresql/schema.sql b/internal/endtoend/testdata/fmt/postgresql/schema.sql
new file mode 100644
index 000000000..468ae88c5
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/schema.sql
@@ -0,0 +1,6 @@
+CREATE TABLE authors (
+ id BIGSERIAL PRIMARY KEY,
+ name text NOT NULL,
+ bio text,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml b/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml
new file mode 100644
index 000000000..cbd1c1399
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+ - engine: "postgresql"
+ schema: "schema.sql"
+ queries: "query.sql"
+ gen:
+ go:
+ package: "querytest"
+ out: "go"
diff --git a/internal/endtoend/testdata/fmt/postgresql/stderr.txt b/internal/endtoend/testdata/fmt/postgresql/stderr.txt
new file mode 100644
index 000000000..4aa7068b8
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/stderr.txt
@@ -0,0 +1 @@
+sqlc fmt does not yet support the postgresql engine; query files left unchanged
diff --git a/internal/endtoend/testdata/fmt/postgresql/stdout.txt b/internal/endtoend/testdata/fmt/postgresql/stdout.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/internal/endtoend/testdata/fmt/sqlite/exec.json b/internal/endtoend/testdata/fmt/sqlite/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/exec.json
@@ -0,0 +1,5 @@
+{
+ "command": "fmt",
+ "args": ["--diff"],
+ "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/sqlite/query.sql b/internal/endtoend/testdata/fmt/sqlite/query.sql
new file mode 100644
index 000000000..eac3f3997
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/query.sql
@@ -0,0 +1,67 @@
+-- name: GetAuthor :one
+select id,name , bio from authors
+where id = ? limit 1;
+
+-- name: PickyQuery :many
+SELECT id, -- the primary key
+ name,
+ -- computed downstream
+ bio
+FROM authors
+-- soft-deleted rows are filtered
+WHERE bio IS NOT NULL
+ AND id > ?;
+
+-- name: InlineBlock :many
+SELECT /* inline note */ id, name FROM authors ORDER BY name;
+
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name;
+
+-- name: GetEvent :one
+SELECT "EventName", "order"
+FROM "Events" WHERE id = ? LIMIT 1;
+
+-- name: CountSigils :one
+SELECT count(*) FROM authors
+WHERE id <> @at_param AND id <> :colon_param AND id <> $dollar_param;
+
+-- name: TopAuthors :many
+WITH ranked AS (
+ SELECT id, name FROM authors
+)
+SELECT * FROM ranked;
+
+-- name: AddAuthor :exec
+INSERT INTO authors (name, bio)
+VALUES (?, ?);
+
+-- name: MakeScratch :exec
+CREATE TABLE scratch (
+ id INTEGER NOT NULL,
+ label TEXT
+);
+
+-- name: MakeMeasurements :exec
+CREATE TABLE IF NOT EXISTS measurements (
+ id INTEGER PRIMARY KEY,
+ label VARYING CHARACTER(120),
+ ratio DECIMAL(10,5),
+ note
+);
+
+-- name: KeepAutoinc :exec
+CREATE TABLE counters (id INTEGER PRIMARY KEY AUTOINCREMENT, hits INTEGER DEFAULT 0);
+
+-- name: CastLabel :one
+SELECT CAST(bio AS VARYING CHARACTER(120)) FROM authors LIMIT 1;
+
+-- name: MakeSearchIndex :exec
+CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+
+-- name: MakeRecipeIndex :exec
+CREATE VIRTUAL TABLE recipes_fts USING fts5(
+ name,
+ ingredients
+);
diff --git a/internal/endtoend/testdata/fmt/sqlite/schema.sql b/internal/endtoend/testdata/fmt/sqlite/schema.sql
new file mode 100644
index 000000000..1d42f1cc1
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/schema.sql
@@ -0,0 +1,11 @@
+CREATE TABLE authors (
+ id integer PRIMARY KEY,
+ name text NOT NULL,
+ bio text
+);
+
+CREATE TABLE "Events" (
+ id integer PRIMARY KEY,
+ "EventName" text NOT NULL,
+ "order" integer NOT NULL
+);
diff --git a/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml b/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml
new file mode 100644
index 000000000..0b5a97a99
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+ - engine: "sqlite"
+ schema: "schema.sql"
+ queries: "query.sql"
+ gen:
+ go:
+ package: "querytest"
+ out: "go"
diff --git a/internal/endtoend/testdata/fmt/sqlite/stdout.txt b/internal/endtoend/testdata/fmt/sqlite/stdout.txt
new file mode 100644
index 000000000..d7572ead9
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/stdout.txt
@@ -0,0 +1,66 @@
+--- a/query.sql
++++ b/query.sql
+@@ -1,12 +1,15 @@
+ -- name: GetAuthor :one
++SELECT id, name, bio
++FROM authors
++WHERE id = ?
++LIMIT 1;
+-select id,name , bio from authors
+-where id = ? limit 1;
+
+ -- name: PickyQuery :many
++SELECT
++ id, -- the primary key
++ name,
++ -- computed downstream
++ bio
+-SELECT id, -- the primary key
+- name,
+- -- computed downstream
+- bio
+ FROM authors
+ -- soft-deleted rows are filtered
+ WHERE bio IS NOT NULL
+@@ -16,7 +19,8 @@
+ SELECT /* inline note */ id, name FROM authors ORDER BY name;
+
+ -- name: ListAuthors :many
++SELECT id, name, bio
++FROM authors
+-SELECT id, name, bio FROM authors
+ ORDER BY name;
+
+ -- name: GetEvent :one
+@@ -23,8 +27,11 @@
+ SELECT "EventName", "order"
++FROM "Events"
++WHERE id = ?
++LIMIT 1;
+-FROM "Events" WHERE id = ? LIMIT 1;
+
+ -- name: CountSigils :one
++SELECT count(*)
++FROM authors
+-SELECT count(*) FROM authors
+ WHERE id <> @at_param AND id <> :colon_param AND id <> $dollar_param;
+
+ -- name: TopAuthors :many
+@@ -46,7 +53,7 @@
+ -- name: MakeMeasurements :exec
+ CREATE TABLE IF NOT EXISTS measurements (
+ id INTEGER PRIMARY KEY,
++ label VARYING CHARACTER(120),
+- label VARYING CHARACTER(120),
+ ratio DECIMAL(10,5),
+ note
+ );
+@@ -58,7 +65,7 @@
+ SELECT CAST(bio AS VARYING CHARACTER(120)) FROM authors LIMIT 1;
+
+ -- name: MakeSearchIndex :exec
++CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+-CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+
+ -- name: MakeRecipeIndex :exec
+ CREATE VIRTUAL TABLE recipes_fts USING fts5(
diff --git a/internal/engine/clickhouse/format.go b/internal/engine/clickhouse/format.go
index c103c7803..997af7d41 100644
--- a/internal/engine/clickhouse/format.go
+++ b/internal/engine/clickhouse/format.go
@@ -22,12 +22,6 @@ func (p *Parser) Param(n int) string {
return "?"
}
-// NamedParam returns the named parameter placeholder for the given name.
-// ClickHouse uses {name:Type} syntax for named parameters.
-func (p *Parser) NamedParam(name string) string {
- return "{" + name + ":String}"
-}
-
// Cast returns a type cast expression.
// ClickHouse uses CAST(expr AS type) syntax, same as MySQL.
func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/dolphin/convert.go b/internal/engine/dolphin/convert.go
index cfd83b5c4..13506ce6c 100644
--- a/internal/engine/dolphin/convert.go
+++ b/internal/engine/dolphin/convert.go
@@ -560,9 +560,28 @@ func (c *cc) convertSelectField(n *pcast.SelectField) *ast.ResTarget {
}
func (c *cc) convertSelectStmt(n *pcast.SelectStmt) *ast.SelectStmt {
+ // The ORDER BY expressions are recorded twice: bare in WindowClause,
+ // where the compiler's strict_order_by validation expects them, and
+ // wrapped in SortBy nodes in SortClause, which carries the sort
+ // direction and is what formatting prints. Both share the same
+ // converted nodes so parameter numbering stays intact.
windowClause := &ast.List{Items: make([]ast.Node, 0)}
- orderByClause := c.convertOrderByClause(n.OrderBy)
- if orderByClause != nil {
+ var sortClause *ast.List
+ if n.OrderBy != nil {
+ sortClause = &ast.List{Items: make([]ast.Node, 0)}
+ orderByClause := &ast.List{Items: []ast.Node{}}
+ for _, item := range n.OrderBy.Items {
+ expr := c.convert(item.Expr)
+ orderByClause.Items = append(orderByClause.Items, expr)
+ dir := ast.SortByDirDefault
+ if item.Desc {
+ dir = ast.SortByDirDesc
+ }
+ sortClause.Items = append(sortClause.Items, &ast.SortBy{
+ Node: expr,
+ SortbyDir: dir,
+ })
+ }
windowClause.Items = append(windowClause.Items, orderByClause)
}
@@ -575,6 +594,7 @@ func (c *cc) convertSelectStmt(n *pcast.SelectStmt) *ast.SelectStmt {
WhereClause: c.convert(n.Where),
WithClause: c.convertWithClause(n.With),
WindowClause: windowClause,
+ SortClause: sortClause,
Op: op,
All: all,
}
@@ -1242,11 +1262,20 @@ func (c *cc) convertPatternInExpr(n *pcast.PatternInExpr) ast.Node {
}
func (c *cc) convertPatternLikeExpr(n *pcast.PatternLikeOrIlikeExpr) ast.Node {
+ kind := ast.A_Expr_Kind_ILIKE
+ op := "~~*"
+ if n.IsLike {
+ kind = ast.A_Expr_Kind_LIKE
+ op = "~~"
+ }
+ if n.Not {
+ op = "!" + op
+ }
return &ast.A_Expr{
- Kind: ast.A_Expr_Kind(9),
+ Kind: kind,
Name: &ast.List{
Items: []ast.Node{
- &ast.String{Str: "~~"},
+ &ast.String{Str: op},
},
},
Lexpr: c.convert(n.Expr),
diff --git a/internal/engine/dolphin/format.go b/internal/engine/dolphin/format.go
index 9c6346756..458ae0236 100644
--- a/internal/engine/dolphin/format.go
+++ b/internal/engine/dolphin/format.go
@@ -29,13 +29,6 @@ func (p *Parser) Param(n int) string {
return "?"
}
-// NamedParam returns the named parameter placeholder for the given name.
-// MySQL doesn't have native named parameters, so we use ? (positional).
-// The actual parameter names are handled by sqlc's rewrite phase.
-func (p *Parser) NamedParam(name string) string {
- return "?"
-}
-
// Cast returns a type cast expression.
// MySQL uses CAST(expr AS type) syntax.
func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/postgresql/reserved.go b/internal/engine/postgresql/reserved.go
index b03a6a7e9..25cebb16e 100644
--- a/internal/engine/postgresql/reserved.go
+++ b/internal/engine/postgresql/reserved.go
@@ -64,12 +64,6 @@ func (p *Parser) Param(n int) string {
return fmt.Sprintf("$%d", n)
}
-// NamedParam returns the named parameter placeholder for the given name.
-// PostgreSQL/sqlc uses @name syntax.
-func (p *Parser) NamedParam(name string) string {
- return "@" + name
-}
-
// Cast returns a type cast expression.
// PostgreSQL uses expr::type syntax.
func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/sqlite/convert.go b/internal/engine/sqlite/convert.go
index 88bc27981..a4e2364e8 100644
--- a/internal/engine/sqlite/convert.go
+++ b/internal/engine/sqlite/convert.go
@@ -14,9 +14,10 @@ import (
// cc converts a meyer syntax tree into sqlc's engine-independent AST. One
// converter is used per statement; paramCount numbers the anonymous "?"
-// markers within it.
+// markers within it, and src is the source the statement was parsed from.
type cc struct {
paramCount int
+ src string
}
func todo(funcname string, n meyer.Node) *ast.TODO {
@@ -214,15 +215,21 @@ func (c *cc) convertAlterTableStmt(n *meyer.AlterTableStmt) ast.Node {
}
name := identifier(def.Name)
return &ast.AlterTableStmt{
- Table: parseTableName(n.Table),
+ Table: parseTableName(n.Table),
+ Incomplete: !representableColumn(def),
Cmds: &ast.List{Items: []ast.Node{
&ast.AlterTableCmd{
Name: &name,
Subtype: ast.AT_AddColumn,
Def: &ast.ColumnDef{
- Colname: name,
- TypeName: &ast.TypeName{Name: columnTypeName(def.Type)},
- IsNotNull: hasNotNullConstraint(def.Constraints),
+ Colname: name,
+ TypeName: &ast.TypeName{
+ Name: columnTypeName(def.Type),
+ Spelling: typeSpelling(def.Type),
+ },
+ Typeless: def.Type == nil,
+ IsNotNull: hasNotNullConstraint(def.Constraints),
+ PrimaryKey: hasPrimaryKeyConstraint(def.Constraints),
},
},
}},
@@ -278,12 +285,24 @@ func (c *cc) convertCreateTableStmt(n *meyer.CreateTableStmt) ast.Node {
stmt := &ast.CreateTableStmt{
Name: parseTableName(n.Name),
IfNotExists: n.IfNotExists,
+ // The node models none of these, so a statement carrying them has
+ // no faithful rendering and the formatter keeps it as written.
+ Incomplete: n.Temp || n.Select != nil || len(n.Constraints) > 0 || len(n.Options) > 0,
}
for _, def := range n.Columns {
+ if !representableColumn(def) {
+ stmt.Incomplete = true
+ }
stmt.Cols = append(stmt.Cols, &ast.ColumnDef{
- Colname: identifier(def.Name),
- IsNotNull: hasNotNullConstraint(def.Constraints),
- TypeName: &ast.TypeName{Name: columnTypeName(def.Type)},
+ Colname: identifier(def.Name),
+ IsNotNull: hasNotNullConstraint(def.Constraints),
+ PrimaryKey: hasPrimaryKeyConstraint(def.Constraints),
+ TypeName: &ast.TypeName{
+ Name: columnTypeName(def.Type),
+ Spelling: typeSpelling(def.Type),
+ },
+ Typeless: def.Type == nil,
+ Location: def.Pos(),
})
}
return stmt
@@ -306,6 +325,19 @@ func (c *cc) convertCreateVirtualTableFTS5(n *meyer.CreateVirtualTableStmt) ast.
stmt := &ast.CreateTableStmt{
Name: parseTableName(n.Name),
IfNotExists: n.IfNotExists,
+ Using: identifier(n.Module),
+ }
+ if n.HasArgs {
+ stmt.ModuleArgs = n.Args
+ if stmt.ModuleArgs == nil {
+ stmt.ModuleArgs = []string{}
+ }
+ // The arguments carry no spans of their own, so the author's exact
+ // breaks cannot be kept; a declaration written across lines keeps
+ // the canonical broken form instead.
+ if n.Pos() >= 0 && n.End() <= len(c.src) {
+ stmt.ModuleArgsMultiline = strings.Contains(c.src[n.Pos():n.End()], "\n")
+ }
}
// The module arguments of a virtual table are an arbitrary token
@@ -462,7 +494,8 @@ func (c *cc) convertColumnNames(cols []*meyer.Ident) *ast.List {
for _, col := range cols {
name := identifier(col)
list.Items = append(list.Items, &ast.ResTarget{
- Name: &name,
+ Name: &name,
+ Location: col.Pos(),
})
}
return list
@@ -891,9 +924,20 @@ func (c *cc) convertBindParam(n *meyer.BindParam) ast.Node {
}
default:
// A named parameter. sqlc carries the name through as the operand of
- // a pseudo-operator and resolves it later.
+ // a pseudo-operator and resolves it later. The operator is the
+ // parameter's own sigil, so the formatter can print the spelling the
+ // author chose — SQLite accepts :name, @name and $name, but sqlc
+ // gives them different meanings, so they must never be rewritten
+ // into one another.
+ sigil := "@"
+ switch n.Kind {
+ case meyer.ParamColon:
+ sigil = ":"
+ case meyer.ParamDollar:
+ sigil = "$"
+ }
return &ast.A_Expr{
- Name: &ast.List{Items: []ast.Node{&ast.String{Str: "@"}}},
+ Name: &ast.List{Items: []ast.Node{&ast.String{Str: sigil}}},
Rexpr: &ast.String{Str: n.Name},
Location: n.Pos(),
}
@@ -1046,6 +1090,7 @@ func (c *cc) convertCastExpr(n *meyer.CastExpr) ast.Node {
Arg: c.convert(n.X),
TypeName: &ast.TypeName{
Name: name,
+ Spelling: typeSpelling(n.Type),
Names: &ast.List{Items: []ast.Node{&ast.String{Str: strings.ToLower(name)}}},
ArrayBounds: &ast.List{},
},
diff --git a/internal/engine/sqlite/format.go b/internal/engine/sqlite/format.go
index 39ac859ca..374c23b18 100644
--- a/internal/engine/sqlite/format.go
+++ b/internal/engine/sqlite/format.go
@@ -1,13 +1,35 @@
package sqlite
-// QuoteIdent returns a quoted identifier if it needs quoting.
-// SQLite uses double quotes for quoting identifiers (SQL standard),
-// though backticks are also supported for MySQL compatibility.
+import "strings"
+
+// QuoteIdent quotes an identifier when printing it bare would change what it
+// names: the parser folds unquoted identifiers to lower case, so any name
+// that is not already a plain lower-case identifier — or that collides with
+// a keyword — only survives a parse round-trip inside double quotes.
func (p *Parser) QuoteIdent(s string) string {
- // For now, don't quote - return as-is
+ if s == "" || p.IsReservedKeyword(s) || !plainIdent(s) {
+ return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
+ }
return s
}
+// plainIdent reports whether s parses back as itself unquoted: ASCII
+// lower-case letters, digits and underscores, not starting with a digit.
+func plainIdent(s string) bool {
+ for i, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z', r == '_':
+ case r >= '0' && r <= '9':
+ if i == 0 {
+ return false
+ }
+ default:
+ return false
+ }
+ }
+ return true
+}
+
// TypeName returns the SQL type name for the given namespace and name.
func (p *Parser) TypeName(ns, name string) string {
if ns != "" {
@@ -22,12 +44,6 @@ func (p *Parser) Param(n int) string {
return "?"
}
-// NamedParam returns the named parameter placeholder for the given name.
-// SQLite uses :name syntax for named parameters.
-func (p *Parser) NamedParam(name string) string {
- return ":" + name
-}
-
// Cast returns a type cast expression.
// SQLite uses CAST(expr AS type) syntax.
func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/sqlite/parse.go b/internal/engine/sqlite/parse.go
index 25acfd689..325dab2cd 100644
--- a/internal/engine/sqlite/parse.go
+++ b/internal/engine/sqlite/parse.go
@@ -3,9 +3,11 @@ package sqlite
import (
"errors"
"io"
+ "strings"
meyer "github.com/sqlc-dev/meyer/ast"
"github.com/sqlc-dev/meyer/parser"
+ mtoken "github.com/sqlc-dev/meyer/token"
"github.com/sqlc-dev/sqlc/internal/source"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
@@ -26,12 +28,22 @@ type Parser struct {
var parseOptions = parser.Options{UpdateDeleteLimit: true}
func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
+ f, err := p.ParseFile(r)
+ if err != nil {
+ return nil, err
+ }
+ return f.Stmts, nil
+}
+
+// ParseFile parses like Parse and also carries the file's comments, taken
+// from the trivia meyer's single lexer pass produces alongside the tokens.
+func (p *Parser) ParseFile(r io.Reader) (*ast.File, error) {
blob, err := io.ReadAll(r)
if err != nil {
return nil, err
}
src := string(blob)
- parsed, err := parseOptions.ParseString(src)
+ parsed, err := parseOptions.ParseFile(src)
if err != nil {
return nil, normalizeErr(err)
}
@@ -41,8 +53,8 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
// that a statement's extent covers the comments written above it. sqlc
// reads the "-- name:" annotation out of that range.
loc := 0
- for _, raw := range parsed {
- converter := &cc{}
+ for _, raw := range parsed.Stmts {
+ converter := &cc{src: src}
out := converter.convert(raw)
if _, ok := out.(*ast.TODO); !ok {
stmts = append(stmts, ast.Statement{
@@ -55,7 +67,36 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
}
loc = raw.End()
}
- return stmts, nil
+
+ var comments []ast.Comment
+ for _, tr := range parsed.Trivia {
+ if tr.Kind != mtoken.COMMENT {
+ continue
+ }
+ comments = append(comments, ast.Comment{
+ Text: strings.TrimRight(tr.Text(src), " \t\r\n"),
+ Start: tr.Pos,
+ End: tr.End,
+ OwnLine: ownLine(src, tr.Pos),
+ })
+ }
+ return &ast.File{Stmts: stmts, Comments: comments}, nil
+}
+
+// ownLine reports that only blank space sits between the preceding line
+// break and pos.
+func ownLine(src string, pos int) bool {
+ for j := pos - 1; j >= 0; j-- {
+ switch src[j] {
+ case '\n':
+ return true
+ case ' ', '\t', '\r':
+ continue
+ default:
+ return false
+ }
+ }
+ return true
}
// trimTerminator returns the end of stmt with its terminating semicolon, and
diff --git a/internal/engine/sqlite/utils.go b/internal/engine/sqlite/utils.go
index e81b6f3fa..3e4a03e64 100644
--- a/internal/engine/sqlite/utils.go
+++ b/internal/engine/sqlite/utils.go
@@ -76,6 +76,60 @@ func typeName(n *meyer.TypeName) string {
return sb.String()
}
+// typeSpelling returns the type as the author wrote it — identifier tokens
+// space-joined, arguments as written — for the formatter to print back.
+// typeName folds the spaces out for catalog matching.
+func typeSpelling(n *meyer.TypeName) string {
+ if n == nil {
+ return ""
+ }
+ var sb strings.Builder
+ sb.WriteString(n.Name)
+ if len(n.Args) > 0 {
+ sb.WriteString("(")
+ sb.WriteString(strings.Join(n.Args, ","))
+ sb.WriteString(")")
+ }
+ return sb.String()
+}
+
+// representableColumn reports whether a column definition round-trips
+// through the fields ast.ColumnDef models: a plain NOT NULL, a plain
+// PRIMARY KEY, or nothing. Anything else — a named constraint, a conflict
+// clause, ASC/DESC or AUTOINCREMENT, DEFAULT, UNIQUE, CHECK, COLLATE,
+// REFERENCES, GENERATED — is parsed away, so a statement printing such a
+// column would lose it. NOT NULL next to PRIMARY KEY is also beyond the
+// node: SQLite's PRIMARY KEY does not imply NOT NULL, and the printed form
+// carries only one of the pair.
+func representableColumn(def *meyer.ColumnDef) bool {
+ var notNull, primary bool
+ for _, con := range def.Constraints {
+ switch {
+ case con.Name != nil:
+ return false
+ case con.Kind == meyer.ColumnNotNull && con.OnConflict == meyer.ConflictDefault:
+ notNull = true
+ case con.Kind == meyer.ColumnPrimaryKey && con.OnConflict == meyer.ConflictDefault &&
+ con.Order == meyer.SortDefault && !con.AutoIncrement:
+ primary = true
+ default:
+ return false
+ }
+ }
+ return !(notNull && primary)
+}
+
+// hasPrimaryKeyConstraint reports whether a column definition carries a
+// PRIMARY KEY constraint.
+func hasPrimaryKeyConstraint(constraints []*meyer.ColumnConstraint) bool {
+ for _, constraint := range constraints {
+ if constraint.Kind == meyer.ColumnPrimaryKey {
+ return true
+ }
+ }
+ return false
+}
+
// hasNotNullConstraint reports whether a column definition guarantees a
// value. A PRIMARY KEY implies NOT NULL for the purposes of code
// generation, matching the behavior of the previous parser.
diff --git a/internal/sql/ast/CLAUDE.md b/internal/sql/ast/CLAUDE.md
index ee62274d6..3c5d3381c 100644
--- a/internal/sql/ast/CLAUDE.md
+++ b/internal/sql/ast/CLAUDE.md
@@ -7,16 +7,67 @@ This package defines the Abstract Syntax Tree (AST) nodes used by sqlc to repres
### Node Interface
All AST nodes implement the `Node` interface with:
- `Pos() int` - returns the source position
-- `Format(buf *TrackedBuffer)` - formats the node back to SQL
+- `Format(buf *TrackedBuffer, d format.Dialect)` - formats the node back to SQL
### TrackedBuffer
-The `TrackedBuffer` type (`pg_query.go`) handles SQL formatting with dialect-specific behavior:
+The `TrackedBuffer` type (`print.go`) handles SQL formatting with dialect-specific behavior:
- `astFormat(node Node)` - formats any AST node
- `join(list *List, sep string)` - joins list items with separator
- `WriteString(s string)` - writes raw SQL
- `QuoteIdent(name string)` - quotes identifiers (dialect-specific)
- `TypeName(ns, name string)` - formats type names (dialect-specific)
+### Pretty printing
+The doc renderer lives in `ast/printer` (`printer.Buffer`), which knows
+nothing about AST nodes; `TrackedBuffer` embeds it and adds the
+AST-facing layer (`astFormat`, comment emission, anchors).
+`TrackedBuffer` records a Wadler-style document (the model behind Prettier
+and ruff): Format methods emit text plus layout tokens, and the renderer
+decides which break opportunities become newlines.
+
+- `Line()` - a space when the group fits on one line, a newline otherwise
+- `Softline()` - nothing when the group fits, a newline otherwise
+- `Group()` / `EndGroup()` - a region laid out flat when its width fits
+- `Indent()` / `EndIndent()` - one level deeper (2 spaces) after breaks
+- `Breaker()` - forces every enclosing group to break (measures as
+ infinitely wide)
+- `joinComma(list)` - joins items with `,` + `Line()`
+- `condition(node)` - clause-level AND/OR chain without outer parentheses,
+ one branch per line when broken
+
+`ast.Format(n, d)` renders on a single line (all breaks collapse);
+`ast.Pretty(n, d, width)` breaks lines to fit `width` columns. Statement
+Format methods open a group and put `Line()` before each clause keyword
+(`FROM`, `WHERE`, ...), so a statement that fits stays on one line and a
+long one breaks at clause boundaries. When adding a Format method, write
+tokens so the flat rendering is correct SQL; layout tokens are optional.
+
+The fmt command does not pass a real width: like gofmt it never rewraps
+on its own, so it prints with an effectively infinite width and defers
+to the author's line breaks instead. `AttachComments` records, for each
+emission-point marker, whether its neighbouring printed nodes sat on
+different source lines; when they did, `boundary()` emits a `Breaker()`
+there on the real print, so the group the author broke stays broken and
+everything else stays flat.
+
+### Comments
+`ast.File{Stmts, Comments}` is what a comment-surfacing parser returns
+(SQLite via meyer's ParseFile). `AttachComments(raw, d, comments, src)`
+classifies each comment once, against a dry-run of the printer: source
+positions and line numbers decide trailing (same line as the code
+before) vs leading, and each comment is attached to the emission point
+— node or clause/list boundary — where the printer will reach it. From
+then on positions are never consulted: `PrettyWithComments(n, d, width,
+table)` emits by node identity, which is what lets edited or synthetic
+trees print their comments correctly (the dave/dst model; each record
+also keeps the node the comment followed, for future rewriting tools).
+A line comment forces every enclosing group to break — `hardline` and
+`breaker` tokens measure as infinitely wide — so commented statements
+format instead of collapsing. Emission points (`beforeClause`,
+`boundary` in joinComma/condition) double as classification markers on
+the dry run, guaranteeing attach-time decisions and print-time emission
+agree.
+
### Dialect Interface
Dialect-specific formatting is handled via the `Dialect` interface:
```go
diff --git a/internal/sql/ast/a_expr.go b/internal/sql/ast/a_expr.go
index 4e67967ba..2605db59d 100644
--- a/internal/sql/ast/a_expr.go
+++ b/internal/sql/ast/a_expr.go
@@ -1,6 +1,10 @@
package ast
-import "github.com/sqlc-dev/sqlc/internal/sql/format"
+import (
+ "strings"
+
+ "github.com/sqlc-dev/sqlc/internal/sql/format"
+)
type A_Expr struct {
Kind A_Expr_Kind
@@ -14,23 +18,43 @@ func (n *A_Expr) Pos() int {
return n.Location
}
-// isNamedParam returns true if this A_Expr represents a named parameter (@name)
-// and extracts the parameter name if so.
-func (n *A_Expr) isNamedParam() (string, bool) {
+// isNamedParam reports whether this A_Expr represents a named parameter,
+// returning its sigil and name. Engines encode a named parameter as a
+// prefix pseudo-operator carrying the sigil the author wrote (@name for
+// most engines; SQLite also spells :name and $name). The spellings mean
+// different things to sqlc, so the printer emits the one it was given.
+func (n *A_Expr) isNamedParam() (sigil, name string, ok bool) {
if n.Name == nil || len(n.Name.Items) != 1 {
- return "", false
+ return "", "", false
}
- s, ok := n.Name.Items[0].(*String)
- if !ok || s.Str != "@" {
- return "", false
+ s, sok := n.Name.Items[0].(*String)
+ if !sok || (s.Str != "@" && s.Str != ":" && s.Str != "$") {
+ return "", "", false
}
if set(n.Lexpr) || !set(n.Rexpr) {
- return "", false
+ return "", "", false
+ }
+ if nameStr, sok := n.Rexpr.(*String); sok {
+ return s.Str, nameStr.Str, true
}
- if nameStr, ok := n.Rexpr.(*String); ok {
- return nameStr.Str, true
+ // Before the compiler rewrites named parameters, @name parses as the @
+ // operator applied to a bare column reference.
+ if col, sok := n.Rexpr.(*ColumnRef); sok && col.Fields != nil && len(col.Fields.Items) == 1 {
+ if f, sok := col.Fields.Items[0].(*String); sok {
+ return s.Str, f.Str, true
+ }
}
- return "", false
+ return "", "", false
+}
+
+// negated returns true when the expression's operator carries the negated
+// spelling of a pattern-match operator (e.g. "!~~" for NOT LIKE).
+func (n *A_Expr) negated() bool {
+ if n.Name == nil || len(n.Name.Items) != 1 {
+ return false
+ }
+ s, ok := n.Name.Items[0].(*String)
+ return ok && strings.HasPrefix(s.Str, "!")
}
func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
@@ -39,8 +63,9 @@ func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
}
// Check for named parameter first (works regardless of Kind)
- if name, ok := n.isNamedParam(); ok {
- buf.WriteString(d.NamedParam(name))
+ if sigil, name, ok := n.isNamedParam(); ok {
+ buf.WriteString(sigil)
+ buf.WriteString(name)
return
}
@@ -52,11 +77,19 @@ func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
buf.WriteString(")")
case A_Expr_Kind_LIKE:
buf.astFormat(n.Lexpr, d)
- buf.WriteString(" LIKE ")
+ if n.negated() {
+ buf.WriteString(" NOT LIKE ")
+ } else {
+ buf.WriteString(" LIKE ")
+ }
buf.astFormat(n.Rexpr, d)
case A_Expr_Kind_ILIKE:
buf.astFormat(n.Lexpr, d)
- buf.WriteString(" ILIKE ")
+ if n.negated() {
+ buf.WriteString(" NOT ILIKE ")
+ } else {
+ buf.WriteString(" ILIKE ")
+ }
buf.astFormat(n.Rexpr, d)
case A_Expr_Kind_SIMILAR:
buf.astFormat(n.Lexpr, d)
diff --git a/internal/sql/ast/alter_table_stmt.go b/internal/sql/ast/alter_table_stmt.go
index 4dc88707f..afbf014b0 100644
--- a/internal/sql/ast/alter_table_stmt.go
+++ b/internal/sql/ast/alter_table_stmt.go
@@ -9,6 +9,10 @@ type AlterTableStmt struct {
Cmds *List
MissingOk bool
Relkind ObjectType
+ // Incomplete marks a statement whose source carried syntax this node
+ // does not model, such as column constraints beyond plain NOT NULL and
+ // PRIMARY KEY on an added column. No faithful rendering exists for it.
+ Incomplete bool
}
func (n *AlterTableStmt) Pos() int {
@@ -19,6 +23,12 @@ func (n *AlterTableStmt) Format(buf *TrackedBuffer, d format.Dialect) {
if n == nil {
return
}
+ // An incomplete statement cannot be printed back: part of its source
+ // was parsed away. Render nothing, which no verification accepts, so
+ // the formatter keeps the statement as written.
+ if n.Incomplete {
+ return
+ }
buf.WriteString("ALTER TABLE ")
buf.astFormat(n.Relation, d)
buf.astFormat(n.Table, d)
diff --git a/internal/sql/ast/bool_expr.go b/internal/sql/ast/bool_expr.go
index f2c0243a9..65b4af53d 100644
--- a/internal/sql/ast/bool_expr.go
+++ b/internal/sql/ast/bool_expr.go
@@ -35,15 +35,34 @@ func (n *BoolExpr) Format(buf *TrackedBuffer, d format.Dialect) {
buf.astFormat(n.Args.Items[0], d)
}
default:
+ var op string
+ switch n.Boolop {
+ case BoolExprTypeAnd:
+ op = "AND "
+ case BoolExprTypeOr:
+ op = "OR "
+ }
buf.WriteString("(")
- if items(n.Args) {
- switch n.Boolop {
- case BoolExprTypeAnd:
- buf.join(n.Args, d, " AND ")
- case BoolExprTypeOr:
- buf.join(n.Args, d, " OR ")
+ buf.Group()
+ buf.Indent()
+ buf.Softline()
+ if items(n.Args) && op != "" {
+ first := true
+ for _, item := range n.Args.Items {
+ if _, ok := item.(*TODO); ok {
+ continue
+ }
+ if !first {
+ buf.Line()
+ buf.WriteString(op)
+ }
+ first = false
+ buf.astFormat(item, d)
}
}
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
}
diff --git a/internal/sql/ast/column_def.go b/internal/sql/ast/column_def.go
index 2a1c01575..6ac6a6e0c 100644
--- a/internal/sql/ast/column_def.go
+++ b/internal/sql/ast/column_def.go
@@ -3,8 +3,12 @@ package ast
import "github.com/sqlc-dev/sqlc/internal/sql/format"
type ColumnDef struct {
- Colname string
+ Colname string
+ // TypeName is the column's type for the catalog. When Typeless is set
+ // the author wrote no type at all — SQLite allows it — and the column
+ // prints without one, whatever TypeName carries.
TypeName *TypeName
+ Typeless bool
IsNotNull bool
IsUnsigned bool
IsArray bool
@@ -44,8 +48,10 @@ func (n *ColumnDef) Format(buf *TrackedBuffer, d format.Dialect) {
return
}
buf.WriteString(n.Colname)
- buf.WriteString(" ")
- buf.astFormat(n.TypeName, d)
+ if !n.Typeless {
+ buf.WriteString(" ")
+ buf.astFormat(n.TypeName, d)
+ }
// Use IsArray from ColumnDef since TypeName.ArrayBounds may not be set
// (for type resolution compatibility)
if n.IsArray && !items(n.TypeName.ArrayBounds) {
diff --git a/internal/sql/ast/comment.go b/internal/sql/ast/comment.go
new file mode 100644
index 000000000..ea877328b
--- /dev/null
+++ b/internal/sql/ast/comment.go
@@ -0,0 +1,235 @@
+package ast
+
+import (
+ "sort"
+
+ "github.com/sqlc-dev/sqlc/internal/sql/format"
+)
+
+// File is a parsed query file: its statements together with the comments
+// the parser's lexer saw. Engines whose parsers surface their trivia — the
+// lexical channel of whitespace and comments the grammar never sees, in
+// Roslyn's terminology — return it from ParseFile, so the formatter gets
+// statements and comments from one lexer pass.
+type File struct {
+ Stmts []Statement
+ Comments []Comment
+}
+
+// Comment is a single SQL comment, positioned by byte offsets into the
+// source the statement was parsed from — the same coordinates the engine
+// parsers stamp on nodes.
+type Comment struct {
+ // Text is the comment as written, marker included ("-- x", "/* x */").
+ Text string
+ Start int
+ End int
+ // OwnLine reports that only blank space preceded the comment on its
+ // line, so it leads the code after it rather than trailing the code
+ // before it.
+ OwnLine bool
+}
+
+// Line reports whether the comment runs to the end of its line (-- or #),
+// so nothing may be printed after it on the same line.
+func (c Comment) Line() bool {
+ return len(c.Text) < 2 || c.Text[0] != '/' || c.Text[1] != '*'
+}
+
+// commentRec is one attached comment: the anchor nodes on either side of it
+// in print order, and whether it trails the code before it (same source
+// line) or leads the code after it (its own line).
+//
+// The next anchor is where the printer emits the comment; the prev anchor
+// is the node the comment belongs to when the tree is edited — a trailing
+// comment travels with the node it annotates, the way dave/dst attaches
+// decorations in the Go ecosystem.
+type commentRec struct {
+ c Comment
+ prev, next Node
+ trailing bool
+}
+
+// CommentTable holds a statement's comments attached to its nodes. It is
+// built once by AttachComments, before any printing (or, later, editing):
+// each comment is classified against the statement's anchor nodes by source
+// position and line, and from then on positions are never consulted again —
+// the printer emits comments by node identity, which is what lets an edited
+// or synthetic tree print its comments correctly.
+type CommentTable struct {
+ recs []commentRec
+ // byNext indexes recs by their next anchor, in source order; end holds
+ // the comments with no anchor after them, which trail the statement.
+ byNext map[Node][]int
+ end []int
+ taken []bool
+ nTaken int
+ // breaks marks the emission points where the author broke the line:
+ // the printer keeps those breaks, gofmt-style, instead of imposing a
+ // line width.
+ breaks map[Node]bool
+}
+
+// breakAt reports whether the author broke the line at this emission point.
+func (t *CommentTable) breakAt(n Node) bool {
+ return t != nil && t.breaks[n]
+}
+
+// Exhausted reports whether every attached comment was printed.
+func (t *CommentTable) Exhausted() bool {
+ return t == nil || t.nTaken == len(t.recs)
+}
+
+// take returns and consumes the comments anchored to n, in order.
+func (t *CommentTable) take(n Node) []commentRec {
+ if t == nil || n == nil {
+ return nil
+ }
+ idxs := t.byNext[n]
+ if len(idxs) == 0 {
+ return nil
+ }
+ out := make([]commentRec, 0, len(idxs))
+ for _, i := range idxs {
+ if t.taken[i] {
+ continue
+ }
+ t.taken[i] = true
+ t.nTaken++
+ out = append(out, t.recs[i])
+ }
+ return out
+}
+
+// takeRemaining returns and consumes every comment not yet printed; the
+// statement is over, so everything left trails it.
+func (t *CommentTable) takeRemaining() []commentRec {
+ if t == nil {
+ return nil
+ }
+ var out []commentRec
+ for i := range t.recs {
+ if t.taken[i] {
+ continue
+ }
+ t.taken[i] = true
+ t.nTaken++
+ out = append(out, t.recs[i])
+ }
+ return out
+}
+
+// AttachComments classifies a statement's interior comments against its
+// nodes, producing the table the printer (and any future rewriting tool)
+// works from. Placement follows gofmt's rules, decided here once from
+// source positions and lines: a comment on the same line as the code before
+// it trails that code; any other comment leads the first node printed after
+// it; a comment after the last node trails the statement.
+func AttachComments(raw *RawStmt, d format.Dialect, comments []Comment, src string) *CommentTable {
+ anchors := collectAnchors(raw, d)
+ lines := []int{0}
+ for i := 0; i < len(src); i++ {
+ if src[i] == '\n' {
+ lines = append(lines, i+1)
+ }
+ }
+ lineOf := func(pos int) int {
+ return sort.SearchInts(lines, pos+1) - 1
+ }
+
+ table := &CommentTable{byNext: make(map[Node][]int, len(anchors))}
+ for _, c := range comments {
+ // prev: the printed node with the greatest position before the
+ // comment (for the trailing/leading call). next: the emission point
+ // for the first printed node after the comment — the node itself,
+ // or, when boundary markers immediately precede it in print order,
+ // the earliest of those markers, which is where the printer will
+ // look for this comment first.
+ var prev, next Node
+ prevPos := -1
+ for _, a := range anchors {
+ if !a.marker && a.pos < c.Start && a.pos > prevPos {
+ prev, prevPos = a.node, a.pos
+ }
+ }
+ for i, a := range anchors {
+ if a.marker || a.pos <= c.Start {
+ continue
+ }
+ j := i
+ for j > 0 && anchors[j-1].marker {
+ j--
+ }
+ next = anchors[j].node
+ break
+ }
+ rec := commentRec{
+ c: c,
+ prev: prev,
+ next: next,
+ trailing: !c.OwnLine && prev != nil && lineOf(prevPos) == lineOf(c.Start),
+ }
+ table.recs = append(table.recs, rec)
+ i := len(table.recs) - 1
+ if next == nil {
+ table.end = append(table.end, i)
+ } else {
+ table.byNext[next] = append(table.byNext[next], i)
+ }
+ }
+ table.taken = make([]bool, len(table.recs))
+
+ // Record where the author broke the line: an emission point whose
+ // neighbouring printed nodes sit on different source lines. The printer
+ // keeps these breaks (and only imposes new ones for comments), so the
+ // statement's shape stays the author's.
+ table.breaks = make(map[Node]bool)
+ for i, a := range anchors {
+ if !a.marker {
+ continue
+ }
+ prevPos, nextPos := -1, -1
+ for j := i - 1; j >= 0; j-- {
+ if !anchors[j].marker {
+ prevPos = anchors[j].pos
+ break
+ }
+ }
+ for j := i + 1; j < len(anchors); j++ {
+ if !anchors[j].marker {
+ nextPos = anchors[j].pos
+ break
+ }
+ }
+ if prevPos >= 0 && nextPos >= 0 && lineOf(prevPos) != lineOf(nextPos) {
+ table.breaks[a.node] = true
+ }
+ }
+ return table
+}
+
+type anchor struct {
+ node Node
+ pos int
+ // marker anchors are emission points (beforeClause, list boundaries)
+ // rather than printed nodes; they carry no position of their own.
+ marker bool
+}
+
+// collectAnchors renders the statement once, flat, recording every
+// positioned node in the order the printer visits them. Print order is what
+// comment emission is defined against, so classifying against it keeps the
+// attach-time decision and the print-time emission point identical.
+func collectAnchors(n Node, d format.Dialect) (out []anchor) {
+ defer func() {
+ // A formatter panic here surfaces later, on the real print; anchors
+ // collected so far still place most comments.
+ recover()
+ }()
+ tb := NewTrackedBuffer()
+ tb.anchors = &out
+ if ft, ok := n.(nodeFormatter); ok {
+ ft.Format(tb, d)
+ }
+ return out
+}
diff --git a/internal/sql/ast/common_table_expr.go b/internal/sql/ast/common_table_expr.go
index aa334167c..a9cc9d502 100644
--- a/internal/sql/ast/common_table_expr.go
+++ b/internal/sql/ast/common_table_expr.go
@@ -32,6 +32,16 @@ func (n *CommonTableExpr) Format(buf *TrackedBuffer, d format.Dialect) {
buf.WriteString(")")
}
buf.WriteString(" AS (")
+ buf.Group()
+ buf.Indent()
+ // The body's boundary: a comment at the top of the CTE prints here, and
+ // an author who broke the line after the parenthesis keeps the CTE — and
+ // therefore the statement around it — broken open.
+ buf.boundary(n.Ctequery)
+ buf.Softline()
buf.astFormat(n.Ctequery, d)
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
diff --git a/internal/sql/ast/create_table_stmt.go b/internal/sql/ast/create_table_stmt.go
index f7ab2f9f6..cd11c61fa 100644
--- a/internal/sql/ast/create_table_stmt.go
+++ b/internal/sql/ast/create_table_stmt.go
@@ -9,6 +9,25 @@ type CreateTableStmt struct {
ReferTable *TableName
Comment string
Inherits []*TableName
+ // Using names the module of a virtual table (SQLite's CREATE VIRTUAL
+ // TABLE ... USING module(...)), and ModuleArgs carries the module's
+ // argument list as written — its grammar belongs to the module, so the
+ // arguments pass through verbatim; nil means the declaration had no
+ // argument list at all. Cols still holds the columns sqlc derives from
+ // the arguments for the catalog; the statement prints as its
+ // declaration, not as those columns.
+ Using string
+ ModuleArgs []string
+ // ModuleArgsMultiline records that the declaration was written across
+ // lines. The arguments carry no positions, so the printer cannot keep
+ // the author's exact breaks and prints the canonical broken form — one
+ // argument per line — instead.
+ ModuleArgsMultiline bool
+ // Incomplete marks a statement whose source carried syntax this node
+ // does not model — column or table constraints beyond plain NOT NULL
+ // and PRIMARY KEY, table options, TEMP, or an AS SELECT body. No
+ // faithful rendering exists for it.
+ Incomplete bool
}
func (n *CreateTableStmt) Pos() int {
@@ -19,15 +38,67 @@ func (n *CreateTableStmt) Format(buf *TrackedBuffer, d format.Dialect) {
if n == nil {
return
}
+ // A virtual table prints as its declaration: the module name and the
+ // argument list as written.
+ if n.Using != "" {
+ buf.WriteString("CREATE VIRTUAL TABLE ")
+ if n.IfNotExists {
+ buf.WriteString("IF NOT EXISTS ")
+ }
+ buf.astFormat(n.Name, d)
+ buf.WriteString(" USING ")
+ buf.WriteString(n.Using)
+ if n.ModuleArgs != nil {
+ buf.WriteString("(")
+ buf.Group()
+ buf.Indent()
+ if n.ModuleArgsMultiline {
+ buf.Breaker()
+ }
+ buf.Softline()
+ for i, arg := range n.ModuleArgs {
+ if i > 0 {
+ buf.WriteString(",")
+ buf.Line()
+ }
+ buf.WriteString(arg)
+ }
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
+ buf.WriteString(")")
+ }
+ return
+ }
+ // An incomplete statement cannot be printed back: part of its source
+ // was parsed away. Render nothing, which no verification accepts, so
+ // the formatter keeps the statement as written.
+ if n.Incomplete {
+ return
+ }
buf.WriteString("CREATE TABLE ")
+ if n.IfNotExists {
+ buf.WriteString("IF NOT EXISTS ")
+ }
buf.astFormat(n.Name, d)
- buf.WriteString("(")
+ buf.WriteString(" (")
+ buf.Group()
+ buf.Indent()
+ if len(n.Cols) > 0 {
+ buf.boundary(n.Cols[0])
+ }
+ buf.Softline()
for i, col := range n.Cols {
if i > 0 {
- buf.WriteString(", ")
+ buf.WriteString(",")
+ buf.boundary(col)
+ buf.Line()
}
buf.astFormat(col, d)
}
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
diff --git a/internal/sql/ast/delete_stmt.go b/internal/sql/ast/delete_stmt.go
index 74683f20b..318713ad6 100644
--- a/internal/sql/ast/delete_stmt.go
+++ b/internal/sql/ast/delete_stmt.go
@@ -26,9 +26,18 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) {
return
}
+ buf.Group()
+ defer buf.EndGroup()
+
if n.WithClause != nil {
buf.astFormat(n.WithClause, d)
- buf.WriteString(" ")
+ // The boundary between the WITH clause and the statement's own
+ // first keyword; the group keeps a break inside the WITH clause
+ // from forcing the statement body apart clause by clause.
+ buf.boundary(n.Relations)
+ buf.Line()
+ buf.Group()
+ defer buf.EndGroup()
}
buf.WriteString("DELETE ")
@@ -50,22 +59,30 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) {
}
if items(n.UsingClause) {
- buf.WriteString(" USING ")
+ buf.beforeClause(n.UsingClause, d)
+ buf.Line()
+ buf.WriteString("USING ")
buf.join(n.UsingClause, d, ", ")
}
if set(n.WhereClause) {
- buf.WriteString(" WHERE ")
- buf.astFormat(n.WhereClause, d)
+ buf.beforeClause(n.WhereClause, d)
+ buf.Line()
+ buf.WriteString("WHERE ")
+ buf.condition(n.WhereClause, d)
}
if set(n.LimitCount) {
- buf.WriteString(" LIMIT ")
+ buf.beforeClause(n.LimitCount, d)
+ buf.Line()
+ buf.WriteString("LIMIT ")
buf.astFormat(n.LimitCount, d)
}
if items(n.ReturningList) {
- buf.WriteString(" RETURNING ")
+ buf.beforeClause(n.ReturningList, d)
+ buf.Line()
+ buf.WriteString("RETURNING ")
formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
buf.astFormat(n.ReturningList, d)
}
diff --git a/internal/sql/ast/insert_stmt.go b/internal/sql/ast/insert_stmt.go
index 6568deb32..6ba998841 100644
--- a/internal/sql/ast/insert_stmt.go
+++ b/internal/sql/ast/insert_stmt.go
@@ -26,9 +26,18 @@ func (n *InsertStmt) Format(buf *TrackedBuffer, d format.Dialect) {
return
}
+ buf.Group()
+ defer buf.EndGroup()
+
if n.WithClause != nil {
buf.astFormat(n.WithClause, d)
- buf.WriteString(" ")
+ // The boundary between the WITH clause and the statement's own
+ // first keyword; the group keeps a break inside the WITH clause
+ // from forcing the statement body apart clause by clause.
+ buf.boundary(n.Relation)
+ buf.Line()
+ buf.Group()
+ defer buf.EndGroup()
}
buf.WriteString("INSERT INTO ")
@@ -37,29 +46,38 @@ func (n *InsertStmt) Format(buf *TrackedBuffer, d format.Dialect) {
}
if items(n.Cols) {
buf.WriteString(" (")
- buf.astFormat(n.Cols, d)
+ buf.Group()
+ buf.Indent()
+ buf.Softline()
+ buf.joinComma(n.Cols, d)
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
if n.DefaultValues {
buf.WriteString(" DEFAULT VALUES")
} else if set(n.SelectStmt) {
- buf.WriteString(" ")
+ buf.beforeClause(n.SelectStmt, d)
+ buf.Line()
buf.astFormat(n.SelectStmt, d)
}
if n.OnConflictClause != nil {
- buf.WriteString(" ")
+ buf.Line()
buf.astFormat(n.OnConflictClause, d)
}
if n.OnDuplicateKeyUpdate != nil {
- buf.WriteString(" ")
+ buf.Line()
buf.astFormat(n.OnDuplicateKeyUpdate, d)
}
if items(n.ReturningList) {
- buf.WriteString(" RETURNING ")
+ buf.beforeClause(n.ReturningList, d)
+ buf.Line()
+ buf.WriteString("RETURNING ")
formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
buf.astFormat(n.ReturningList, d)
}
diff --git a/internal/sql/ast/join_expr.go b/internal/sql/ast/join_expr.go
index 8ac059d00..c68235666 100644
--- a/internal/sql/ast/join_expr.go
+++ b/internal/sql/ast/join_expr.go
@@ -22,25 +22,27 @@ func (n *JoinExpr) Format(buf *TrackedBuffer, d format.Dialect) {
return
}
buf.astFormat(n.Larg, d)
+ buf.beforeClause(n.Rarg, d)
+ buf.Line()
if n.IsNatural {
- buf.WriteString(" NATURAL")
+ buf.WriteString("NATURAL ")
}
switch n.Jointype {
case JoinTypeLeft:
- buf.WriteString(" LEFT JOIN ")
+ buf.WriteString("LEFT JOIN ")
case JoinTypeRight:
- buf.WriteString(" RIGHT JOIN ")
+ buf.WriteString("RIGHT JOIN ")
case JoinTypeFull:
- buf.WriteString(" FULL JOIN ")
+ buf.WriteString("FULL JOIN ")
case JoinTypeInner:
// CROSS JOIN has no ON or USING clause
if !items(n.UsingClause) && !set(n.Quals) {
- buf.WriteString(" CROSS JOIN ")
+ buf.WriteString("CROSS JOIN ")
} else {
- buf.WriteString(" JOIN ")
+ buf.WriteString("JOIN ")
}
default:
- buf.WriteString(" JOIN ")
+ buf.WriteString("JOIN ")
}
buf.astFormat(n.Rarg, d)
if items(n.UsingClause) {
@@ -49,6 +51,6 @@ func (n *JoinExpr) Format(buf *TrackedBuffer, d format.Dialect) {
buf.WriteString(")")
} else if set(n.Quals) {
buf.WriteString(" ON ")
- buf.astFormat(n.Quals, d)
+ buf.condition(n.Quals, d)
}
}
diff --git a/internal/sql/ast/print.go b/internal/sql/ast/print.go
index 87f610762..1ec48a087 100644
--- a/internal/sql/ast/print.go
+++ b/internal/sql/ast/print.go
@@ -1,9 +1,8 @@
package ast
import (
- "strings"
-
"github.com/sqlc-dev/sqlc/internal/debug"
+ "github.com/sqlc-dev/sqlc/internal/sql/ast/printer"
"github.com/sqlc-dev/sqlc/internal/sql/format"
)
@@ -11,18 +10,37 @@ type nodeFormatter interface {
Format(*TrackedBuffer, format.Dialect)
}
+// TrackedBuffer layers AST formatting over the document renderer in
+// ast/printer: node dispatch, list joins, and comment emission. The
+// renderer itself — tokens, groups, width fitting — lives in the printer
+// package; TrackedBuffer stays here because every node's Format method
+// names it, which an ast → printer → ast import cycle would forbid.
type TrackedBuffer struct {
- *strings.Builder
+ *printer.Buffer
+ // ct, when set, carries the statement's interior comments attached to
+ // their anchor nodes; the buffer emits each comment when it reaches the
+ // comment's anchor. Positions were consulted once, in AttachComments —
+ // never here — so edited and synthetic trees print comments correctly.
+ ct *CommentTable
+ // anchors, when set, records every positioned node and emission point
+ // in print order instead of producing output; AttachComments uses this
+ // dry run to classify comments against the same order printing will
+ // use.
+ anchors *[]anchor
}
// NewTrackedBuffer creates a new TrackedBuffer.
func NewTrackedBuffer() *TrackedBuffer {
- return &TrackedBuffer{
- Builder: new(strings.Builder),
- }
+ return &TrackedBuffer{Buffer: &printer.Buffer{}}
}
func (t *TrackedBuffer) astFormat(n Node, d format.Dialect) {
+ if t.anchors != nil && n != nil && n.Pos() > 0 {
+ *t.anchors = append(*t.anchors, anchor{node: n, pos: n.Pos()})
+ }
+ if t.ct != nil && n != nil {
+ t.emitComments(t.ct.take(n))
+ }
if ft, ok := n.(nodeFormatter); ok {
ft.Format(t, d)
} else {
@@ -30,27 +48,200 @@ func (t *TrackedBuffer) astFormat(n Node, d format.Dialect) {
}
}
+// emitComments prints attached comments at the boundary before their anchor
+// node. A trailing comment continues the line before it (a line comment
+// then forces the enclosing groups to break); an own-line or line comment
+// goes on its own line; an inline block comment stays in the flow.
+func (t *TrackedBuffer) emitComments(recs []commentRec) {
+ for _, rec := range recs {
+ switch {
+ case rec.trailing:
+ t.WriteString(" ")
+ t.WriteString(rec.c.Text)
+ if rec.c.Line() {
+ t.Breaker()
+ }
+ case rec.c.OwnLine || rec.c.Line():
+ t.Hardline()
+ t.WriteString(rec.c.Text)
+ t.Hardline()
+ default:
+ t.WriteString(rec.c.Text)
+ t.WriteString(" ")
+ }
+ }
+}
+
+// beforeClause is the emission point for comments that sit between the
+// previous clause and the one about to be printed, so they land before the
+// clause keyword. Call it before the clause's line break. During the
+// AttachComments dry run it records itself as a boundary marker, which is
+// how classification and emission are guaranteed to pick the same spot —
+// and how the author's own line break before the clause is observed and
+// kept.
+func (t *TrackedBuffer) beforeClause(n Node, d format.Dialect) {
+ t.boundary(n)
+}
+
+// boundary is a separator-adjacent emission point (before a clause, after a
+// comma, before an AND/OR): comments classified to the upcoming node print
+// here, before the separator's line break, and a line break the author
+// wrote at this boundary forces the break to stay. On the dry run it
+// records a marker instead, so classification and emission agree by
+// construction.
+func (t *TrackedBuffer) boundary(next Node) {
+ if next == nil {
+ return
+ }
+ if t.anchors != nil {
+ *t.anchors = append(*t.anchors, anchor{node: next, marker: true})
+ return
+ }
+ if t.ct != nil {
+ t.emitComments(t.ct.take(next))
+ if t.ct.breakAt(next) {
+ t.Breaker()
+ }
+ }
+}
+
+// flushRemaining prints every comment not yet printed; the statement is
+// over, so everything left trails it.
+func (t *TrackedBuffer) flushRemaining() {
+ if t.ct == nil {
+ return
+ }
+ for _, rec := range t.ct.takeRemaining() {
+ if rec.trailing {
+ t.WriteString(" ")
+ t.WriteString(rec.c.Text)
+ if rec.c.Line() {
+ t.Breaker()
+ }
+ } else {
+ t.Hardline()
+ t.WriteString(rec.c.Text)
+ }
+ }
+}
+
func (t *TrackedBuffer) join(n *List, d format.Dialect, sep string) {
if n == nil {
return
}
- for i, item := range n.Items {
+ first := true
+ for _, item := range n.Items {
if _, ok := item.(*TODO); ok {
continue
}
- if i > 0 {
+ if !first {
t.WriteString(sep)
}
+ first = false
+ t.astFormat(item, d)
+ }
+}
+
+// joinComma writes the list items separated by a comma and a break
+// opportunity, so a list that fits stays on one line and a list that does
+// not puts every item on its own line. An item's trailing comment prints
+// after the comma, gofmt-style: `total, -- computed`.
+func (t *TrackedBuffer) joinComma(n *List, d format.Dialect) {
+ if n == nil {
+ return
+ }
+ items := make([]Node, 0, len(n.Items))
+ for _, item := range n.Items {
+ if _, ok := item.(*TODO); ok {
+ continue
+ }
+ items = append(items, item)
+ }
+ for i, item := range items {
+ if i > 0 {
+ t.WriteString(",")
+ t.boundary(item)
+ t.Line()
+ }
+ t.astFormat(item, d)
+ }
+}
+
+// condition formats a clause-level boolean condition (WHERE, HAVING, ON).
+// A top-level AND/OR chain is printed without the enclosing parentheses a
+// nested BoolExpr gets — the clause keyword already delimits it — and each
+// branch goes on its own line when the chain does not fit:
+//
+// WHERE name LIKE $1
+// AND id > $2
+func (t *TrackedBuffer) condition(n Node, d format.Dialect) {
+ be, ok := n.(*BoolExpr)
+ if !ok || (be.Boolop != BoolExprTypeAnd && be.Boolop != BoolExprTypeOr) {
+ t.astFormat(n, d)
+ return
+ }
+ op := "AND "
+ if be.Boolop == BoolExprTypeOr {
+ op = "OR "
+ }
+ t.Group()
+ t.Indent()
+ first := true
+ t.conditionArgs(be, d, op, &first)
+ t.EndIndent()
+ t.EndGroup()
+}
+
+// conditionArgs writes the branches of an AND/OR chain, flattening nested
+// chains of the same operator (some parsers produce `a AND b AND c` as a
+// left-nested tree) so no redundant parentheses appear.
+func (t *TrackedBuffer) conditionArgs(be *BoolExpr, d format.Dialect, op string, first *bool) {
+ if be.Args == nil {
+ return
+ }
+ for _, item := range be.Args.Items {
+ if _, ok := item.(*TODO); ok {
+ continue
+ }
+ if nested, ok := item.(*BoolExpr); ok && nested.Boolop == be.Boolop {
+ t.conditionArgs(nested, d, op, first)
+ continue
+ }
+ if !*first {
+ t.boundary(item)
+ t.Line()
+ t.WriteString(op)
+ }
+ *first = false
t.astFormat(item, d)
}
}
+// Format renders the node as SQL on a single line.
func Format(n Node, d format.Dialect) string {
+ return Pretty(n, d, -1)
+}
+
+// Pretty renders the node as SQL, breaking lines so the output fits within
+// width columns where the statement's structure allows it. A negative width
+// renders everything on a single line.
+func Pretty(n Node, d format.Dialect, width int) string {
+ return PrettyWithComments(n, d, width, nil)
+}
+
+// PrettyWithComments renders the node as SQL like Pretty, emitting the
+// comments a prior AttachComments call anchored to its nodes and keeping
+// the line breaks the author wrote at the boundaries the printer models.
+// Each comment prints at the boundary before its anchor, a trailing comment
+// continues the line of the code it followed, and every comment in the
+// table is printed — anything left when the statement ends trails it.
+func PrettyWithComments(n Node, d format.Dialect, width int, ct *CommentTable) string {
tb := NewTrackedBuffer()
+ tb.ct = ct
if ft, ok := n.(nodeFormatter); ok {
ft.Format(tb, d)
}
- return tb.String()
+ return tb.Print(width)
}
func set(n Node) bool {
@@ -58,10 +249,7 @@ func set(n Node) bool {
return false
}
_, ok := n.(*TODO)
- if ok {
- return false
- }
- return true
+ return !ok
}
func items(n *List) bool {
diff --git a/internal/sql/ast/printer/printer.go b/internal/sql/ast/printer/printer.go
new file mode 100644
index 000000000..69c8bbacb
--- /dev/null
+++ b/internal/sql/ast/printer/printer.go
@@ -0,0 +1,250 @@
+// Package printer implements the document renderer the SQL formatter
+// prints through: a small Wadler-style engine, the model behind Prettier
+// and ruff (via Biome's printer). Callers emit a stream of tokens — literal
+// text, break opportunities, and markers that open and close groups and
+// indented regions — and Print lays each group out on a single line when
+// its flat width fits, breaking it otherwise. The package knows nothing
+// about SQL or the AST; the ast package's TrackedBuffer embeds a Buffer and
+// layers node formatting and comment emission on top.
+package printer
+
+import (
+ "strings"
+ "unicode/utf8"
+)
+
+type tokenKind uint8
+
+const (
+ tokenText tokenKind = iota
+ // tokenLine renders as a single space when its group fits on one line
+ // and as a line break when the group is broken.
+ tokenLine
+ // tokenSoftline renders as nothing when its group fits on one line and
+ // as a line break when the group is broken.
+ tokenSoftline
+ // tokenHardline always renders a line break and forces every group
+ // containing it to break (it measures as infinitely wide). Emitted
+ // around comments, which pin the author's layout open.
+ tokenHardline
+ // tokenBreaker renders nothing but forces every group containing it to
+ // break. Emitted after a trailing line comment, whose text swallows the
+ // rest of the line, and at boundaries where the author broke the line.
+ tokenBreaker
+ tokenOpenGroup
+ tokenCloseGroup
+ tokenOpenIndent
+ tokenCloseIndent
+)
+
+// breakWidth is the measured width of tokens that force a break: wider than
+// any real line, so no group containing one ever fits.
+const breakWidth = 1 << 24
+
+// indentWidth is the number of spaces per indentation level in broken
+// (multi-line) output.
+const indentWidth = 2
+
+type token struct {
+ kind tokenKind
+ text string
+}
+
+// Buffer accumulates the document token stream.
+type Buffer struct {
+ tokens []token
+}
+
+func (t *Buffer) WriteString(s string) (int, error) {
+ if s == "" {
+ return 0, nil
+ }
+ t.tokens = append(t.tokens, token{kind: tokenText, text: s})
+ return len(s), nil
+}
+
+// Write implements io.Writer so callers can use fmt.Fprintf.
+func (t *Buffer) Write(p []byte) (int, error) {
+ return t.WriteString(string(p))
+}
+
+func (t *Buffer) WriteRune(r rune) (int, error) {
+ return t.WriteString(string(r))
+}
+
+// String renders the buffer on a single line.
+func (t *Buffer) String() string {
+ return t.Print(-1)
+}
+
+// Line marks a break opportunity between two tokens: a space when the
+// surrounding group fits on one line, a line break when it does not.
+func (t *Buffer) Line() {
+ t.tokens = append(t.tokens, token{kind: tokenLine})
+}
+
+// Softline marks a break opportunity that disappears entirely when the
+// surrounding group fits on one line.
+func (t *Buffer) Softline() {
+ t.tokens = append(t.tokens, token{kind: tokenSoftline})
+}
+
+// Hardline always renders a line break and forces every enclosing group to
+// break.
+func (t *Buffer) Hardline() {
+ t.tokens = append(t.tokens, token{kind: tokenHardline})
+}
+
+// Breaker renders nothing but forces every enclosing group to break, so the
+// next break opportunity becomes a real line break.
+func (t *Buffer) Breaker() {
+ t.tokens = append(t.tokens, token{kind: tokenBreaker})
+}
+
+// Group opens a region the renderer tries to lay out on a single line,
+// breaking it only when its flat form does not fit. Must be paired with
+// EndGroup.
+func (t *Buffer) Group() {
+ t.tokens = append(t.tokens, token{kind: tokenOpenGroup})
+}
+
+func (t *Buffer) EndGroup() {
+ t.tokens = append(t.tokens, token{kind: tokenCloseGroup})
+}
+
+// Indent opens a region printed one indentation level deeper when line
+// breaks occur inside it. Must be paired with EndIndent.
+func (t *Buffer) Indent() {
+ t.tokens = append(t.tokens, token{kind: tokenOpenIndent})
+}
+
+func (t *Buffer) EndIndent() {
+ t.tokens = append(t.tokens, token{kind: tokenCloseIndent})
+}
+
+// docNode is the tree form of the token stream: text and break tokens are
+// leaves, groups and indented regions are interior nodes.
+type docNode struct {
+ kind tokenKind
+ text string
+ kids []*docNode
+ width int // flat width in runes, filled in by measure
+}
+
+// tree assembles the flat token stream into a document tree. Stray close
+// markers are ignored and unclosed regions end at the end of the stream.
+func (t *Buffer) tree() *docNode {
+ root := &docNode{kind: tokenOpenGroup}
+ stack := []*docNode{root}
+ for _, tok := range t.tokens {
+ top := stack[len(stack)-1]
+ switch tok.kind {
+ case tokenText, tokenLine, tokenSoftline, tokenHardline, tokenBreaker:
+ top.kids = append(top.kids, &docNode{kind: tok.kind, text: tok.text})
+ case tokenOpenGroup, tokenOpenIndent:
+ n := &docNode{kind: tok.kind}
+ top.kids = append(top.kids, n)
+ stack = append(stack, n)
+ case tokenCloseGroup, tokenCloseIndent:
+ if len(stack) > 1 {
+ stack = stack[:len(stack)-1]
+ }
+ }
+ }
+ return root
+}
+
+// measure computes the width of every node when rendered flat. Hardlines
+// and breakers measure wider than any real line, so no group containing one
+// ever fits — Prettier's breakParent, by arithmetic.
+func measure(d *docNode) int {
+ switch d.kind {
+ case tokenText:
+ d.width = utf8.RuneCountInString(d.text)
+ case tokenLine:
+ d.width = 1
+ case tokenSoftline:
+ d.width = 0
+ case tokenHardline, tokenBreaker:
+ d.width = breakWidth
+ default:
+ for _, kid := range d.kids {
+ d.width += measure(kid)
+ if d.width > breakWidth {
+ d.width = breakWidth
+ }
+ }
+ }
+ return d.width
+}
+
+// Print renders the token stream. A negative width renders everything on
+// one line; otherwise each group is rendered flat only when it fits in the
+// space remaining on its line — and a group holding a hardline or breaker
+// never fits, whatever the width, so forced breaks survive even an
+// unlimited line length.
+func (t *Buffer) Print(width int) string {
+ root := t.tree()
+ measure(root)
+
+ type frame struct {
+ d *docNode
+ indent int
+ flat bool
+ }
+ var sb strings.Builder
+ col := 0
+ // atLineStart dedupes consecutive breaks: a break that fires when the
+ // output is already at the start of a fresh line writes nothing, so a
+ // comment's surrounding hardlines collapse against clause breaks
+ // instead of leaving blank lines.
+ atLineStart := true
+ newline := func(indent int) {
+ if atLineStart {
+ return
+ }
+ sb.WriteByte('\n')
+ for i := 0; i < indent; i++ {
+ sb.WriteByte(' ')
+ }
+ col = indent
+ atLineStart = true
+ }
+ stack := []frame{{d: root, flat: width < 0}}
+ for len(stack) > 0 {
+ f := stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ switch f.d.kind {
+ case tokenText:
+ sb.WriteString(f.d.text)
+ col += f.d.width
+ atLineStart = false
+ case tokenLine:
+ if f.flat {
+ sb.WriteByte(' ')
+ col++
+ atLineStart = false
+ } else {
+ newline(f.indent)
+ }
+ case tokenSoftline:
+ if !f.flat {
+ newline(f.indent)
+ }
+ case tokenHardline:
+ newline(f.indent)
+ case tokenBreaker:
+ // forces enclosing groups broken; renders nothing
+ case tokenOpenGroup:
+ flat := f.flat || (f.d.width < breakWidth && f.d.width <= width-col)
+ for i := len(f.d.kids) - 1; i >= 0; i-- {
+ stack = append(stack, frame{d: f.d.kids[i], indent: f.indent, flat: flat})
+ }
+ case tokenOpenIndent:
+ for i := len(f.d.kids) - 1; i >= 0; i-- {
+ stack = append(stack, frame{d: f.d.kids[i], indent: f.indent + indentWidth, flat: f.flat})
+ }
+ }
+ }
+ return sb.String()
+}
diff --git a/internal/sql/ast/raw_stmt.go b/internal/sql/ast/raw_stmt.go
index fe02bed80..619b84424 100644
--- a/internal/sql/ast/raw_stmt.go
+++ b/internal/sql/ast/raw_stmt.go
@@ -16,5 +16,7 @@ func (n *RawStmt) Format(buf *TrackedBuffer, d format.Dialect) {
if n.Stmt != nil {
buf.astFormat(n.Stmt, d)
}
+ // The terminator goes first: a trailing line comment would swallow it.
buf.WriteString(";")
+ buf.flushRemaining()
}
diff --git a/internal/sql/ast/select_stmt.go b/internal/sql/ast/select_stmt.go
index 62e6f1c9c..2b41692bf 100644
--- a/internal/sql/ast/select_stmt.go
+++ b/internal/sql/ast/select_stmt.go
@@ -1,8 +1,6 @@
package ast
import (
- "fmt"
-
"github.com/sqlc-dev/sqlc/internal/sql/format"
)
@@ -44,82 +42,125 @@ func (n *SelectStmt) Format(buf *TrackedBuffer, d format.Dialect) {
buf.WriteString(", ")
}
buf.WriteString("(")
- buf.astFormat(row, d)
+ buf.Group()
+ buf.Indent()
+ buf.Softline()
+ if r, ok := row.(*List); ok {
+ buf.joinComma(r, d)
+ } else {
+ buf.astFormat(row, d)
+ }
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
return
}
+ buf.Group()
+ defer buf.EndGroup()
+
if n.WithClause != nil {
buf.astFormat(n.WithClause, d)
- buf.WriteString(" ")
+ // The boundary between the WITH clause and the statement's own
+ // first keyword; the group keeps a break inside the WITH clause
+ // from forcing the statement body apart clause by clause.
+ if n.Larg != nil {
+ buf.boundary(n.Larg)
+ } else {
+ buf.boundary(n.TargetList)
+ }
+ buf.Line()
+ buf.Group()
+ defer buf.EndGroup()
}
if n.Larg != nil && n.Rarg != nil {
buf.astFormat(n.Larg, d)
+ buf.Line()
switch n.Op {
case Union:
- buf.WriteString(" UNION ")
+ buf.WriteString("UNION")
case Except:
- buf.WriteString(" EXCEPT ")
+ buf.WriteString("EXCEPT")
case Intersect:
- buf.WriteString(" INTERSECT ")
+ buf.WriteString("INTERSECT")
}
if n.All {
- buf.WriteString("ALL ")
+ buf.WriteString(" ALL")
}
+ buf.Line()
buf.astFormat(n.Rarg, d)
} else {
- buf.WriteString("SELECT ")
- }
-
- if items(n.DistinctClause) {
- buf.WriteString("DISTINCT ")
- if !todo(n.DistinctClause) {
- fmt.Fprintf(buf, "ON (")
- buf.astFormat(n.DistinctClause, d)
- fmt.Fprintf(buf, ")")
+ buf.WriteString("SELECT")
+ if items(n.DistinctClause) {
+ buf.WriteString(" DISTINCT")
+ if !todo(n.DistinctClause) {
+ buf.WriteString(" ON (")
+ buf.astFormat(n.DistinctClause, d)
+ buf.WriteString(")")
+ }
}
+ buf.Group()
+ buf.Indent()
+ buf.Line()
+ buf.joinComma(n.TargetList, d)
+ buf.EndIndent()
+ buf.EndGroup()
}
- buf.astFormat(n.TargetList, d)
if items(n.FromClause) {
- buf.WriteString(" FROM ")
+ buf.beforeClause(n.FromClause, d)
+ buf.Line()
+ buf.WriteString("FROM ")
buf.astFormat(n.FromClause, d)
}
if set(n.WhereClause) {
- buf.WriteString(" WHERE ")
- buf.astFormat(n.WhereClause, d)
+ buf.beforeClause(n.WhereClause, d)
+ buf.Line()
+ buf.WriteString("WHERE ")
+ buf.condition(n.WhereClause, d)
}
if items(n.GroupClause) {
- buf.WriteString(" GROUP BY ")
+ buf.beforeClause(n.GroupClause, d)
+ buf.Line()
+ buf.WriteString("GROUP BY ")
buf.astFormat(n.GroupClause, d)
}
if set(n.HavingClause) {
- buf.WriteString(" HAVING ")
- buf.astFormat(n.HavingClause, d)
+ buf.beforeClause(n.HavingClause, d)
+ buf.Line()
+ buf.WriteString("HAVING ")
+ buf.condition(n.HavingClause, d)
}
if items(n.SortClause) {
- buf.WriteString(" ORDER BY ")
+ buf.beforeClause(n.SortClause, d)
+ buf.Line()
+ buf.WriteString("ORDER BY ")
buf.astFormat(n.SortClause, d)
}
if set(n.LimitCount) {
- buf.WriteString(" LIMIT ")
+ buf.beforeClause(n.LimitCount, d)
+ buf.Line()
+ buf.WriteString("LIMIT ")
buf.astFormat(n.LimitCount, d)
}
if set(n.LimitOffset) {
- buf.WriteString(" OFFSET ")
+ buf.beforeClause(n.LimitOffset, d)
+ buf.Line()
+ buf.WriteString("OFFSET ")
buf.astFormat(n.LimitOffset, d)
}
if items(n.LockingClause) {
- buf.WriteString(" ")
+ buf.Line()
buf.astFormat(n.LockingClause, d)
}
diff --git a/internal/sql/ast/sub_link.go b/internal/sql/ast/sub_link.go
index 99b8458af..bfd3ded20 100644
--- a/internal/sql/ast/sub_link.go
+++ b/internal/sql/ast/sub_link.go
@@ -54,6 +54,12 @@ func (n *SubLink) Format(buf *TrackedBuffer, d format.Dialect) {
buf.WriteString("(")
}
}
+ buf.Group()
+ buf.Indent()
+ buf.Softline()
buf.astFormat(n.Subselect, d)
+ buf.EndIndent()
+ buf.Softline()
+ buf.EndGroup()
buf.WriteString(")")
}
diff --git a/internal/sql/ast/type_name.go b/internal/sql/ast/type_name.go
index d8d91f4f8..26ef4d6d2 100644
--- a/internal/sql/ast/type_name.go
+++ b/internal/sql/ast/type_name.go
@@ -6,6 +6,11 @@ type TypeName struct {
Catalog string
Schema string
Name string
+ // Spelling is the type as the author wrote it, when that differs from
+ // Name: SQLite folds the spaces out of multi-word type names ("VARYING
+ // CHARACTER" resolves as "VARYINGCHARACTER" in the catalog), so the
+ // formatter prints this back instead of the folded form.
+ Spelling string
// From pg.TypeName
Names *List
@@ -26,6 +31,10 @@ func (n *TypeName) Format(buf *TrackedBuffer, d format.Dialect) {
if n == nil {
return
}
+ if n.Spelling != "" {
+ buf.WriteString(n.Spelling)
+ goto addMods
+ }
if items(n.Names) {
// Check if this is a qualified type (e.g., pg_catalog.int4)
if len(n.Names.Items) == 2 {
diff --git a/internal/sql/ast/update_stmt.go b/internal/sql/ast/update_stmt.go
index 54382b3f4..55775a662 100644
--- a/internal/sql/ast/update_stmt.go
+++ b/internal/sql/ast/update_stmt.go
@@ -27,9 +27,18 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
if n == nil {
return
}
+ buf.Group()
+ defer buf.EndGroup()
+
if n.WithClause != nil {
buf.astFormat(n.WithClause, d)
- buf.WriteString(" ")
+ // The boundary between the WITH clause and the statement's own
+ // first keyword; the group keeps a break inside the WITH clause
+ // from forcing the statement body apart clause by clause.
+ buf.boundary(n.Relations)
+ buf.Line()
+ buf.Group()
+ defer buf.EndGroup()
}
buf.WriteString("UPDATE ")
@@ -38,7 +47,9 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
}
if items(n.TargetList) {
- buf.WriteString(" SET ")
+ buf.beforeClause(n.TargetList, d)
+ buf.Line()
+ buf.WriteString("SET ")
multi := false
for _, item := range n.TargetList.Items {
@@ -79,9 +90,13 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
buf.join(vals, d, ",")
buf.WriteString(")")
} else {
+ buf.Group()
+ buf.Indent()
for i, item := range n.TargetList.Items {
if i > 0 {
- buf.WriteString(", ")
+ buf.WriteString(",")
+ buf.boundary(item)
+ buf.Line()
}
switch nn := item.(type) {
case *ResTarget:
@@ -100,26 +115,36 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
buf.astFormat(item, d)
}
}
+ buf.EndIndent()
+ buf.EndGroup()
}
}
if items(n.FromClause) {
- buf.WriteString(" FROM ")
+ buf.beforeClause(n.FromClause, d)
+ buf.Line()
+ buf.WriteString("FROM ")
buf.astFormat(n.FromClause, d)
}
if set(n.WhereClause) {
- buf.WriteString(" WHERE ")
- buf.astFormat(n.WhereClause, d)
+ buf.beforeClause(n.WhereClause, d)
+ buf.Line()
+ buf.WriteString("WHERE ")
+ buf.condition(n.WhereClause, d)
}
if set(n.LimitCount) {
- buf.WriteString(" LIMIT ")
+ buf.beforeClause(n.LimitCount, d)
+ buf.Line()
+ buf.WriteString("LIMIT ")
buf.astFormat(n.LimitCount, d)
}
if items(n.ReturningList) {
- buf.WriteString(" RETURNING ")
+ buf.beforeClause(n.ReturningList, d)
+ buf.Line()
+ buf.WriteString("RETURNING ")
formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
buf.astFormat(n.ReturningList, d)
}
diff --git a/internal/sql/ast/with_clause.go b/internal/sql/ast/with_clause.go
index 0def53d38..a7d4b2490 100644
--- a/internal/sql/ast/with_clause.go
+++ b/internal/sql/ast/with_clause.go
@@ -20,5 +20,5 @@ func (n *WithClause) Format(buf *TrackedBuffer, d format.Dialect) {
if n.Recursive {
buf.WriteString("RECURSIVE ")
}
- buf.join(n.Ctes, d, ", ")
+ buf.joinComma(n.Ctes, d)
}
diff --git a/internal/sql/format/format.go b/internal/sql/format/format.go
index b900c227e..1520cb235 100644
--- a/internal/sql/format/format.go
+++ b/internal/sql/format/format.go
@@ -14,10 +14,6 @@ type Dialect interface {
// PostgreSQL uses $1, $2, etc. MySQL uses ?
Param(n int) string
- // NamedParam returns the named parameter placeholder for the given name.
- // PostgreSQL uses @name, SQLite uses :name
- NamedParam(name string) string
-
// Cast formats a type cast expression.
// PostgreSQL uses expr::type, MySQL uses CAST(expr AS type)
Cast(arg, typeName string) string