| Serge Bazanski | 1b28e1b | 2022-09-05 18:41:18 +0200 | [diff] [blame] | 1 | Bazel rules for sqlc |
| 2 | === |
| 3 | |
| 4 | This 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 Bazanski | 1b28e1b | 2022-09-05 18:41:18 +0200 | [diff] [blame] | 6 | Usage |
| 7 | --- |
| 8 | |
| 9 | In 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 | ``` |
| 16 | load("@io_bazel_rules_go//go:def.bzl", "go_library") |
| 17 | load("//build/sqlc:sqlc.bzl", "sqlc_go_library") |
| 18 | |
| 19 | sqlc_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 | |
| 33 | go_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 | |
| 44 | The 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 | |
| 46 | To 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 Bazanski | 9cdec58 | 2022-09-15 18:48:27 +0200 | [diff] [blame] | 48 | Migrations |
| 49 | --- |
| 50 | |
| 51 | Currently, 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. |