Skip to content

Commit

Permalink
multi: add sqlc support
Browse files Browse the repository at this point in the history
sqlc is a tool that generates fully type-safe idiomatic code from SQL.
The result is Go code can then used execute the queries in the database.

The noraml flow looks like:
- The developer write some sql that will update the schema in the
  database: new tables, indices, etc
- The developer updates the set of queries that will use the new schema.
- `sqlc` generates type-safe interfaces to those queries.
- The developer can then write application code that calls the methods
  generated by sqlc.

The tool configuration needs to live in the repo's root and its name is
`sqlc.yaml`.

LND will support out of the box sqlite and postgres. The sql code needs to
be (almost) the same for both engines, so we cannot use custom functions
like `ANY` in postgres.

The SQLC config file needs to define what is the target engine, we will
set postgres but the generated code can be executed by sqlite too.

In some specific cases, we will `match and replace` some sql lines to be
sure the table definitions are valid for the targeted engine.
  • Loading branch information
positiveblue committed Jul 11, 2023
1 parent 287b0ac commit 43a9e2f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,14 @@ list:
grep -v Makefile | \
sort

sqlc:
@$(call print, "Generating sql models and queries in Go")
./scripts/gen_sqlc_docker.sh

sqlc-check: sqlc
@$(call print, "Verifying sql code generation.")
if test -n "$$(git status --porcelain '*.go')"; then echo "SQL models not properly generated!"; git status --porcelain '*.go'; exit 1; fi

rpc:
@$(call print, "Compiling protos.")
cd ./lnrpc; ./gen_protos_docker.sh
Expand Down
19 changes: 19 additions & 0 deletions scripts/gen_sqlc_docker.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/bash

set -e

# Directory of the script file, independent of where it's called from.
DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
# Use the user's cache directories
GOCACHE=`go env GOCACHE`
GOMODCACHE=`go env GOMODCACHE`

echo "Generating sql models and queries in go..."

docker run \
--rm \
--user "$UID:$(id -g)" \
-e UID=$UID \
-v "$DIR/../:/build" \
-w /build \
kjconroy/sqlc:1.18.0 generate
10 changes: 10 additions & 0 deletions sqlc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: "2"
sql:
- engine: "postgresql"
schema: "sqldb/sqlc/migrations"
queries: "sqldb/sqlc/queries"
gen:
go:
out: sqldb/sqlc
package: sqlc
emit_interface: true

0 comments on commit 43a9e2f

Please sign in to comment.