|
| 1 | +// +build exp |
| 2 | + |
| 3 | +package compiler |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "sort" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/kyleconroy/sqlc/internal/config" |
| 13 | + "github.com/kyleconroy/sqlc/internal/dinosql" |
| 14 | + "github.com/kyleconroy/sqlc/internal/dolphin" |
| 15 | + "github.com/kyleconroy/sqlc/internal/pg" |
| 16 | + "github.com/kyleconroy/sqlc/internal/postgresql" |
| 17 | + "github.com/kyleconroy/sqlc/internal/sql/ast" |
| 18 | + "github.com/kyleconroy/sqlc/internal/sql/catalog" |
| 19 | + "github.com/kyleconroy/sqlc/internal/sqlite" |
| 20 | +) |
| 21 | + |
| 22 | +type Parser interface { |
| 23 | + Parse(io.Reader) ([]ast.Statement, error) |
| 24 | +} |
| 25 | + |
| 26 | +func Run(conf config.SQL, combo config.CombinedSettings) (*Result, error) { |
| 27 | + var p Parser |
| 28 | + |
| 29 | + switch conf.Engine { |
| 30 | + case config.EngineXLemon: |
| 31 | + p = sqlite.NewParser() |
| 32 | + case config.EngineXDolphin: |
| 33 | + p = dolphin.NewParser() |
| 34 | + case config.EngineXElephant: |
| 35 | + p = postgresql.NewParser() |
| 36 | + default: |
| 37 | + return nil, fmt.Errorf("unknown engine: %s", conf.Engine) |
| 38 | + } |
| 39 | + |
| 40 | + rd, err := os.Open(conf.Schema) |
| 41 | + if err != nil { |
| 42 | + return nil, err |
| 43 | + } |
| 44 | + |
| 45 | + stmts, err := p.Parse(rd) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + |
| 50 | + c, err := catalog.Build(stmts) |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + |
| 55 | + var structs []dinosql.GoStruct |
| 56 | + for _, schema := range c.Schemas { |
| 57 | + for _, table := range schema.Tables { |
| 58 | + s := dinosql.GoStruct{ |
| 59 | + Table: pg.FQN{Schema: table.Rel.Schema, Rel: table.Rel.Name}, |
| 60 | + Name: strings.Title(table.Rel.Name), |
| 61 | + } |
| 62 | + for _, col := range table.Columns { |
| 63 | + s.Fields = append(s.Fields, dinosql.GoField{ |
| 64 | + Name: strings.Title(col.Name), |
| 65 | + Type: "string", |
| 66 | + Tags: map[string]string{"json:": col.Name}, |
| 67 | + }) |
| 68 | + } |
| 69 | + structs = append(structs, s) |
| 70 | + } |
| 71 | + } |
| 72 | + if len(structs) > 0 { |
| 73 | + sort.Slice(structs, func(i, j int) bool { return structs[i].Name < structs[j].Name }) |
| 74 | + } |
| 75 | + |
| 76 | + return &Result{structs: structs}, nil |
| 77 | +} |
0 commit comments