Something went wrong. Try again.
A mapping language to compose SQL for Go.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328package compiler
import ( "cmp" "go/token" "slices" "strings"
pgast "github.com/pganalyze/pg_query_go/v6" pgquery "github.com/wasilibs/go-pgquery")
// Compare lexer tokens after binding holes, allowing only keyword casing to// differ. This also guards against accidental operator/number token merging.func sqlFormatSignature(sql string) ([]string, error) { scan, err := pgquery.Scan(sql) if err != nil { return nil, err } var signature []string for _, item := range scan.Tokens { text := sql[item.Start:item.End] if item.KeywordKind != pgast.KeywordKind_NO_KEYWORD { text = strings.ToUpper(text) } signature = append(signature, item.Token.String(), text) } return signature, nil}
type sqlLayoutToken struct { text, word string start, end int goValue bool comment bool lineBefore bool stringLiteral bool}
// Layout uses PostgreSQL's lexer, retaining authored token text rather than// deparsing an AST, which would discard comments and StitchQL annotations.func layoutSQL(source string, scanned []*pgast.ScanToken, groups []formatToken, kind string) (string, []formatToken, []formatToken) { const syntax = ` ADD ALTER ALWAYS ASC BY CASCADE CONFLICT CONSTRAINT CREATE CROSS CYCLE DEFAULT DEFERRABLE DELETE DESC DO DROP ENUM EXCLUDE EXISTS EXPLAIN FILTER FIRST FOLLOWING FULL GENERATED GROUPS IDENTITY INCREMENT INDEX INNER INSERT INTO JOIN KEY LAST LEFT MATERIALIZED MAXVALUE MINVALUE NATURAL NO NULLS OFFSET OTHERS OUTER OVER PARTITION PRECEDING RANGE RECURSIVE REFERENCES RETURNING RIGHT ROLLUP ROWS SCHEMA SEARCH SEQUENCE SET STORED TABLE TEMP TEMPORARY TIES TYPE UNBOUNDED UNIQUE UPDATE USING VALID VALUES VIEW WINDOW WITHIN WITHOUT BIGINT BIGSERIAL BIT BOOLEAN BOOL BYTEA CHAR CHARACTER DATE DEC DECIMAL DOUBLE FLOAT INT INTEGER INTERVAL JSON JSONB NUMERIC PRECISION REAL SERIAL SMALLINT TEXT TIME TIMESTAMP TIMESTAMPTZ UUID VARCHAR VARYING ZONE` uppercase := strings.Fields(syntax)
var items []sqlLayoutToken for _, item := range scanned { if slices.ContainsFunc(groups, func(group formatToken) bool { return int(item.Start) >= group.start && int(item.End) <= group.end }) { continue } text := source[item.Start:item.End] word := "" if item.KeywordKind != pgast.KeywordKind_NO_KEYWORD { word = strings.ToUpper(text) // Unreserved words such as "name" commonly denote identifiers. // Reserve casing changes for SQL syntax and built-in type keywords.
if item.KeywordKind == pgast.KeywordKind_RESERVED_KEYWORD || slices.Contains(uppercase, word) { text = word } } items = append(items, sqlLayoutToken{ text: text, word: word, start: int(item.Start), end: int(item.End), comment: strings.HasPrefix(text, "--") || strings.HasPrefix(text, "/*"), stringLiteral: item.Token == pgast.Token_SCONST, }) } for _, group := range groups { items = append(items, sqlLayoutToken{ text: source[group.start:group.end], start: group.start, end: group.end, goValue: true, }) } slices.SortFunc(items, func(a, b sqlLayoutToken) int { return cmp.Compare(a.start, b.start) }) end := 0 for i := range items { items[i].lineBefore = strings.ContainsAny(source[end:items[i].start], "\r\n") end = items[i].end if i > 0 && items[i-1].text == "." && !items[i].goValue { items[i].text = source[items[i].start:items[i].end] } } var layout sqlLayout layout.out.WriteByte('\n') // Include the first SQL line in the indentation margin. layout.write(items, 0, kind) return layout.out.String(), layout.protected, layout.groups}
type sqlLayout struct { out strings.Builder protected, groups []formatToken previous sqlLayoutToken breaks int unary bool lastString bool}
func (w *sqlLayout) emit(item sqlLayoutToken, indent int, spaceBeforeOpen bool) { if w.breaks != 0 { w.out.WriteString(strings.Repeat("\n", w.breaks)) w.out.WriteString(strings.Repeat(" ", indent*4)) } else if w.previous.text != "" && sqlTokenSpace(w.previous.text, item.text, w.unary, spaceBeforeOpen) { w.out.WriteByte(' ') } start := w.out.Len() w.out.WriteString(item.text) if item.goValue { w.groups = append(w.groups, formatToken{start: start, end: w.out.Len()}) for _, t := range formatTokens(item.text) { if t.kind == token.STRING || t.kind == token.CHAR || t.kind == token.COMMENT { w.protected = append(w.protected, formatToken{start: start + t.start, end: start + t.end}) } } } else { w.protected = append(w.protected, formatToken{start: start, end: w.out.Len()}) } w.unary = (item.text == "+" || item.text == "-") && (w.previous.text == "" || strings.Contains("(,[=<>+-*/", w.previous.text) || w.previous.word != "") w.previous = item if !item.comment { w.lastString = item.stringLiteral } w.breaks = 0}
func sqlTokenSpace(previous, next string, unary, spaceBeforeOpen bool) bool { if next == "." && previous[0] >= '0' && previous[0] <= '9' { return true } if next == "(" { return spaceBeforeOpen } if next == "," || next == ";" || next == ")" || next == "]" || next == "." || next == "[" || next == "::" || next == ":" { return false } if previous == "(" || previous == "[" || previous == "." || previous == "::" || previous == ":" { return false } // Separate operator tokens must not merge into a different operator or --. if unary && next != "+" && next != "-" { return false } return true}
func sqlNextWord(items []sqlLayoutToken) string { for _, item := range items { if !item.comment { return item.word } } return ""}
func sqlGroupEnd(items []sqlLayoutToken, start int) int { depth := 0 for i := start; i < len(items); i++ { switch items[i].text { case "(", "[": depth++ case ")", "]": depth-- if depth == 0 { return i } } } return start // Incomplete SQL remains the compiler's diagnostic to report.}
func (w *sqlLayout) write(items []sqlLayoutToken, indent int, mode string) { clause, statement := "", "" current := indent list := mode == "columns" || mode == "fields" createTable, between, cases := false, false, 0 for i := 0; i < len(items); i++ { item := items[i] if item.comment { pending := w.breaks if item.lineBefore { w.breaks = max(1, w.breaks) } else { w.breaks = 0 // Keep an end-of-line comment with the preceding token. } w.emit(item, current, false) w.breaks = pending if item.lineBefore || strings.HasPrefix(item.text, "--") { w.breaks = max(1, w.breaks) } continue } if item.stringLiteral && w.lastString && item.lineBefore { // PostgreSQL concatenates adjacent strings only across a newline. w.breaks = max(1, w.breaks) } if item.text == "(" || item.text == "[" { end := sqlGroupEnd(items, i) if end != i { first := sqlNextWord(items[i+1 : end]) query := first == "SELECT" || first == "WITH" || first == "INSERT" || first == "UPDATE" || first == "DELETE" table := createTable && clause == "" space := table || statement == "INSERT" && clause == "" || slices.Contains([]string{"IN", "EXISTS", "OVER", "FILTER", "AS", "VALUES", "KEY", "CHECK", "ON", "CONFLICT", "AND", "OR", "NOT", "WHERE"}, w.previous.word) || w.previous.text == "=" w.emit(item, current, space) if query || table { w.breaks = 1 childMode := "query" if table { childMode = "fields" } w.write(items[i+1:end], current+1, childMode) w.breaks = 1 } else { w.write(items[i+1:end], current, "expression") } w.emit(items[end], current, false) createTable = false i = end continue } } if item.text == ";" { w.emit(item, current, false) w.breaks = 2 current, clause, statement, createTable = indent, "", "", false continue } if item.text == "," { w.emit(item, current, false) if list { w.breaks = 1 } continue } key := item.word if w.previous.text == "." { key = "" // A qualified identifier is not a clause. } if statement == "" && key != "" { statement = key } if key == "TABLE" && statement == "CREATE" { createTable = true } if key == "CASE" { cases++ } else if key == "END" && cases > 0 { cases-- } if mode != "expression" && mode != "fields" && cases == 0 { next := sqlNextWord(items[i+1:]) previous := w.previous.word switch { case key == "UPDATE" && previous == "DO": statement = "UPDATE" case key == "WITH" && statement == "WITH": clause, list = "WITH", true w.emit(item, indent, false) current = indent + 1 if next != "RECURSIVE" { w.breaks = 1 } continue case key == "RECURSIVE" && clause == "WITH": w.emit(item, indent, false) w.breaks = 1 continue case key == "SELECT" || key == "RETURNING" || key == "SET" && statement == "UPDATE" && clause != "SET" || key == "VALUES" && statement == "INSERT": if key == "SELECT" { statement = "SELECT" } clause, list = key, true if w.previous.text != "" && w.previous.text != "(" { w.breaks = max(1, w.breaks) } w.emit(item, indent, false) current = indent + 1 if key != "SELECT" || next != "ALL" && next != "DISTINCT" { w.breaks = 1 } continue case (key == "ALL" || key == "DISTINCT") && previous == "SELECT": w.emit(item, indent, false) w.breaks = 1 continue case key == "FROM" && previous != "DELETE" || key == "WHERE" || key == "HAVING" || (key == "GROUP" || key == "ORDER") && next == "BY" || key == "LIMIT" || key == "OFFSET" || key == "UNION" || key == "INTERSECT" || key == "EXCEPT" || key == "WINDOW" || key == "ON" && next == "CONFLICT": current, clause, list = indent, key, false w.breaks = max(1, w.breaks) case key == "JOIN" && !slices.Contains([]string{"LEFT", "RIGHT", "FULL", "INNER", "OUTER", "CROSS", "NATURAL"}, previous) || (key == "LEFT" || key == "RIGHT" || key == "FULL" || key == "INNER" || key == "CROSS" || key == "NATURAL") && (next == "JOIN" || next == "OUTER"): current, clause, list = indent, "JOIN", false w.breaks = max(1, w.breaks) case key == "BETWEEN": between = true case key == "AND" && between: between = false case key == "AND" || key == "OR": if clause == "WHERE" || clause == "HAVING" || clause == "JOIN" || mode == "predicate" { current = indent + 1 w.breaks = max(1, w.breaks) } } } w.emit(item, current, false) }}