v_two.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package config
  2. import (
  3. "fmt"
  4. "io"
  5. "path/filepath"
  6. yaml "gopkg.in/yaml.v3"
  7. )
  8. func v2ParseConfig(rd io.Reader) (Config, error) {
  9. dec := yaml.NewDecoder(rd)
  10. dec.KnownFields(true)
  11. var conf Config
  12. if err := dec.Decode(&conf); err != nil {
  13. return conf, err
  14. }
  15. if conf.Version == "" {
  16. return conf, ErrMissingVersion
  17. }
  18. if conf.Version != "2" {
  19. return conf, ErrUnknownVersion
  20. }
  21. if len(conf.SQL) == 0 {
  22. return conf, ErrNoPackages
  23. }
  24. if err := conf.validateGlobalOverrides(); err != nil {
  25. return conf, err
  26. }
  27. if conf.Gen.Go != nil {
  28. for i := range conf.Gen.Go.Overrides {
  29. if err := conf.Gen.Go.Overrides[i].Parse(); err != nil {
  30. return conf, err
  31. }
  32. }
  33. }
  34. for j := range conf.SQL {
  35. if conf.SQL[j].Engine == "" {
  36. return conf, ErrMissingEngine
  37. }
  38. if conf.SQL[j].Gen.Go != nil {
  39. if conf.SQL[j].Gen.Go.Out == "" {
  40. return conf, ErrNoPackagePath
  41. }
  42. if conf.SQL[j].Gen.Go.Package == "" {
  43. conf.SQL[j].Gen.Go.Package = filepath.Base(conf.SQL[j].Gen.Go.Out)
  44. }
  45. for i := range conf.SQL[j].Gen.Go.Overrides {
  46. if err := conf.SQL[j].Gen.Go.Overrides[i].Parse(); err != nil {
  47. return conf, err
  48. }
  49. }
  50. }
  51. if conf.SQL[j].Gen.Kotlin != nil {
  52. if conf.SQL[j].Gen.Kotlin.Out == "" {
  53. return conf, ErrNoOutPath
  54. }
  55. if conf.SQL[j].Gen.Kotlin.Package == "" {
  56. return conf, ErrNoPackageName
  57. }
  58. }
  59. if conf.SQL[j].Gen.Python != nil {
  60. if conf.SQL[j].Gen.Python.Out == "" {
  61. return conf, ErrNoOutPath
  62. }
  63. if conf.SQL[j].Gen.Python.Package == "" {
  64. return conf, ErrNoPackageName
  65. }
  66. if !conf.SQL[j].Gen.Python.EmitSyncQuerier && !conf.SQL[j].Gen.Python.EmitAsyncQuerier {
  67. return conf, ErrNoQuerierType
  68. }
  69. for i := range conf.SQL[j].Gen.Python.Overrides {
  70. if err := conf.SQL[j].Gen.Python.Overrides[i].Parse(); err != nil {
  71. return conf, err
  72. }
  73. }
  74. }
  75. }
  76. return conf, nil
  77. }
  78. func (c *Config) validateGlobalOverrides() error {
  79. engines := map[Engine]struct{}{}
  80. for _, pkg := range c.SQL {
  81. if _, ok := engines[pkg.Engine]; !ok {
  82. engines[pkg.Engine] = struct{}{}
  83. }
  84. }
  85. if c.Gen.Go == nil {
  86. return nil
  87. }
  88. usesMultipleEngines := len(engines) > 1
  89. for _, oride := range c.Gen.Go.Overrides {
  90. if usesMultipleEngines && oride.Engine == "" {
  91. return fmt.Errorf(`the "engine" field is required for global type overrides because your configuration uses multiple database engines`)
  92. }
  93. }
  94. return nil
  95. }