blob: 570e02409d3c61ba88ba75acff4357a9388e23a6 [file] [log] [blame] [view]
Serge Bazanski1b28e1b2022-09-05 18:41:18 +02001Bazel rules for sqlc
2===
3
4This is a set of rules which uses [sqlc](https://github.com/kyleconroy/sqlc) to generate Go code (types and functions) based on a SQL schema/migrations and a list of queries to be turned into functions.
5
Serge Bazanski1b28e1b2022-09-05 18:41:18 +02006Usage
7---
8
9In an empty directory (eg. monogon/foo/bar/model), create:
10
11 - Migration files, eg. `1662395623_foo.up.sql` and `1662395623_foo.down.sql` containing CREATE TABLE and DROP TABLE statements respectively.
12 - A query file, containing SQL queries annotated with function names and return values (see [official docs](https://docs.sqlc.dev/en/stable/tutorials/getting-started-postgresql.html) for a sample `query.sql` file).
13 - A `BUILD.bazel` file containing:
14
15```
16load("@io_bazel_rules_go//go:def.bzl", "go_library")
17load("//build/sqlc:sqlc.bzl", "sqlc_go_library")
18
19sqlc_go_library(
20 name = "sqlc_model",
21 importpath = "source.monogon.dev/foo/bar/model",
22 migrations = [
23 "1662395623_foo.up.sql",
24 "1662395623_foo.down.sql",
25 # More migrations can be created by provising larger timestamp values.
26 ],
27 queries = [
28 "queries.sql",
29 ],
30 dialect = "cockroachdb",
31)
32
33go_library(
34 name = "model",
35 importpath = "source.monogon.dev/foo/bar/model",
36 embed = [":sqlc_model"],
37 deps = [
38 # Might need this for CockroachDB UUID types.
39 "@com_github_google_uuid//:uuid",
40 ],
41)
42```
43
44The built `go_library ` will contain sqlc functions corresponding to queries defined in `queries.sql` and structures corresponding to database tables (and query parameters/results).
45
46To list the generated files for inspection/debugging, `bazel aquery //foo/bar:sqlc_model` and find files named `db.go`, `model.go` and `queries.sql.go` (or similar, depending on how your query file(s) are named).
47
Serge Bazanski9cdec582022-09-15 18:48:27 +020048Migrations
49---
50
51Currently, you need to manually embed the same migrations files using standard //go:embed directives, then you can used them with golang-migrate via en embed.FS/io.FS/iofs-source. See //cloud/apigw/model for an example.