Generate code with SQLC in Bazel - update to Bazel 9
How to use SQLC to generate code in a Bazel >=9 setup. Bazel 9 had some breaking changes regarding the C toolchain that requires some changes to the previously described solution.
As shown in my previous article when using sqlc in a hermetic way - i.e. you want to build sqlc from source instead of relying on some pre-built binary - it requires some adjustments because out of the box, the build will fail.
One of the biggest changes (from what I know so far) in Bazel 9 is that the cc toolchain is now extracted to its own rule (rules_cc).
This means that the previous
cc_library(
name = "include",
hdrs = glob(["include/**"]),
)
does now not work anymore without a corresponding load() statement.
The updated patch now looks like this:
diff --git a/parser/BUILD.bazel b/parser/BUILD.bazel
index b2e972d..00612be 100644
--- parser/BUILD.bazel
+++ parser/BUILD.bazel
@@ -1,4 +1,5 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@rules_cc//cc:cc_library.bzl", "cc_library")
go_library(
name = "parser",
@@ -87,18 +88,24 @@ go_library(
cgo = True,
clinkopts = [""],
copts = [
- "-Iparser/include -Iparser/include/postgres -g -fstack-protector -std=gnu99 -Wno-unknown-warning-option",
+ "-Iexternal/gazelle++go_deps+com_github_pganalyze_pg_query_go_v6/parser/include/ -Iexternal/gazelle++go_deps+com_github_pganalyze_pg_query_go_v6/parser/include/postgres -g -fstack-protector -std=gnu99 -Wno-unknown-warning-option",
] + select({
"@io_bazel_rules_go//go/platform:windows": [
"-Iparser/include/postgres/port/win32",
],
"//conditions:default": [],
}),
+ cdeps = [":include"],
importpath = "github.com/pganalyze/pg_query_go/v6/parser",
importpath_aliases = ["github.com/pganalyze/pg_query_go/parser"],
visibility = ["//visibility:public"],
)
+cc_library(
+ name = "include",
+ hdrs = glob(["include/**"]),
+)
+
alias(
name = "go_default_library",
actual = ":parser",
Furthermore, because rules_cc is now an external rule, you need to declare a dependency to it, in your MODULE.bazel like this:
bazel_dep(name = "rules_cc", version = "<version>")
Make sure to check for the latest version in the Bazel registry!
Now, you should be able again to generate your code with sqlc 🎉