config.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package config
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "go/types"
  8. "io"
  9. "os"
  10. "strings"
  11. yaml "gopkg.in/yaml.v3"
  12. "github.com/kyleconroy/sqlc/internal/core"
  13. )
  14. const errMessageNoVersion = `The configuration file must have a version number.
  15. Set the version to 1 at the top of sqlc.json:
  16. {
  17. "version": "1"
  18. ...
  19. }
  20. `
  21. const errMessageUnknownVersion = `The configuration file has an invalid version number.
  22. The only supported version is "1".
  23. `
  24. const errMessageNoPackages = `No packages are configured`
  25. type versionSetting struct {
  26. Number string `json:"version" yaml:"version"`
  27. }
  28. type Engine string
  29. type Paths []string
  30. func (p *Paths) UnmarshalJSON(data []byte) error {
  31. if string(data[0]) == `[` {
  32. var out []string
  33. if err := json.Unmarshal(data, &out); err != nil {
  34. return nil
  35. }
  36. *p = Paths(out)
  37. return nil
  38. }
  39. var out string
  40. if err := json.Unmarshal(data, &out); err != nil {
  41. return nil
  42. }
  43. *p = Paths([]string{out})
  44. return nil
  45. }
  46. func (p *Paths) UnmarshalYAML(unmarshal func(interface{}) error) error {
  47. out := []string{}
  48. if sliceErr := unmarshal(&out); sliceErr != nil {
  49. var ele string
  50. if strErr := unmarshal(&ele); strErr != nil {
  51. return strErr
  52. }
  53. out = []string{ele}
  54. }
  55. *p = Paths(out)
  56. return nil
  57. }
  58. const (
  59. EngineMySQL Engine = "mysql"
  60. EnginePostgreSQL Engine = "postgresql"
  61. // Experimental engines
  62. EngineXLemon Engine = "_lemon"
  63. EngineXDolphin Engine = "_dolphin"
  64. EngineXVitess Engine = "_vitess"
  65. )
  66. type Config struct {
  67. Version string `json:"version" yaml:"version"`
  68. SQL []SQL `json:"sql" yaml:"sql"`
  69. Gen Gen `json:"overrides,omitempty" yaml:"overrides"`
  70. }
  71. type Gen struct {
  72. Go *GenGo `json:"go,omitempty" yaml:"go"`
  73. Kotlin *GenKotlin `json:"kotlin,omitempty" yaml:"kotlin"`
  74. }
  75. type GenGo struct {
  76. Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
  77. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  78. }
  79. type GenKotlin struct {
  80. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  81. }
  82. type SQL struct {
  83. Engine Engine `json:"engine,omitempty" yaml:"engine"`
  84. Schema Paths `json:"schema" yaml:"schema"`
  85. Queries Paths `json:"queries" yaml:"queries"`
  86. Gen SQLGen `json:"gen" yaml:"gen"`
  87. }
  88. type SQLGen struct {
  89. Go *SQLGo `json:"go,omitempty" yaml:"go"`
  90. Kotlin *SQLKotlin `json:"kotlin,omitempty" yaml:"kotlin"`
  91. }
  92. type SQLGo struct {
  93. EmitInterface bool `json:"emit_interface" yaml:"emit_interface"`
  94. EmitJSONTags bool `json:"emit_json_tags" yaml:"emit_json_tags"`
  95. EmitPreparedQueries bool `json:"emit_prepared_queries" yaml:"emit_prepared_queries"`
  96. EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
  97. EmitEmptySlices bool `json:"emit_empty_slices,omitempty" yaml:"emit_empty_slices"`
  98. Package string `json:"package" yaml:"package"`
  99. Out string `json:"out" yaml:"out"`
  100. Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
  101. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  102. }
  103. type SQLKotlin struct {
  104. EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
  105. Package string `json:"package" yaml:"package"`
  106. Out string `json:"out" yaml:"out"`
  107. }
  108. type Override struct {
  109. // name of the golang type to use, e.g. `github.com/segmentio/ksuid.KSUID`
  110. GoType string `json:"go_type" yaml:"go_type"`
  111. // fully qualified name of the Go type, e.g. `github.com/segmentio/ksuid.KSUID`
  112. DBType string `json:"db_type" yaml:"db_type"`
  113. Deprecated_PostgresType string `json:"postgres_type" yaml:"postgres_type"`
  114. // for global overrides only when two different engines are in use
  115. Engine Engine `json:"engine,omitempty" yaml:"engine"`
  116. // True if the GoType should override if the maching postgres type is nullable
  117. Null bool `json:"null" yaml:"null"`
  118. // fully qualified name of the column, e.g. `accounts.id`
  119. Column string `json:"column" yaml:"column"`
  120. ColumnName string
  121. Table core.FQN
  122. GoTypeName string
  123. GoPackage string
  124. GoBasicType bool
  125. }
  126. func (o *Override) Parse() error {
  127. // validate deprecated postgres_type field
  128. if o.Deprecated_PostgresType != "" {
  129. fmt.Fprintf(os.Stderr, "WARNING: \"postgres_type\" is deprecated. Instead, use \"db_type\" to specify a type override.\n")
  130. if o.DBType != "" {
  131. return fmt.Errorf(`Type override configurations cannot have "db_type" and "postres_type" together. Use "db_type" alone`)
  132. }
  133. o.DBType = o.Deprecated_PostgresType
  134. }
  135. // validate option combinations
  136. switch {
  137. case o.Column != "" && o.DBType != "":
  138. return fmt.Errorf("Override specifying both `column` (%q) and `db_type` (%q) is not valid.", o.Column, o.DBType)
  139. case o.Column == "" && o.DBType == "":
  140. return fmt.Errorf("Override must specify one of either `column` or `db_type`")
  141. }
  142. // validate Column
  143. if o.Column != "" {
  144. colParts := strings.Split(o.Column, ".")
  145. switch len(colParts) {
  146. case 2:
  147. o.ColumnName = colParts[1]
  148. o.Table = core.FQN{Schema: "public", Rel: colParts[0]}
  149. case 3:
  150. o.ColumnName = colParts[2]
  151. o.Table = core.FQN{Schema: colParts[0], Rel: colParts[1]}
  152. case 4:
  153. o.ColumnName = colParts[3]
  154. o.Table = core.FQN{Catalog: colParts[0], Schema: colParts[1], Rel: colParts[2]}
  155. default:
  156. return fmt.Errorf("Override `column` specifier %q is not the proper format, expected '[catalog.][schema.]colname.tablename'", o.Column)
  157. }
  158. }
  159. // validate GoType
  160. lastDot := strings.LastIndex(o.GoType, ".")
  161. lastSlash := strings.LastIndex(o.GoType, "/")
  162. typename := o.GoType
  163. if lastDot == -1 && lastSlash == -1 {
  164. // if the type name has no slash and no dot, validate that the type is a basic Go type
  165. var found bool
  166. for _, typ := range types.Typ {
  167. info := typ.Info()
  168. if info == 0 {
  169. continue
  170. }
  171. if info&types.IsUntyped != 0 {
  172. continue
  173. }
  174. if typename == typ.Name() {
  175. found = true
  176. }
  177. }
  178. if !found {
  179. return fmt.Errorf("Package override `go_type` specifier %q is not a Go basic type e.g. 'string'", o.GoType)
  180. }
  181. o.GoBasicType = true
  182. } else {
  183. // assume the type lives in a Go package
  184. if lastDot == -1 {
  185. return fmt.Errorf("Package override `go_type` specifier %q is not the proper format, expected 'package.type', e.g. 'github.com/segmentio/ksuid.KSUID'", o.GoType)
  186. }
  187. if lastSlash == -1 {
  188. return fmt.Errorf("Package override `go_type` specifier %q is not the proper format, expected 'package.type', e.g. 'github.com/segmentio/ksuid.KSUID'", o.GoType)
  189. }
  190. typename = o.GoType[lastSlash+1:]
  191. if strings.HasPrefix(typename, "go-") {
  192. // a package name beginning with "go-" will give syntax errors in
  193. // generated code. We should do the right thing and get the actual
  194. // import name, but in lieu of that, stripping the leading "go-" may get
  195. // us what we want.
  196. typename = typename[len("go-"):]
  197. }
  198. if strings.HasSuffix(typename, "-go") {
  199. typename = typename[:len(typename)-len("-go")]
  200. }
  201. o.GoPackage = o.GoType[:lastDot]
  202. }
  203. o.GoTypeName = typename
  204. isPointer := o.GoType[0] == '*'
  205. if isPointer {
  206. o.GoPackage = o.GoPackage[1:]
  207. o.GoTypeName = "*" + o.GoTypeName
  208. }
  209. return nil
  210. }
  211. var ErrMissingVersion = errors.New("no version number")
  212. var ErrUnknownVersion = errors.New("invalid version number")
  213. var ErrMissingEngine = errors.New("unknown engine")
  214. var ErrUnknownEngine = errors.New("invalid engine")
  215. var ErrNoPackages = errors.New("no packages")
  216. var ErrNoPackageName = errors.New("missing package name")
  217. var ErrNoPackagePath = errors.New("missing package path")
  218. var ErrKotlinNoOutPath = errors.New("no output path")
  219. func ParseConfig(rd io.Reader) (Config, error) {
  220. var buf bytes.Buffer
  221. var config Config
  222. var version versionSetting
  223. ver := io.TeeReader(rd, &buf)
  224. dec := yaml.NewDecoder(ver)
  225. if err := dec.Decode(&version); err != nil {
  226. return config, err
  227. }
  228. if version.Number == "" {
  229. return config, ErrMissingVersion
  230. }
  231. switch version.Number {
  232. case "1":
  233. return v1ParseConfig(&buf)
  234. case "2":
  235. return v2ParseConfig(&buf)
  236. default:
  237. return config, ErrUnknownVersion
  238. }
  239. }
  240. type CombinedSettings struct {
  241. Global Config
  242. Package SQL
  243. Go SQLGo
  244. Kotlin SQLKotlin
  245. Rename map[string]string
  246. Overrides []Override
  247. }
  248. func Combine(conf Config, pkg SQL) CombinedSettings {
  249. cs := CombinedSettings{
  250. Global: conf,
  251. Package: pkg,
  252. }
  253. if conf.Gen.Go != nil {
  254. cs.Rename = conf.Gen.Go.Rename
  255. cs.Overrides = append(cs.Overrides, conf.Gen.Go.Overrides...)
  256. }
  257. if conf.Gen.Kotlin != nil {
  258. cs.Rename = conf.Gen.Kotlin.Rename
  259. }
  260. if pkg.Gen.Go != nil {
  261. cs.Go = *pkg.Gen.Go
  262. cs.Overrides = append(cs.Overrides, pkg.Gen.Go.Overrides...)
  263. }
  264. if pkg.Gen.Kotlin != nil {
  265. cs.Kotlin = *pkg.Gen.Kotlin
  266. }
  267. return cs
  268. }