|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "path/filepath" |
| 8 | +) |
| 9 | + |
| 10 | +func v2ParseConfig(rd io.Reader) (Config, error) { |
| 11 | + dec := json.NewDecoder(rd) |
| 12 | + dec.DisallowUnknownFields() |
| 13 | + var conf Config |
| 14 | + if err := dec.Decode(&conf); err != nil { |
| 15 | + return conf, err |
| 16 | + } |
| 17 | + if conf.Version == "" { |
| 18 | + return conf, ErrMissingVersion |
| 19 | + } |
| 20 | + if conf.Version != "2" { |
| 21 | + return conf, ErrUnknownVersion |
| 22 | + } |
| 23 | + if len(conf.SQL) == 0 { |
| 24 | + return conf, ErrNoPackages |
| 25 | + } |
| 26 | + if err := conf.validateGlobalOverrides(); err != nil { |
| 27 | + return conf, err |
| 28 | + } |
| 29 | + if conf.Gen.Go != nil { |
| 30 | + for i := range conf.Gen.Go.Overrides { |
| 31 | + if err := conf.Gen.Go.Overrides[i].Parse(); err != nil { |
| 32 | + return conf, err |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + for j := range conf.SQL { |
| 37 | + if conf.SQL[j].Engine == "" { |
| 38 | + return conf, ErrMissingEngine |
| 39 | + } |
| 40 | + if conf.SQL[j].Gen.Go != nil { |
| 41 | + if conf.SQL[j].Gen.Go.Out == "" { |
| 42 | + return conf, ErrNoPackagePath |
| 43 | + } |
| 44 | + if conf.SQL[j].Gen.Go.Package == "" { |
| 45 | + conf.SQL[j].Gen.Go.Package = filepath.Base(conf.SQL[j].Gen.Go.Out) |
| 46 | + } |
| 47 | + for i := range conf.SQL[j].Gen.Go.Overrides { |
| 48 | + if err := conf.SQL[j].Gen.Go.Overrides[i].Parse(); err != nil { |
| 49 | + return conf, err |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return conf, nil |
| 55 | +} |
| 56 | + |
| 57 | +func (c *Config) validateGlobalOverrides() error { |
| 58 | + engines := map[Engine]struct{}{} |
| 59 | + for _, pkg := range c.SQL { |
| 60 | + if _, ok := engines[pkg.Engine]; !ok { |
| 61 | + engines[pkg.Engine] = struct{}{} |
| 62 | + } |
| 63 | + } |
| 64 | + if c.Gen.Go == nil { |
| 65 | + return nil |
| 66 | + } |
| 67 | + usesMultipleEngines := len(engines) > 1 |
| 68 | + for _, oride := range c.Gen.Go.Overrides { |
| 69 | + if usesMultipleEngines && oride.Engine == "" { |
| 70 | + return fmt.Errorf(`the "engine" field is required for global type overrides because your configuration uses multiple database engines`) |
| 71 | + } |
| 72 | + } |
| 73 | + return nil |
| 74 | +} |
0 commit comments