|
| 1 | +package compiler |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "github.com/sqlc-dev/sqlc/internal/core" |
| 7 | + "github.com/sqlc-dev/sqlc/internal/source" |
| 8 | + "github.com/sqlc-dev/sqlc/internal/sql/ast" |
| 9 | +) |
| 10 | + |
| 11 | +// expandCore rewrites the stars in a query's text with the columns the core |
| 12 | +// analyzer resolved them to. The analyzer has already walked the statement and |
| 13 | +// its subqueries, so there is nothing left to look up here: what remains is |
| 14 | +// deciding how each name is written, which is the engine's business and not |
| 15 | +// the core's. |
| 16 | +func (c *Compiler) expandCore(raw *ast.RawStmt, stars []core.StarExpansion) ([]source.Edit, error) { |
| 17 | + if len(stars) == 0 { |
| 18 | + return nil, nil |
| 19 | + } |
| 20 | + edits := make([]source.Edit, 0, len(stars)) |
| 21 | + seen := make(map[int]bool, len(stars)) |
| 22 | + for _, star := range stars { |
| 23 | + // A statement analyzed more than once — the same CTE referenced twice, |
| 24 | + // say — reports its stars once per pass. Editing one twice would |
| 25 | + // overlap, so only the first is kept. |
| 26 | + if seen[star.Location] { |
| 27 | + continue |
| 28 | + } |
| 29 | + seen[star.Location] = true |
| 30 | + |
| 31 | + // Everything before the star qualifies it: "foo.*" is scoped to foo, |
| 32 | + // while a bare "*" covers every relation in the FROM clause. |
| 33 | + scope := strings.Join(star.Fields[:len(star.Fields)-1], ".") |
| 34 | + |
| 35 | + // An unqualified star that covers more than one relation may name the |
| 36 | + // same column twice, so those are written with their relation. |
| 37 | + counts := map[string]int{} |
| 38 | + if scope == "" { |
| 39 | + for _, col := range star.Columns { |
| 40 | + counts[col.Name]++ |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + cols := make([]string, 0, len(star.Columns)) |
| 45 | + for _, col := range star.Columns { |
| 46 | + cname := col.Name |
| 47 | + if star.Alias != "" { |
| 48 | + cname = star.Alias |
| 49 | + } |
| 50 | + cname = c.quoteIdent(cname) |
| 51 | + if scope != "" { |
| 52 | + cname = c.quoteIdent(scope) + "." + cname |
| 53 | + } |
| 54 | + if counts[cname] > 1 { |
| 55 | + cname = c.quoteIdent(col.Relation) + "." + cname |
| 56 | + } |
| 57 | + |
| 58 | + // This is important for SQLite in particular which needs to wrap |
| 59 | + // jsonb column values with `json(colname)` so they're in a publicly |
| 60 | + // usable format (i.e. not jsonb). |
| 61 | + cols = append(cols, c.selector.ColumnExpr(cname, &Column{ |
| 62 | + Name: col.Name, |
| 63 | + DataType: col.DataType, |
| 64 | + })) |
| 65 | + } |
| 66 | + |
| 67 | + edits = append(edits, source.Edit{ |
| 68 | + Location: star.Location - raw.StmtLocation, |
| 69 | + OldFunc: c.starOldFunc(star.Fields), |
| 70 | + New: strings.Join(cols, ", "), |
| 71 | + }) |
| 72 | + } |
| 73 | + return edits, nil |
| 74 | +} |
0 commit comments