Referencia · §8.37

Code from the schema and from queries

nucleus codegen, §M14.16 M5, M6

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

nucleus codegen ts|rust|python|java <db> writes a type per table (not partitions; --tables a,b for some) for that language’s nucleus driver: each column in the type the driver returns its values as, a nullable one optional (| null, Optional[…], Option<…>; Java’s boxed types are null), with the table’s name, the SELECT of its columns in order and a function making the type from a row of it:

TypeScript Python Java Rust
a table interface T + const T @dataclass class T record Schema.T struct T
its query T.select T.SELECT T.SELECT T::SELECT
a row T.fromRow(row) T.from_row(row) T.fromRow(row) T::from_row(row)?
integer, bigint number, number | bigint int Integer, Long i32, i64
numeric nucleus.Decimal decimal.Decimal BigDecimal Value
an enum "a" | "b" Literal["a", "b"] String String
timestamptz Date datetime.datetime OffsetDateTime i64 (µs)
bytea, uuid Uint8Array, string bytes, uuid.UUID byte[], UUID Vec<u8>, [u8; 16]
T[] (T | null)[] List[Optional[T]] List<T> Vec<Option<T>>

(The rest as each driver’s README lists.) A name that is no identifier of the language becomes one ("Two Words" → Two_Words, a reserved word gets _); a type named as one the generated code uses (Value, Date, List, String) gets Row. --out writes a file; --import names the driver (TypeScript’s module, default nucleus-db; Python’s, nucleus; Rust’s crate, nucleus_client); --package is the Java class’s package. The Rust file is a module of its own (#[rustfmt::skip] mod schema; — rustfmt would change what a later run checks against; the file allows dead code).

import { connect } from "nucleus-db";
import { Emp } from "./schema.ts";        // nucleus codegen ts ./mydb --out schema.ts
const db = await connect();
const emps: Emp[] = (await db.query(Emp.select + " WHERE pay > $1", [100])).rows.map(Emp.fromRow);

Code from SQL files (§M14.16 M6, sqlc’s way). --queries <file | dir> (repeatable) reads named queries instead of the tables:

-- name: user_by_email :one
-- A user, by the address they log in with.
SELECT id, email, display_name FROM users WHERE email = $1;

-- name: add_post :exec
-- params: id, author, title, body?
INSERT INTO posts (id, author, title, body) VALUES ($1, $2, $3, $4);

:one returns the first row or none, :many the rows, :exec the count of rows changed; -- lines after the name are the function’s documentation. Each query is parsed (one statement: nothing after a ; ever runs) and described by the database (DESCRIBE, §8.5): its parameters’ types, its columns’ names, types and whether they may be NULL — so a column of a LEFT JOIN’s right side is optional where the same column of an inner join is not. A query that does not check is an error at its place (queries.sql:12:9: syntax error …, or queries.sql:12: user_by_email: column "nope" does not exist); a parameter whose type nothing tells asks for a cast ($1::text). A parameter is named after the column it is compared with, assigned to, inserted into or combined with (email = $1, SET pay = pay + $1, INSERT … (a, b) VALUES ($1, $2)), limit / offset, else p1, …; -- params: a, b? names them itself, ? taking NULL too (otherwise a parameter is not optional). Per query: the SQL as a constant (userByEmailSql, USER_BY_EMAIL_SQL), a row type (UserByEmailRow) and a function taking what runs a statement — TypeScript’s Queryable (a client, a transaction’s, a database in the process), Python’s connection, Java’s NucleusClient, Rust’s &mut Client — and the parameters:

const ann = await userByEmail(db, "[email protected]");   // UserByEmailRow | null
await db.transaction(async (tx) => { await addPost(tx, 1, ann!.id, "Hello", null); });

The sample project, examples/migrations: two migrations, queries.sql, the code generated from them in the four languages (committed) and a program in each that runs it; examples/migrations/run.sh <nucleus> starts a server, applies the migrations, checks that the committed code is what the schema and queries make now (--generate writes it) and runs the programs.

scripts/driver-tests.sh … codegen compiles each language’s code from a schema of every type and from queries over it strictly (tsc --strict, javac -Werror, clippy -D warnings), reads its rows with it, and runs the sample project.

gRPC’s services (§M16.6b P2): nucleus codegen proto <db> [--tables a,b] [--out f] writes nucleus/tables/v1/tables.proto — the tables’ services as the grpc front end serves them and its server reflection describes them (see “gRPC” in §9): a message per table, a field per column numbered as the column (nc_catalog.columns.number). Compiled with any language’s protoc plugin, it is a client for the database’s tables; a column added later is a new field, a column dropped leaves its number unused, so clients compiled before go on working.