|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | + |
| 11 | + pg_query "github.com/pganalyze/pg_query_go/v4" |
| 12 | + "github.com/sqlc-dev/sqlc/internal/engine/postgresql" |
| 13 | + "github.com/sqlc-dev/sqlc/internal/sql/ast" |
| 14 | +) |
| 15 | + |
| 16 | +func TestFormat(t *testing.T) { |
| 17 | + t.Parallel() |
| 18 | + var queries []string |
| 19 | + err := filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error { |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
| 23 | + if !strings.Contains(path, filepath.Join("pgx/v5")) { |
| 24 | + return nil |
| 25 | + } |
| 26 | + if info.Name() == "query.sql" { |
| 27 | + queries = append(queries, path) |
| 28 | + return filepath.SkipDir |
| 29 | + } |
| 30 | + return nil |
| 31 | + }) |
| 32 | + if err != nil { |
| 33 | + t.Fatal(err) |
| 34 | + } |
| 35 | + parse := postgresql.NewParser() |
| 36 | + for _, q := range queries { |
| 37 | + q := q |
| 38 | + t.Run(filepath.Dir(q), func(t *testing.T) { |
| 39 | + contents, err := os.ReadFile(q) |
| 40 | + if err != nil { |
| 41 | + t.Fatal(err) |
| 42 | + } |
| 43 | + for i, query := range bytes.Split(bytes.TrimSpace(contents), []byte(";")) { |
| 44 | + if len(query) <= 1 { |
| 45 | + continue |
| 46 | + } |
| 47 | + query := query |
| 48 | + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 49 | + expected, err := pg_query.Fingerprint(string(query)) |
| 50 | + if err != nil { |
| 51 | + t.Fatal(err) |
| 52 | + } |
| 53 | + stmts, err := parse.Parse(bytes.NewReader(query)) |
| 54 | + if err != nil { |
| 55 | + t.Fatal(err) |
| 56 | + } |
| 57 | + if len(stmts) != 1 { |
| 58 | + t.Fatal("expected one statement") |
| 59 | + } |
| 60 | + out := ast.Format(stmts[0].Raw) |
| 61 | + actual, err := pg_query.Fingerprint(out) |
| 62 | + if err != nil { |
| 63 | + t.Error(err) |
| 64 | + } |
| 65 | + if expected != actual { |
| 66 | + t.Errorf("- %s", expected) |
| 67 | + t.Errorf("- %s", string(query)) |
| 68 | + t.Errorf("+ %s", actual) |
| 69 | + t.Errorf("+ %s", out) |
| 70 | + } |
| 71 | + }) |
| 72 | + } |
| 73 | + }) |
| 74 | + } |
| 75 | +} |
0 commit comments