|
| 1 | +package compiler |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "github.com/sqlc-dev/sqlc/internal/core" |
| 7 | + "github.com/sqlc-dev/sqlc/internal/sql/ast" |
| 8 | + "github.com/sqlc-dev/sqlc/internal/sql/catalog" |
| 9 | +) |
| 10 | + |
| 11 | +// coreResultCatalog dumps the core catalog into the legacy catalog shape a |
| 12 | +// Result carries, so codegen sees the same table models either way a query |
| 13 | +// set was analyzed. Only relations make the trip: codegen reads tables and |
| 14 | +// their columns to build models, and none of the types, functions or |
| 15 | +// operators the core catalog also holds. |
| 16 | +func coreResultCatalog(c *core.Catalog) (*catalog.Catalog, error) { |
| 17 | + cat := catalog.New("public") |
| 18 | + namespaces, err := c.Namespaces() |
| 19 | + if err != nil { |
| 20 | + return nil, err |
| 21 | + } |
| 22 | + for _, ns := range namespaces { |
| 23 | + schema := &catalog.Schema{Name: ns.Name} |
| 24 | + tables, err := c.TablesInNamespace(ns.OID) |
| 25 | + if err != nil { |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + for _, table := range tables { |
| 29 | + cols, err := c.ClassCodegenColumns(table.OID) |
| 30 | + if err != nil { |
| 31 | + return nil, err |
| 32 | + } |
| 33 | + t := &catalog.Table{Rel: &ast.TableName{Schema: ns.Name, Name: table.Name}} |
| 34 | + for _, col := range cols { |
| 35 | + // The catalog names an array type after its element with the |
| 36 | + // suffix appended, which is codegen's data type and array |
| 37 | + // flag in one string. The core catalog holds one dimension, |
| 38 | + // and codegen renders a "[]" per dimension. |
| 39 | + dataType, isArray := strings.CutSuffix(col.TypeName, core.ArraySuffix) |
| 40 | + column := &catalog.Column{ |
| 41 | + Name: col.Name, |
| 42 | + Type: ast.TypeName{Name: dataType}, |
| 43 | + IsNotNull: col.NotNull, |
| 44 | + IsArray: isArray, |
| 45 | + } |
| 46 | + if isArray { |
| 47 | + column.ArrayDims = 1 |
| 48 | + } |
| 49 | + t.Columns = append(t.Columns, column) |
| 50 | + } |
| 51 | + schema.Tables = append(schema.Tables, t) |
| 52 | + } |
| 53 | + cat.Schemas = append(cat.Schemas, schema) |
| 54 | + } |
| 55 | + return cat, nil |
| 56 | +} |
0 commit comments