blob: 72d9a867889de450edc12b79e54a4b8cd762effb [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
6It also embeds the migrations using [bindata](https://github.com/kevinburke/go-bindata).
7
8Usage
9---
10
11In an empty directory (eg. monogon/foo/bar/model), create:
12
13 - Migration files, eg. `1662395623_foo.up.sql` and `1662395623_foo.down.sql` containing CREATE TABLE and DROP TABLE statements respectively.
14 - 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).
15 - A `BUILD.bazel` file containing:
16
17```
18load("@io_bazel_rules_go//go:def.bzl", "go_library")
19load("//build/sqlc:sqlc.bzl", "sqlc_go_library")
20
21sqlc_go_library(
22 name = "sqlc_model",
23 importpath = "source.monogon.dev/foo/bar/model",
24 migrations = [
25 "1662395623_foo.up.sql",
26 "1662395623_foo.down.sql",
27 # More migrations can be created by provising larger timestamp values.
28 ],
29 queries = [
30 "queries.sql",
31 ],
32 dialect = "cockroachdb",
33)
34
35go_library(
36 name = "model",
37 importpath = "source.monogon.dev/foo/bar/model",
38 embed = [":sqlc_model"],
39 deps = [
40 # Might need this for CockroachDB UUID types.
41 "@com_github_google_uuid//:uuid",
42 ],
43)
44```
45
46The built `go_library ` will contain sqlc functions corresponding to queries defined in `queries.sql` and structures corresponding to database tables (and query parameters/results).
47
48To 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).
49
50TODO(q3k): document migrations (and probably move them to a subpackage).