Checked SQL
You write queries as SQL. A generator checks each one against the real, migrated schema and writes typed code: a function per query and a row type per result. The generated code is committed, so ordinary builds need no database; a check step fails the build when the committed code is stale. It is the approach of sqlc and of sqlx’s offline mode.
You get: a misspelled column or a wrong type is a build error, parameters and results are typed, and the SQL you read is the SQL that runs.
The Java and Go toolchains differ (a Maven plugin and its own generator for Java; sqlc and go-jet,
driven by a small framework tool, for Go) but keep the same promise. The normative rules are in the
checked SQL specification. Queries that cannot be static (optional
filters, variable IN lists) are written by hand, see Dynamic queries.
The workflow
Section titled “The workflow”- Put queries in
src/main/sql/<package path>/<ClassName>.sql. The path belowsrc/main/sqlis the Java package, the file name the generated class. - Run the generator (Docker running, or an empty database given by
FW_SQL_DATABASE_URL). - Commit
src/main/java-generated/. ./mvnw verifyrunscheckand fails, naming the files, if the committed code is stale.
- Put queries in
.sqlfiles with sqlc’s-- name: X :oneheaders and@nameparameters (go/examples/orders-demo/sql/orders.sql). - Run the framework’s tool:
go run ./tools/fwsql generate. - Commit the generated code and the
.fw/schemadirectory. - CI runs
go run ./tools/fwsql check, which fails when anything is stale.
Setting up
Section titled “Setting up”Add the plugin to your pom.xml (from examples/orders-demo/pom.xml; the version is your
framework.version):
<plugin> <groupId>io.flowcatalyst.framework</groupId> <artifactId>framework-sql-maven-plugin</artifactId> <version>${framework.version}</version> <configuration> <migrations> <migration> <moduleId>outbox</moduleId> <location>db/migration/outbox</location> </migration> <migration> <moduleId>orders</moduleId> <location>db/migration/orders</location> </migration> </migrations> </configuration> <executions> <execution> <id>add-generated-source</id> <goals> <goal>add-source</goal> </goals> </execution> <execution> <id>check-sql</id> <goals> <goal>check</goal> </goals> </execution> </executions></plugin><migrations> lists the migration sets to apply to the scratch database, in order, as the application
applies them: each is a module id plus a classpath location. The framework modules’ sets are on your
dependency classpath; your own src/main/resources is searched too.
| Goal | Phase | What it does |
|---|---|---|
generate |
generate-sources |
starts a throwaway PostgreSQL (Testcontainers postgres:18-alpine), or uses the empty database at FW_SQL_DATABASE_URL; applies the migration sets with the framework’s own runner; describes every query without executing it; writes the sources; removes committed generated files (recognised by their header) whose query file is gone |
check |
verify |
does the same in memory, writes nothing, and fails if any generated file differs from the committed one, is missing, or has no source. Lists the files |
add-source |
generate-sources |
adds src/main/java-generated to the compile source roots. A build that only compiles the committed code needs this |
check needs Docker (or a database) too. As configured above it is bound to verify, so a plain
./mvnw verify starts a container. -Dfw.sql.skip=true skips a goal, but it skips all three,
including add-source: the committed generated sources are then no longer on the compile path and the
build will not compile. To make check optional, bind it in a profile instead of in the main
<executions> and leave add-source bound always.
Parameters (all optional): fw.sql.sqlDirectory, fw.sql.outputDirectory, fw.sql.databaseUrl,
fw.sql.databaseUser, fw.sql.databasePassword, fw.sql.image (default postgres:18-alpine),
fw.sql.skip. The environment variables FW_SQL_DATABASE_URL, FW_SQL_DATABASE_USER (default
postgres) and FW_SQL_DATABASE_PASSWORD are used when the properties are not set. The database must
be empty.
Regenerating
Section titled “Regenerating”./mvnw io.flowcatalyst.framework:framework-sql-maven-plugin:generateor bind generate in a profile, as the example does:
<profile> <id>generate-sql</id> <build> <plugins> <plugin> <groupId>io.flowcatalyst.framework</groupId> <artifactId>framework-sql-maven-plugin</artifactId> <executions> <execution> <id>generate-sql</id> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build></profile>./mvnw -Pgenerate-sql -DskipTests packageCommit the result.
sqlc.yaml follows the platform’s style (pgx/v5, pointers for nullable types, db tags) and names typed
ids per column; a type alias of a generic id works as the override type:
- column: orders.id go_type: { import: "github.com/flowcatalyst/framework/go/examples/orders-demo/domain", type: OrderID }Only the application knows its migration sets, so it wires the framework’s tool in a few lines
(tools/fwsql/main.go):
os.Exit(sqlfw.Main(context.Background(), os.Args[1:], sqlfw.Config{ Sets: []fw.MigrationSet{ {Module: usecase.OutboxModuleID, Files: usecase.OutboxMigrations()}, sqlfw.MigrationDir("orders", "orders/migrations"), // by path: the command needs no application code }, Jet: &sqlfw.JetConfig{Dir: "internal/jet"},}))The application’s own sets are named with sqlfw.MigrationDir(module, dir): read from the directory by
path, relative to Config.Dir (a missing directory fails naming the set and the path). The command
then imports no application package, so it compiles before the queries generated from a set exist: the
first generate of a new package needs no stub. The directory holds the files the package embeds; the
module id must be the one the package declares. The framework’s own sets are imported as before.
| Command | What it does |
|---|---|
schema |
writes every set, in apply order, flat into .fw/schema (00_outbox__V000001__create_outbox_messages.sql; versions are zero-padded because sqlc reads the directory in lexical order and only one level deep), which sqlc.yaml’s schema: names |
generate |
writes the schema, runs sqlc generate (static, no database) and generates the go-jet table code from a PostgreSQL 18 migrated by the framework’s own runner |
check |
for CI: fails, one line per problem, when the schema directory, the sqlc code (sqlc diff) or the jet code is stale, or when a query does not prepare against the migrated database (sqlc vet with the sqlc/db-prepare rule; sqlc’s own analysis already catches an unknown column, prepare catches what it misses, such as lower(bigint)) |
The database is an embedded PostgreSQL 18, or the empty one at FW_SQL_DATABASE_URL. sqlc v1.31.1
must be on PATH.
A query file
Section titled “A query file”From examples/orders-demo/src/main/sql/.../OrderSql.sql:
-- name: findHeader :one-- The order's root row, for its client only.-- param: id io.flowcatalyst.framework.examples.ordersdemo.OrderId-- param: client_id io.flowcatalyst.framework.context.ClientId-- column: status enum io.flowcatalyst.framework.examples.ordersdemo.OrderStatusSELECT version, customer, status FROM orders WHERE id = :id AND client_id = :client_id;
-- name: updateOrder :exec-- The optimistic-locking write: the row count says whether the version still matched.-- param: id io.flowcatalyst.framework.examples.ordersdemo.OrderId-- param: client_id io.flowcatalyst.framework.context.ClientId-- param: status enum io.flowcatalyst.framework.examples.ordersdemo.OrderStatusUPDATE orders SET version = :new_version, customer = :customer, status = :status WHERE id = :id AND client_id = :client_id AND version = :version;- A query starts at a
-- name: <javaName> <kind>line and runs to the next.javaNameis a lower-camel identifier, unique in the file. - Kinds:
:onereturnsOptional<Row>(more than one row at run time throwsIllegalStateException),:manyreturnsList<Row>,:execreturns the affected row count asint. - Parameters are
:snake_name; the Java parameter is its lower-camel form (:new_versionbecomesnewVersion), in order of first appearance. A name used twice is one parameter.::(a PostgreSQL cast), and:nameinside a string literal, quoted identifier, dollar-quoted string or comment, are not parameters. A literal?is an error (write the jsonb?operator asjsonb_exists()), as is a second statement; one trailing;is dropped. - Comment lines between the
-- name:line and the SQL are the generated method’s Javadoc, except-- param:and-- column:lines, which are declarations.
sqlc’s own syntax applies: -- name: X :one (or :many, :exec, …) and @name parameters. See
go/examples/orders-demo/sql/orders.sql and the sqlc documentation for the
full set of query annotations. The generated functions take a database.DB or Tx-compatible handle,
and typed ids per column come from the sqlc.yaml overrides above.
Types and nullability
Section titled “Types and nullability”| PostgreSQL | Java |
|---|---|
text, varchar, char |
String |
int2, int4 |
int |
int8 |
long |
bool |
boolean |
numeric |
BigDecimal |
float4, float8 |
float, double |
timestamptz |
Instant |
timestamp |
LocalDateTime |
date |
LocalDate |
uuid |
UUID |
bytea |
byte[] |
json, jsonb |
String (the JSON text) |
| one-dimensional arrays of the above | List<T> |
Any other type fails generation, naming the query and column.
Nullability.
- A result column read directly from a table column declared
NOT NULLis non-null. Every other column (expressions, aggregates) is nullable: its type is boxed and@Nullable. - The database cannot say that an outer-joined table’s column may be null, so in a query whose text
contains
LEFT,RIGHTorFULL JOIN, every column is nullable unless overridden. - Override with
AS "total!"(non-null; only when the query guarantees it:COALESCE,count(*),RETURNINGaNOT NULLcolumn) orAS "note?"(nullable). A!is checked at run time: a null there throwsIllegalStateExceptionnaming the query and column. - Parameters are non-null by default;
-- param: <name> ?declares one nullable.
Typed values and enums. Map a column or parameter to your own type:
-- param: id com.acme.OrderIdorAS "id: com.acme.OrderId". The type must be a record with exactly one component namedvalue, of the Java type the column maps to (record OrderId(String value)). The generated code callsnew X(...)andx.value().enum com.acme.OrderStatusstores the enum as itsname()in a text column; the generated code callsvalueOfandname().- Overrides combine:
AS "col?: com.acme.X". Typed values do not apply to arrays.
PostgreSQL cuts an identifier at 63 bytes and a fully qualified type name often exceeds that. So every
alias override can instead be a -- column: line: -- column: status ! enum com.acme.OrderStatus
(-- column: <name> [!|?] [enum] [<type>]). Mix the two across columns, but override a column in one
place only. The generator refuses an alias of 63 bytes or more that contains a : and names the
-- column: line as the fix. The generator never loads your classes; javac checks the generated
calls when the project compiles.
Types come from sqlc, configured in sqlc.yaml (pointers for nullable columns, typed ids by column
override).
sqlc’s nullability. Columns of an outer-joined table are nullable to sqlc (pointers), even those
declared NOT NULL. But a column with a type override keeps its non-pointer type even when it comes
from the outer-joined table (a NULL then fails to scan), and an expression with a cast is typed
non-null although it can be NULL (min(l.sku)::text over an order without lines). sqlc is less strict
than the Java generator here, where every column of an outer-joined query is nullable unless
overridden. Write such columns so they cannot be NULL (coalesce(min(l.sku), '')::text), as the
demo’s Summaries query does, or cast an overridden column to text and parse it in the repository.
The generated code
Section titled “The generated code”For OrderSql.sql, one public final class OrderSql in the matching package, with:
- a
recordper:oneand:manyquery for its row (FindHeaderRow), components in select order; - one static method per query taking a
java.sql.Connectionfirst (a use case’sTxand aDatabaseboth give one), then the parameters; - the SQL text as it is executed,
public static final String FIND_HEADER_SQL, with a comment giving the file and line; - the query’s comment lines as Javadoc.
try (Connection c = db.dataSource().getConnection()) { Optional<FindHeaderRow> header = OrderSql.findHeader(c, id, client); ...}Output is deterministic: same input, same bytes. Do not edit it; it carries a
// Generated from <file>. Do not edit. header.
sqlc writes the typed functions and row structs; go-jet writes table definitions for building dynamic
statements (below). Both are committed, and check fails when either is stale. Do not edit them.
Dynamic queries
Section titled “Dynamic queries”Optional filters and variable IN lists cannot be a static query, so they stay hand-written.
Use the Jdbc helper from the write path module: see Reading
for its methods and the parameter types it binds. Multi-statement queries, COPY and MySQL are out of
scope.
The orders read model writes the same list query two ways and one test runs every filter combination
against both. go-jet builds the statement from the generated table code (a renamed column fails to
compile); pgx runs and scans it through sqlfw.Query, never jet’s own mapper:
stmt := pg.SELECT(o.ID.AS("id"), o.Customer.AS("customer"), o.Status.AS("status")). FROM(o). WHERE(cond). ORDER_BY(o.ID.DESC()). LIMIT(int64(q.Size)). OFFSET(int64(q.offset()))return sqlfw.Query(ctx, r.DB, stmt, pgx.RowToStructByName[OrderRow])database.Filter needs no dependency; its column names are strings, so the test is what checks
them:
var f database.Filterf.Eq("client_id", cx.Client().String())if q.Status != nil { f.Eq("status", *q.Status)}if q.Search != "" { f.Clause("customer LIKE $%d", "%"+escapeLike(q.Search)+"%")}Values are always bound in both.
Errors
Section titled “Errors”Errors name the file and the line of the query’s -- name: line: SQL syntax or an unknown column (the
database’s message), an unsupported type, a parameter used with two types, or a wrong override. All
queries are described first and then every failure is reported, one line each.