generate.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package cmd
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "runtime/trace"
  11. "strings"
  12. "github.com/kyleconroy/sqlc/internal/codegen/golang"
  13. "github.com/kyleconroy/sqlc/internal/codegen/kotlin"
  14. "github.com/kyleconroy/sqlc/internal/codegen/python"
  15. "github.com/kyleconroy/sqlc/internal/compiler"
  16. "github.com/kyleconroy/sqlc/internal/config"
  17. "github.com/kyleconroy/sqlc/internal/debug"
  18. "github.com/kyleconroy/sqlc/internal/multierr"
  19. "github.com/kyleconroy/sqlc/internal/opts"
  20. "github.com/kyleconroy/sqlc/internal/plugin"
  21. )
  22. const errMessageNoVersion = `The configuration file must have a version number.
  23. Set the version to 1 at the top of sqlc.json:
  24. {
  25. "version": "1"
  26. ...
  27. }
  28. `
  29. const errMessageUnknownVersion = `The configuration file has an invalid version number.
  30. The only supported version is "1".
  31. `
  32. const errMessageNoPackages = `No packages are configured`
  33. func printFileErr(stderr io.Writer, dir string, fileErr *multierr.FileError) {
  34. filename := strings.TrimPrefix(fileErr.Filename, dir+"/")
  35. fmt.Fprintf(stderr, "%s:%d:%d: %s\n", filename, fileErr.Line, fileErr.Column, fileErr.Err)
  36. }
  37. type outPair struct {
  38. Gen config.SQLGen
  39. config.SQL
  40. }
  41. func readConfig(stderr io.Writer, dir, filename string) (string, *config.Config, error) {
  42. configPath := ""
  43. if filename != "" {
  44. configPath = filepath.Join(dir, filename)
  45. } else {
  46. var yamlMissing, jsonMissing bool
  47. yamlPath := filepath.Join(dir, "sqlc.yaml")
  48. jsonPath := filepath.Join(dir, "sqlc.json")
  49. if _, err := os.Stat(yamlPath); os.IsNotExist(err) {
  50. yamlMissing = true
  51. }
  52. if _, err := os.Stat(jsonPath); os.IsNotExist(err) {
  53. jsonMissing = true
  54. }
  55. if yamlMissing && jsonMissing {
  56. fmt.Fprintln(stderr, "error parsing configuration files. sqlc.yaml or sqlc.json: file does not exist")
  57. return "", nil, errors.New("config file missing")
  58. }
  59. if !yamlMissing && !jsonMissing {
  60. fmt.Fprintln(stderr, "error: both sqlc.json and sqlc.yaml files present")
  61. return "", nil, errors.New("sqlc.json and sqlc.yaml present")
  62. }
  63. configPath = yamlPath
  64. if yamlMissing {
  65. configPath = jsonPath
  66. }
  67. }
  68. base := filepath.Base(configPath)
  69. blob, err := os.ReadFile(configPath)
  70. if err != nil {
  71. fmt.Fprintf(stderr, "error parsing %s: file does not exist\n", base)
  72. return "", nil, err
  73. }
  74. conf, err := config.ParseConfig(bytes.NewReader(blob))
  75. if err != nil {
  76. switch err {
  77. case config.ErrMissingVersion:
  78. fmt.Fprintf(stderr, errMessageNoVersion)
  79. case config.ErrUnknownVersion:
  80. fmt.Fprintf(stderr, errMessageUnknownVersion)
  81. case config.ErrNoPackages:
  82. fmt.Fprintf(stderr, errMessageNoPackages)
  83. }
  84. fmt.Fprintf(stderr, "error parsing %s: %s\n", base, err)
  85. return "", nil, err
  86. }
  87. return configPath, &conf, nil
  88. }
  89. func Generate(ctx context.Context, e Env, dir, filename string, stderr io.Writer) (map[string]string, error) {
  90. configPath, conf, err := readConfig(stderr, dir, filename)
  91. if err != nil {
  92. return nil, err
  93. }
  94. base := filepath.Base(configPath)
  95. if err := config.Validate(conf); err != nil {
  96. fmt.Fprintf(stderr, "error validating %s: %s\n", base, err)
  97. return nil, err
  98. }
  99. output := map[string]string{}
  100. errored := false
  101. var pairs []outPair
  102. for _, sql := range conf.SQL {
  103. if sql.Gen.Go != nil {
  104. pairs = append(pairs, outPair{
  105. SQL: sql,
  106. Gen: config.SQLGen{Go: sql.Gen.Go},
  107. })
  108. }
  109. if sql.Gen.Kotlin != nil {
  110. pairs = append(pairs, outPair{
  111. SQL: sql,
  112. Gen: config.SQLGen{Kotlin: sql.Gen.Kotlin},
  113. })
  114. }
  115. if sql.Gen.Python != nil {
  116. if !e.ExperimentalFeatures {
  117. fmt.Fprintf(stderr, "error parsing %s: unknown target langauge \"python\"\n", base)
  118. return nil, fmt.Errorf("unknown target language \"python\"")
  119. }
  120. pairs = append(pairs, outPair{
  121. SQL: sql,
  122. Gen: config.SQLGen{Python: sql.Gen.Python},
  123. })
  124. }
  125. }
  126. for _, sql := range pairs {
  127. combo := config.Combine(*conf, sql.SQL)
  128. // TODO: This feels like a hack that will bite us later
  129. joined := make([]string, 0, len(sql.Schema))
  130. for _, s := range sql.Schema {
  131. joined = append(joined, filepath.Join(dir, s))
  132. }
  133. sql.Schema = joined
  134. joined = make([]string, 0, len(sql.Queries))
  135. for _, q := range sql.Queries {
  136. joined = append(joined, filepath.Join(dir, q))
  137. }
  138. sql.Queries = joined
  139. var name, lang string
  140. parseOpts := opts.Parser{
  141. Debug: debug.Debug,
  142. }
  143. if sql.Gen.Go != nil {
  144. name = combo.Go.Package
  145. lang = "golang"
  146. } else if sql.Gen.Kotlin != nil {
  147. if sql.Engine == config.EnginePostgreSQL {
  148. parseOpts.UsePositionalParameters = true
  149. }
  150. lang = "kotlin"
  151. name = combo.Kotlin.Package
  152. } else if sql.Gen.Python != nil {
  153. lang = "python"
  154. name = combo.Python.Package
  155. }
  156. var packageRegion *trace.Region
  157. if debug.Traced {
  158. packageRegion = trace.StartRegion(ctx, "package")
  159. trace.Logf(ctx, "", "name=%s dir=%s language=%s", name, dir, lang)
  160. }
  161. result, failed := parse(ctx, e, name, dir, sql.SQL, combo, parseOpts, stderr)
  162. if failed {
  163. if packageRegion != nil {
  164. packageRegion.End()
  165. }
  166. errored = true
  167. break
  168. }
  169. var region *trace.Region
  170. if debug.Traced {
  171. region = trace.StartRegion(ctx, "codegen")
  172. }
  173. var files map[string]string
  174. var resp *plugin.CodeGenResponse
  175. var out string
  176. switch {
  177. case sql.Gen.Go != nil:
  178. out = combo.Go.Out
  179. files, err = golang.Generate(result, combo)
  180. case sql.Gen.Kotlin != nil:
  181. out = combo.Kotlin.Out
  182. resp, err = kotlin.Generate(codeGenRequest(result, combo))
  183. case sql.Gen.Python != nil:
  184. out = combo.Python.Out
  185. resp, err = python.Generate(codeGenRequest(result, combo))
  186. default:
  187. panic("missing language backend")
  188. }
  189. if region != nil {
  190. region.End()
  191. }
  192. if resp != nil {
  193. files = map[string]string{}
  194. for _, file := range resp.Files {
  195. files[file.Name] = string(file.Contents)
  196. }
  197. }
  198. if err != nil {
  199. fmt.Fprintf(stderr, "# package %s\n", name)
  200. fmt.Fprintf(stderr, "error generating code: %s\n", err)
  201. errored = true
  202. if packageRegion != nil {
  203. packageRegion.End()
  204. }
  205. continue
  206. }
  207. for n, source := range files {
  208. filename := filepath.Join(dir, out, n)
  209. output[filename] = source
  210. }
  211. if packageRegion != nil {
  212. packageRegion.End()
  213. }
  214. }
  215. if errored {
  216. return nil, fmt.Errorf("errored")
  217. }
  218. return output, nil
  219. }
  220. func parse(ctx context.Context, e Env, name, dir string, sql config.SQL, combo config.CombinedSettings, parserOpts opts.Parser, stderr io.Writer) (*compiler.Result, bool) {
  221. if debug.Traced {
  222. defer trace.StartRegion(ctx, "parse").End()
  223. }
  224. c := compiler.NewCompiler(sql, combo)
  225. if err := c.ParseCatalog(sql.Schema); err != nil {
  226. fmt.Fprintf(stderr, "# package %s\n", name)
  227. if parserErr, ok := err.(*multierr.Error); ok {
  228. for _, fileErr := range parserErr.Errs() {
  229. printFileErr(stderr, dir, fileErr)
  230. }
  231. } else {
  232. fmt.Fprintf(stderr, "error parsing schema: %s\n", err)
  233. }
  234. return nil, true
  235. }
  236. if parserOpts.Debug.DumpCatalog {
  237. debug.Dump(c.Catalog())
  238. }
  239. if err := c.ParseQueries(sql.Queries, parserOpts); err != nil {
  240. fmt.Fprintf(stderr, "# package %s\n", name)
  241. if parserErr, ok := err.(*multierr.Error); ok {
  242. for _, fileErr := range parserErr.Errs() {
  243. printFileErr(stderr, dir, fileErr)
  244. }
  245. } else {
  246. fmt.Fprintf(stderr, "error parsing queries: %s\n", err)
  247. }
  248. return nil, true
  249. }
  250. return c.Result(), false
  251. }