|
| 1 | +# `fmt` - Formatting queries |
| 2 | + |
| 3 | +`sqlc fmt` rewrites the query files referenced by your configuration file in a |
| 4 | +canonical format. Each query is parsed with the engine's parser and printed |
| 5 | +back from the syntax tree, so formatting never depends on how the query was |
| 6 | +written — only on what it means. |
| 7 | + |
| 8 | +Like `gofmt`, the formatter does not impose a maximum line width. A statement |
| 9 | +written on a single line stays on a single line, and a statement the author |
| 10 | +broke across lines keeps its breaks: the printer notices which clause |
| 11 | +boundaries (`FROM`, `WHERE`, `ORDER BY`, ...) and list boundaries the author |
| 12 | +broke at and preserves them, normalizing indentation and spacing around them. |
| 13 | + |
| 14 | +Comments inside a statement are formatted along with it: each comment is |
| 15 | +anchored to the code around it by source position and printed back there — |
| 16 | +a comment trailing a select-list item stays with that item, a comment above |
| 17 | +a clause stays above its keyword — and a comment that runs to the end of its |
| 18 | +line breaks the statement open around it. Any statement that cannot be |
| 19 | +proven to survive formatting unchanged is left exactly as written. |
| 20 | + |
| 21 | +## Usage |
| 22 | + |
| 23 | +```sh |
| 24 | +sqlc fmt [--diff] |
| 25 | +``` |
| 26 | + |
| 27 | +Without flags, the query files are rewritten in place. With `--diff`, the |
| 28 | +changes are printed to standard output instead and no files are modified. |
| 29 | + |
| 30 | +## Examples |
| 31 | + |
| 32 | +Given this query file: |
| 33 | + |
| 34 | +```sql |
| 35 | +-- name: GetAuthor :one |
| 36 | +select id,name , bio |
| 37 | +from authors |
| 38 | +where id = ? limit 1; |
| 39 | + |
| 40 | +-- name: SearchAuthors :many |
| 41 | +SELECT id, -- the primary key |
| 42 | + name, bio, created_at FROM authors WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? ORDER BY name; |
| 43 | +``` |
| 44 | + |
| 45 | +running `sqlc fmt` rewrites it to: |
| 46 | + |
| 47 | +```sql |
| 48 | +-- name: GetAuthor :one |
| 49 | +SELECT id, name, bio |
| 50 | +FROM authors |
| 51 | +WHERE id = ? |
| 52 | +LIMIT 1; |
| 53 | + |
| 54 | +-- name: SearchAuthors :many |
| 55 | +SELECT |
| 56 | + id, -- the primary key |
| 57 | + name, |
| 58 | + bio, |
| 59 | + created_at |
| 60 | +FROM authors |
| 61 | +WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? |
| 62 | +ORDER BY name; |
| 63 | +``` |
| 64 | + |
| 65 | +`GetAuthor` keeps the line breaks its author wrote; had it been written on |
| 66 | +one line, it would stay on one line. In `SearchAuthors`, the line comment |
| 67 | +cannot share a line with the code after it, so the statement breaks open |
| 68 | +around it, while the `WHERE` chain — written on one line — stays on one. |
0 commit comments