sqlc rules for Bazel
This repository contains rules for Bazel that allow you to compile your SQL files into a Go package that can be used for type-safe database code.
Table of Contents
Setup
The first thing you need to do is load the rules in your WORKSPACE file to make them available in your Bazel repository.
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_plezentek_rules_sqlc",
sha256 = "f75a84af8a907917293f92cd12168e87f30a9f277119ffe90d62edf6e09cbab3",
urls = [
"https://github.com/plezentek/rules_sqlc/releases/download/v0.9.0/rules_sqlc-v0.9.0.tar.gz"
],
)
load("@com_plezentek_rules_sqlc//sqlc:deps.bzl", "sqlc_register_toolchains", "sqlc_rules_dependencies")
sqlc_rules_dependencies()
sqlc_register_toolchains()
Pass in a version to sqlc_register_toolchains
if your code depends on an
older version of the compiler:
sqlc_register_toolchains(version="1.5.0")
If you'd like to use the development version of these rules, you can fetch them
with git_repository
by setting the commit
parameter to a recent commit hash.
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "com_plezentek_rules_sqlc",
commit = "<RECENT_COMMIT>",
remote = "https://github.com/plezentek/rules_sqlc",
)
load("@com_plezentek_rules_sqlc//sqlc:deps.bzl", "sqlc_register_toolchains", "sqlc_rules_dependencies")
sqlc_rules_dependencies()
sqlc_register_toolchains()
Usage
In order to generate a Go package called database
, use the following
sql_package
rule.
load("@com_plezentek_rules_sqlc//sqlc:def.bzl", "sqlc_package")
sqlc_package(
name = "product_database",
package = "database",
queries = ["query.sql"],
schema = ["schema.sql"],
)
You can combine this with rules_go in
order to compile a Go library. Notice how the package
and the importpath
coincide.
load("@com_plezentek_rules_sqlc//sqlc:def.bzl", "sqlc_package")
load("@io_bazel_rules_go//go:def.bzl", "go_library")
sqlc_package(
name = "product_database",
package = "database",
queries = ["query.sql"],
schema = ["schema.sql"],
)
go_library(
name = "product_library",
srcs = [":product_database"],
importpath = "example.com/owner/repo/database",
)
Documentation
Full details on the use of the sqlc_package rule can be found in the rules documentation.
The SQLCRelease
bazel provider (for writers of further bazel rules) can be
found in the provider documentation.