config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package config
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strings"
  10. "github.com/kyleconroy/sqlc/internal/pattern"
  11. "github.com/kyleconroy/sqlc/internal/sql/ast"
  12. yaml "gopkg.in/yaml.v3"
  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. )
  64. type Config struct {
  65. Version string `json:"version" yaml:"version"`
  66. SQL []SQL `json:"sql" yaml:"sql"`
  67. Gen Gen `json:"overrides,omitempty" yaml:"overrides"`
  68. }
  69. type Gen struct {
  70. Go *GenGo `json:"go,omitempty" yaml:"go"`
  71. Kotlin *GenKotlin `json:"kotlin,omitempty" yaml:"kotlin"`
  72. }
  73. type GenGo struct {
  74. Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
  75. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  76. }
  77. type GenKotlin struct {
  78. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  79. }
  80. type SQL struct {
  81. Engine Engine `json:"engine,omitempty" yaml:"engine"`
  82. Schema Paths `json:"schema" yaml:"schema"`
  83. Queries Paths `json:"queries" yaml:"queries"`
  84. StrictFunctionChecks bool `json:"strict_function_checks" yaml:"strict_function_checks"`
  85. Gen SQLGen `json:"gen" yaml:"gen"`
  86. }
  87. type SQLGen struct {
  88. Go *SQLGo `json:"go,omitempty" yaml:"go"`
  89. Kotlin *SQLKotlin `json:"kotlin,omitempty" yaml:"kotlin"`
  90. Python *SQLPython `json:"python,omitempty" yaml:"python"`
  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. EmitDBTags bool `json:"emit_db_tags" yaml:"emit_db_tags"`
  96. EmitPreparedQueries bool `json:"emit_prepared_queries" yaml:"emit_prepared_queries"`
  97. EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
  98. EmitEmptySlices bool `json:"emit_empty_slices,omitempty" yaml:"emit_empty_slices"`
  99. EmitExportedQueries bool `json:"emit_exported_queries" yaml:"emit_exported_queries"`
  100. EmitResultStructPointers bool `json:"emit_result_struct_pointers" yaml:"emit_result_struct_pointers"`
  101. EmitParamsStructPointers bool `json:"emit_params_struct_pointers" yaml:"emit_params_struct_pointers"`
  102. EmitMethodsWithDBArgument bool `json:"emit_methods_with_db_argument,omitempty" yaml:"emit_methods_with_db_argument"`
  103. JSONTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
  104. Package string `json:"package" yaml:"package"`
  105. Out string `json:"out" yaml:"out"`
  106. Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
  107. Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
  108. SQLPackage string `json:"sql_package" yaml:"sql_package"`
  109. OutputDBFileName string `json:"output_db_file_name,omitempty" yaml:"output_db_file_name"`
  110. OutputModelsFileName string `json:"output_models_file_name,omitempty" yaml:"output_models_file_name"`
  111. OutputQuerierFileName string `json:"output_querier_file_name,omitempty" yaml:"output_querier_file_name"`
  112. OutputFilesSuffix string `json:"output_files_suffix,omitempty" yaml:"output_files_suffix"`
  113. }
  114. type SQLKotlin struct {
  115. EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
  116. Package string `json:"package" yaml:"package"`
  117. Out string `json:"out" yaml:"out"`
  118. }
  119. type SQLPython struct {
  120. EmitExactTableNames bool `json:"emit_exact_table_names" yaml:"emit_exact_table_names"`
  121. EmitSyncQuerier bool `json:"emit_sync_querier" yaml:"emit_sync_querier"`
  122. EmitAsyncQuerier bool `json:"emit_async_querier" yaml:"emit_async_querier"`
  123. Package string `json:"package" yaml:"package"`
  124. Out string `json:"out" yaml:"out"`
  125. Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
  126. }
  127. type Override struct {
  128. // name of the golang type to use, e.g. `github.com/segmentio/ksuid.KSUID`
  129. GoType GoType `json:"go_type" yaml:"go_type"`
  130. // name of the python type to use, e.g. `mymodule.TypeName`
  131. PythonType PythonType `json:"python_type" yaml:"python_type"`
  132. // fully qualified name of the Go type, e.g. `github.com/segmentio/ksuid.KSUID`
  133. DBType string `json:"db_type" yaml:"db_type"`
  134. Deprecated_PostgresType string `json:"postgres_type" yaml:"postgres_type"`
  135. // for global overrides only when two different engines are in use
  136. Engine Engine `json:"engine,omitempty" yaml:"engine"`
  137. // True if the GoType should override if the maching postgres type is nullable
  138. Nullable bool `json:"nullable" yaml:"nullable"`
  139. // Deprecated. Use the `nullable` property instead
  140. Deprecated_Null bool `json:"null" yaml:"null"`
  141. // fully qualified name of the column, e.g. `accounts.id`
  142. Column string `json:"column" yaml:"column"`
  143. ColumnName *pattern.Match
  144. TableCatalog *pattern.Match
  145. TableSchema *pattern.Match
  146. TableRel *pattern.Match
  147. GoImportPath string
  148. GoPackage string
  149. GoTypeName string
  150. GoBasicType bool
  151. }
  152. func (o *Override) Matches(n *ast.TableName, defaultSchema string) bool {
  153. if n == nil {
  154. return false
  155. }
  156. schema := n.Schema
  157. if n.Schema == "" {
  158. schema = defaultSchema
  159. }
  160. if o.TableCatalog != nil && !o.TableCatalog.MatchString(n.Catalog) {
  161. return false
  162. }
  163. if o.TableSchema == nil && schema != "" {
  164. return false
  165. }
  166. if o.TableSchema != nil && !o.TableSchema.MatchString(schema) {
  167. return false
  168. }
  169. if o.TableRel == nil && n.Name != "" {
  170. return false
  171. }
  172. if o.TableRel != nil && !o.TableRel.MatchString(n.Name) {
  173. return false
  174. }
  175. return true
  176. }
  177. func (o *Override) Parse() (err error) {
  178. // validate deprecated postgres_type field
  179. if o.Deprecated_PostgresType != "" {
  180. fmt.Fprintf(os.Stderr, "WARNING: \"postgres_type\" is deprecated. Instead, use \"db_type\" to specify a type override.\n")
  181. if o.DBType != "" {
  182. return fmt.Errorf(`Type override configurations cannot have "db_type" and "postres_type" together. Use "db_type" alone`)
  183. }
  184. o.DBType = o.Deprecated_PostgresType
  185. }
  186. // validate deprecated null field
  187. if o.Deprecated_Null {
  188. fmt.Fprintf(os.Stderr, "WARNING: \"null\" is deprecated. Instead, use the \"nullable\" field.\n")
  189. o.Nullable = true
  190. }
  191. // validate option combinations
  192. switch {
  193. case o.Column != "" && o.DBType != "":
  194. return fmt.Errorf("Override specifying both `column` (%q) and `db_type` (%q) is not valid.", o.Column, o.DBType)
  195. case o.Column == "" && o.DBType == "":
  196. return fmt.Errorf("Override must specify one of either `column` or `db_type`")
  197. }
  198. // validate Column
  199. if o.Column != "" {
  200. colParts := strings.Split(o.Column, ".")
  201. switch len(colParts) {
  202. case 2:
  203. if o.ColumnName, err = pattern.MatchCompile(colParts[1]); err != nil {
  204. return err
  205. }
  206. if o.TableRel, err = pattern.MatchCompile(colParts[0]); err != nil {
  207. return err
  208. }
  209. if o.TableSchema, err = pattern.MatchCompile("public"); err != nil {
  210. return err
  211. }
  212. case 3:
  213. if o.ColumnName, err = pattern.MatchCompile(colParts[2]); err != nil {
  214. return err
  215. }
  216. if o.TableRel, err = pattern.MatchCompile(colParts[1]); err != nil {
  217. return err
  218. }
  219. if o.TableSchema, err = pattern.MatchCompile(colParts[0]); err != nil {
  220. return err
  221. }
  222. case 4:
  223. if o.ColumnName, err = pattern.MatchCompile(colParts[3]); err != nil {
  224. return err
  225. }
  226. if o.TableRel, err = pattern.MatchCompile(colParts[2]); err != nil {
  227. return err
  228. }
  229. if o.TableSchema, err = pattern.MatchCompile(colParts[1]); err != nil {
  230. return err
  231. }
  232. if o.TableCatalog, err = pattern.MatchCompile(colParts[0]); err != nil {
  233. return err
  234. }
  235. default:
  236. return fmt.Errorf("Override `column` specifier %q is not the proper format, expected '[catalog.][schema.]tablename.colname'", o.Column)
  237. }
  238. }
  239. // validate GoType
  240. parsed, err := o.GoType.Parse()
  241. if err != nil {
  242. return err
  243. }
  244. o.GoImportPath = parsed.ImportPath
  245. o.GoPackage = parsed.Package
  246. o.GoTypeName = parsed.TypeName
  247. o.GoBasicType = parsed.BasicType
  248. return nil
  249. }
  250. var ErrMissingVersion = errors.New("no version number")
  251. var ErrUnknownVersion = errors.New("invalid version number")
  252. var ErrMissingEngine = errors.New("unknown engine")
  253. var ErrUnknownEngine = errors.New("invalid engine")
  254. var ErrNoPackages = errors.New("no packages")
  255. var ErrNoPackageName = errors.New("missing package name")
  256. var ErrNoPackagePath = errors.New("missing package path")
  257. var ErrNoOutPath = errors.New("no output path")
  258. var ErrNoQuerierType = errors.New("no querier emit type enabled")
  259. func ParseConfig(rd io.Reader) (Config, error) {
  260. var buf bytes.Buffer
  261. var config Config
  262. var version versionSetting
  263. ver := io.TeeReader(rd, &buf)
  264. dec := yaml.NewDecoder(ver)
  265. if err := dec.Decode(&version); err != nil {
  266. return config, err
  267. }
  268. if version.Number == "" {
  269. return config, ErrMissingVersion
  270. }
  271. switch version.Number {
  272. case "1":
  273. return v1ParseConfig(&buf)
  274. case "2":
  275. return v2ParseConfig(&buf)
  276. default:
  277. return config, ErrUnknownVersion
  278. }
  279. }
  280. func Validate(c *Config) error {
  281. for _, sql := range c.SQL {
  282. sqlGo := sql.Gen.Go
  283. if sqlGo == nil {
  284. continue
  285. }
  286. if sqlGo.EmitMethodsWithDBArgument && sqlGo.EmitPreparedQueries {
  287. return fmt.Errorf("invalid config: emit_methods_with_db_argument and emit_prepared_queries settings are mutually exclusive")
  288. }
  289. }
  290. return nil
  291. }
  292. type CombinedSettings struct {
  293. Global Config
  294. Package SQL
  295. Go SQLGo
  296. Kotlin SQLKotlin
  297. Python SQLPython
  298. Rename map[string]string
  299. Overrides []Override
  300. }
  301. func Combine(conf Config, pkg SQL) CombinedSettings {
  302. cs := CombinedSettings{
  303. Global: conf,
  304. Package: pkg,
  305. }
  306. if conf.Gen.Go != nil {
  307. cs.Rename = conf.Gen.Go.Rename
  308. cs.Overrides = append(cs.Overrides, conf.Gen.Go.Overrides...)
  309. }
  310. if conf.Gen.Kotlin != nil {
  311. cs.Rename = conf.Gen.Kotlin.Rename
  312. }
  313. if pkg.Gen.Go != nil {
  314. cs.Go = *pkg.Gen.Go
  315. cs.Overrides = append(cs.Overrides, pkg.Gen.Go.Overrides...)
  316. }
  317. if pkg.Gen.Kotlin != nil {
  318. cs.Kotlin = *pkg.Gen.Kotlin
  319. }
  320. if pkg.Gen.Python != nil {
  321. cs.Python = *pkg.Gen.Python
  322. cs.Overrides = append(cs.Overrides, pkg.Gen.Python.Overrides...)
  323. }
  324. return cs
  325. }