Skip to content

About

Typed Sqlite SQL generator for Rust

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

252 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Marmot

Marmot analyzes SQL against SQLite and generates typed Rust database code. It also owns the migration, seed, reset, schema-dump, and declarative-view tooling used by repository applications.

The architecture decision index governs its design. The Rust SQLite benchmark is dated supporting evidence, not a current performance guarantee.

The goal is to keep Marmot's source layout:

src/items.rs
src/items.sql
src/registrations/index.rs
src/registrations/index.sql
src/orders.rs
src/orders.sql

and generate direct database code from those colocated SQL files.

The first target is Rust + rusqlite. The useful end state is a shared analyzer with multiple emitters:

SQL files + SQLite schema
        |
        v
query model
        |
        +-- Rust / rusqlite
        +-- Gleam / sqlight

Public boundary

Marmot's supported boundary is the CLI plus the public modules and re-exports in src/lib.rs. Applications provide SQL files, SQLite schema, and marmot.toml; generated Rust and schema dumps are derived output.

Marmot:

  • finds module companion SQL files like src/items.rs plus src/items.sql
  • supports multiple -- func: blocks per companion SQL file
  • derives generated function names from -- func: blocks
  • derives generated module paths from the companion SQL path
  • extracts named parameters like @org_id
  • prepares each statement with SQLite and records result columns
  • infers common parameter and result types from schema metadata, expressions, casts, joins, returning clauses, and insert/update positions
  • emits typed direct rusqlite functions using prepare_cached (see Statement cache size)
  • requires immutable connections for reads and stronger mutation-capable connections for writes
  • lowers source-level SQL parameters to dense positional binds in generated Rust
  • runs forward-only SQL migrations, seed files, and database resets through marmot::migrations, marmot::seeds, and marmot::reset, with bounded planner-statistics optimization after schema-changing workflows
  • owns declarative SQLite views under src/db_views and reconciles them after migrations
  • supports named database references for multi-database projects
  • can enforce configured temporal suffixes and generate checked Rust date/datetime boundary types for those columns

Unsupported SQL shapes fail analysis rather than silently generating an untyped runtime fallback.

Table rebuild migrations

Use a rebuild only when SQLite can't make the change in place. DROP COLUMN and RENAME COLUMN don't need one, and neither does a type or constraint change made by adding a new column, backfilling it and dropping the old one. A column's own named Boolean CHECK doesn't block dropping it.

Put -- marmot: rebuild-table on its own line in a numbered migration that replaces a referenced table. Marmot disables foreign-key enforcement before starting that migration's transaction, checks all foreign keys before commit, and restores the prior setting. The table copy, replacement and migration tracking record commit together. A SQL error or invalid relationship rolls them back.

Keep table copies and explicit insert columns in the migration. Preserve unrelated columns, indexes, triggers and dependent rows. A rebuild cannot run inside a caller-owned transaction or an atomic seed workflow. For a complete release batch, use migrate_connection_atomically with the application validation callback. It disables foreign keys before beginning only when a pending migration needs a rebuild, runs every pending migration and validation in one transaction, and checks all foreign keys before commit. A failure or dry run rolls back the whole batch. Foreign keys are enabled again on return. Rebuild SQL must not contain transaction-control statements; Marmot owns the transaction boundary. Ordinary batches keep foreign-key enforcement enabled.

Implementation navigation

  • src/analyzer.rs, src/sqlite/, and src/model.rs build the language-neutral query model.
  • src/emit/ generates target code.
  • src/config.rs and src/main.rs own configuration and the CLI.
  • src/migrations.rs, src/seeds.rs, src/reset.rs, src/schema.rs, and src/views.rs own database lifecycle tooling.

Declared types are semantic input

Marmot uses SQLite declared types to build its language-neutral query model. In particular, BOOLEAN and BOOL generate Boolean parameters and result fields even though SQLite stores those values as integers.

SQLite STRICT tables reject BOOLEAN and BOOL. To preserve explicit Boolean semantics with an allowed integer storage type, name the column's canonical 0/1 check constraint boolean:

CREATE TABLE settings (
  enabled INTEGER NOT NULL
    CONSTRAINT boolean CHECK (enabled IN (0, 1))
) STRICT;

Marmot generates enabled as bool. The same named constraint works on ordinary non-strict tables. The marker must be a column-level constraint on an INT or INTEGER column, and its check must use the exact shape CHECK (column IN (0, 1)). Marmot rejects malformed markers during analysis.

An unnamed 0/1 check remains an integer because that shape can represent an index, numeric flag, or two-value domain type. Marmot does not infer Boolean semantics from values, column names, defaults, or unnamed constraints. See ADR 0003.

Usage

Run the Cargo examples from the standalone Marmot repository root. In a Cargo workspace, select the package with cargo run -p marmot -- instead. An installed binary accepts the same arguments after marmot.

Inspect discovered queries:

cargo run -- inspect --database path/to/app.db --source-root path/to/src

Project defaults can live in marmot.toml:

[tools.marmot]
database = "path/to/app.db"
source_root = "path/to/src"
output = "path/to/src/generated/sql"   # shared generated artifacts
init_sql = "db/marmot_init.sql"
migrations_dir = "db/migrations"
bootstrap_dir = "db/bootstrap"
seeds_dir = "db/seeds"
migration_table = "schema_versions"
schema_output = "db/schema.sql"

Use another config path with --config path/to/marmot.toml. CLI flags override config values.

output names the shared output folder, not the place query bindings go. Marmot writes each query file's bindings beside the SQL (see Generated bindings). The shared folder holds disposable views.sql, the temporal module and its fixed declaration when configured, and value_sets.rs when the owner declares column value sets, and scoped_ids.rs when the owner defines scoped IDs.

Multi-database projects can use named references:

[tools.marmot.databases.app]
path = "db/app.sqlite"
source_root = "src/app"
output = "src/app/generated/sql"
init_sql = "db/app_marmot_init.sql"
migrations_dir = "db/migrations/app"
seeds_dir = "db/seeds/app"

[tools.marmot.databases.analytics]
path = "db/analytics.sqlite"
source_root = "src/analytics"
output = "src/analytics/generated/sql"
migrations_dir = "db/migrations/analytics"
seeds_dir = "db/seeds/analytics"

Pass --database-name app to target one named database. Without it, generate, migrate, seed, and reset run every named database in sorted name order. Ambient DATABASE_URL does not replace named database paths in that mode. Named references can omit paths; Marmot derives db/NAME.sqlite, src/NAME, src/NAME/generated/sql (the shared output folder), db/migrations/NAME, and db/seeds/NAME.

Temporal Suffixes

Temporal suffix enforcement is opt-in:

[tools.marmot.temporal]
strict_suffixes = true
datetime_suffixes = ["_at"]
date_suffixes = ["_on"]
datetime_storage = "text_second_utc"
date_storage = "text_ymd"
module = "crate::generated::sql::temporal"
output = "src/generated/sql/temporal.rs"

module is the absolute path every generated file imports temporal types from. It is required when any query uses a temporal type. output is optional. When you set it, Marmot writes the temporal module there, directly inside the shared output folder and named after the module's last segment, and writes a fixed mod.rs beside it that declares only pub mod temporal; (the file holds a single newline when no query uses temporal types). Marmot keeps that file current on every run and removes it only when you drop output. Only one owner can hold the module: a target whose shared folder isn't the configured one and that uses no temporal types emits nothing temporal. When you omit output, your project supplies the module: Marmot emits neither the temporal module nor the declaration, and bindings import module as written.

Set emit_without_queries = true for a dedicated temporal owner, including one with no SQL files. This requires both module and output. The owner still needs its configured local database for analysis. It publishes the module and its declaration inside its own shared output folder, with the same stale-file cleanup, fingerprint cache and --check validation as query owners. Other owners import its module by setting module and omitting output.

With strict_suffixes = true, columns ending in a configured datetime suffix must be declared as TEXT and generate temporal::DbDateTime. Columns ending in a configured date suffix must be declared as TEXT and generate temporal::DbDate.

If stored text does not match the configured temporal format, generated row decoding includes the generated field name, bad value, and expected format in the error. The original rusqlite conversion error remains in the error source chain.

The storage keys are explicit because they are part of the project contract, but they are not a menu of equally supported backends yet. The only supported values today are:

  • datetime_storage = "text_second_utc" for YYYY-MM-DD HH:MM:SS UTC datetime text, optionally followed by a decimal point and 1 through 9 fractional-second digits. Decoding retains the original precision.
  • date_storage = "text_ymd" for YYYY-MM-DD date text

Unknown storage values are rejected.

init_sql is optional setup for Marmot's analysis connection. Marmot runs the file after opening SQLite and before reading schema metadata or preparing query blocks. Named databases inherit [tools.marmot].init_sql unless they set their own init_sql. The --init-sql PATH CLI option overrides both defaults and named targets. Packaged applications can supply their analysis declarations without a development configuration file.

Warning: init_sql is an escape hatch. Marmot does not sandbox it, roll it back, or check whether it mutates schema or data. It is not a migration system, and it only runs during inspect and generate, not when your application starts. Use it for setup the analyzer needs, such as ATTACH, temporary tables, PRAGMAs, or native SQLite extension loading when your SQLite build and driver support it.

An application-owned Rust SQLite scalar function can be declared to Marmot in init_sql with -- marmot: scalar FUNCTION_NAME ARITY. Marmot registers a prepare-only stub on its analysis connection, so SQLite can prepare the queries. Reset and view audit also read these declarations to prepare views. Their validation connections do not execute other statements from init_sql. A stub returns an error if a query tries to execute it; it cannot supply a value to seed or application data. Register the real function on every application connection. Cast function results when they appear in selected columns, because the stub does not define a result type.

For a deterministic application function, add the optional suffix: -- marmot: scalar FUNCTION_NAME ARITY deterministic. This lets Marmot prepare expression-index schemas and create an index on an empty table. The stub still rejects execution, so reset or migration cannot use it to populate that index.

Generate Rust files:

cargo run -- generate \
  --database path/to/app.db \
  --source-root path/to/src

A companion SQL file contains named blocks:

-- func: get_item_by_id
select id, name from items where id = @id;

-- func: list_items
select id, name from items order by name;

Allowlisted update columns

SQLite parameters can bind values, but they cannot bind column names. For the rare update whose target column is selected at runtime, declare the complete allowlist in the function block:

-- func: update_user_field
-- columns: display_name, email
update users
set {{column}} = @value,
    updated_at = @now
where id = @id;

Marmot verifies that every choice is a real column on the updated table, quotes each identifier, prepares every resulting statement during analysis, and generates a closed UpdateUserFieldColumn Rust enum. The marker must be the complete left side of a direct {{column}} = @value assignment. Only one column allowlist and marker are allowed per function. A long allowlist can continue on another -- columns: directive:

-- columns: first_name, last_name, email
-- columns: phone, city, country, postal_code

@column is reserved because generated parameter structs use column for the selector enum. Marmot rejects that collision during analysis. Reusing another named parameter is allowed and follows SQLite's normal single-binding behavior.

When every allowed column has a compatible type, @value keeps that inferred type. If the columns have incompatible types, only @value falls back to rusqlite::types::Value; the column remains a closed enum. This feature does not substitute table names, clauses, expressions, ordering, or arbitrary SQL fragments.

Read and mutation connections

Marmot asks SQLite whether each prepared statement is read-only. Read statements generate functions that accept &Connection. Anything SQLite reports as a write, including INSERT, UPDATE, DELETE, write statements with RETURNING, and DDL, generates a function that accepts impl MutationConnection.

marmot::MutationConnection is one shared sealed trait implemented for &mut Connection and &Transaction. This means an immutable &Connection cannot call generated mutation SQL:

let mut conn = rusqlite::Connection::open("app.sqlite")?;
queries::create_item(&mut conn, "Stone")?;

let tx = conn.transaction()?;
queries::create_item(&tx, "Broom")?;
tx.commit()?;

Existing callers must make standalone write connections mutable and pass &mut conn. Callers already inside a transaction should pass &transaction. Read calls stay unchanged. Marmot rejects multi-statement query blocks, so each generated function has one SQLite access classification.

Mutation bindings import the shared trait, so add marmot as an application dependency alongside rusqlite.

Scalar cardinality

A single-column query emits a list function by default. Add -- cardinality: one to emit only its _one function, or -- cardinality: both when callers need both forms:

-- func: item_count
-- cardinality: one
select count(*) from items;

-- cardinality: many explicitly selects the default list form. These annotations require exactly one result column. They also work on single-column mutations with RETURNING; those functions retain the mutation-connection requirement. The annotation selects generated functions without changing SQL or result handling. _one still uses query_row, including its error when no row is returned.

Prepared mutation batches

Add -- batch inside a parameterized mutation block to emit its _batch helper:

-- func: insert_item
-- batch
insert into items (name) values (@name);

The ordinary function remains available. The batch helper prepares the statement once and executes it for each parameter struct in the supplied slice, using the caller's connection or transaction. It does not create or commit a transaction. Unannotated blocks emit only the ordinary function. Batch annotations are rejected on reads, statements without parameters, column substitutions and statements with RETURNING.

Statement cache size

Generated functions call prepare_cached, so they reuse compiled statements from rusqlite's per-connection cache. That cache holds 16 statements by default and evicts the least recently used one when it fills. Raise it on every connection you pass to generated code:

let conn = rusqlite::Connection::open("app.sqlite")?;
conn.set_prepared_statement_cache_capacity(4096);

Size it above the number of distinct statements a connection runs, not the number one request runs. A pooled connection serves every route over time, so its working set is every hot statement in the app. Count distinct SQL texts, including allowlisted column variants and handwritten statements that share the connection.

A cache smaller than the working set can repeatedly evict statements. Measure your workload before choosing a capacity; compiled statements consume memory on each connection.

Statement labels

Pass --statement-labels to generate to start each generated SQL constant with a comment naming its source: /* marmot:<path>#<function> */. The path is the companion .sql file as the config sees it (the configured source_root joined with the module path), and the function is the -- func: name. SQLite returns that text from sqlite3_sql, so a trace or profile hook can attribute every statement without a runtime registry. The flag is off by default, and generate --check must be given the same flag to compare against labelled bindings.

Generated bindings

Marmot writes each companion file's bindings beside it, as NAME.generated.rs with an // @generated by Marmot from NAME.sql header:

src/items.sql                       -> src/items.generated.rs
src/registrations/index.sql         -> src/registrations/index.generated.rs
src/registrations/form.sql          -> src/registrations/form.generated.rs

Each -- func: block in one companion file becomes a function in that file. There is no central query tree and no per-query override. Don't edit generated files; Marmot overwrites them.

The Rust compiler never loads a file nothing declares, so the module that owns the SQL declares its bindings:

// src/items.rs
#[path = "items.generated.rs"]
mod sql;

Keep the declaration private. If the compiler reports a caller outside the module, widen that one declaration to pub(crate) mod sql; instead of moving code. The name after mod is yours; check only requires exactly one declaration per discovered query, pointing at an existing file. Rust resolves #[path] relative to the declaring file's directory. Inside an inline mod tests { ... }, it resolves relative to the nested directory instead (and a file that isn't mod.rs, lib.rs or main.rs adds its own name first), so mod tests { #[path = "../../items.generated.rs"] mod sql; } in src/items.rs loads the same file. A declaration under #[cfg(...)], on the module itself or on an enclosing inline module such as #[cfg(test)] mod tests, doesn't count, because non-test builds wouldn't load it.

Generation stages every changed file first and then publishes directory by directory. If publishing any step fails, Marmot restores the files it already replaced, so the prior complete output survives; if restoration also fails, the error names the retained backup folder. Unchanged files are never touched, so they keep their bytes and modification times, and repeated generation changes nothing. Stale *.generated.rs files whose NAME.sql is gone are removed, as is any Rust file left in the shared output folder (so keep output a dedicated folder below source_root; Marmot rejects output equal to source_root). The guarantee covers returned I/O errors. A process killed mid-publish (SIGKILL, power loss) can leave a partly published tree and a .marmot-publish-* folder next to the source root; rerun generate to repair it. Concurrent readers can briefly see a file missing or a mixed tree while publishing (each replacement is two renames).

Check generated files without writing:

cargo run -- generate \
  --database path/to/app.db \
  --source-root path/to/src \
  --check

--check compares the bindings and configured shared artifacts against what generation would write and touches no generated or source file: no bytes, no modification times, no staging folder. It still opens the analysis database and, like generate, applies init_sql and reconciles views there, so point it at a disposable or development database. It reports every problem with the owning file and the fix, for example:

src/items.sql has no owner declaration for src/items.generated.rs; add `#[path = "items.generated.rs"] mod sql;` to src/items.rs
orphan generated file src/old.generated.rs has no matching .sql file; delete it and remove its declaration in src/old.rs
generated file is stale: src/registrations/form.generated.rs; run generate

It also reports a duplicate declaration, a declaration whose file doesn't exist, and an orphan *.generated.rs.

Migrating to adjacent bindings

If you generated into a central tree, such as src/generated/sql/items.rs:

  1. Add module (and output if Marmot should keep emitting the temporal module) to [tools.marmot.temporal]. Drop any --output override that meant "where bindings go".
  2. Run marmot generate. It writes NAME.generated.rs beside each SQL file and deletes the old central files under the shared output folder.
  3. In each owner module, declare its bindings with #[path = "NAME.generated.rs"] mod sql;.
  4. Replace crate::generated::sql::items::... callers with sql::... from the owner, or widen the declaration to pub(crate) for callers outside it.
  5. Run marmot generate --check until it passes.

Database validation

Validate a configured database without changing it:

marmot validate

Routine validation runs SQLite quick_check, checks foreign keys, audits Marmot-owned views, and compares the migration tracking table with configured migration files. Use the full SQLite integrity check for restore drills and scheduled maintenance:

marmot validate --full

The report also identifies the bundled SQLite version, compile options, and whether planner statistics exist. Planner statistics are informational because some healthy databases have not needed ANALYZE.

Automation can request the stable versioned JSON shape:

marmot validate --json

The top-level object contains format_version and databases. Each database contains its path, required checks, and SQLite runtime information. A failed or incomplete required check returns a non-zero exit status in both output modes. Validation opens the database read-only and does not checkpoint WAL, repair data, reconcile views, create statistics, or apply migrations.

Declarative views

A companion package that shares an application database can set [tools.marmot].view_source_root to the schema owner's source directory. inspect and generate reconcile and audit views from that directory while SQL companion discovery and generated bindings stay under source_root. Generated views.sql contains only declarations owned by source_root, so referencing another view owner doesn't copy its declarations into the package. The default view source is each target's resolved source_root. Paths use the command's working directory. Keep migrate, reset and audit-views with the schema owner; this analysis setting doesn't change their source selection.

Put reusable, permanent SQLite views in src/db_views. Each view has one file, and its filename must match the physical view name:

-- src/db_views/view_active_memberships.sql
CREATE VIEW view_active_memberships (participant_id, season_started_in) AS
SELECT participant_id, season_started_in
FROM line_items
WHERE status IN ('submitted', 'paid');

View names use lowercase view_ prefixes. The declaration requires an explicit output column list because those names are the view's public contract. A file contains one native CREATE VIEW statement, and the SQL view name must match the filename. The directory and filename convention identifies declarative view code, so no Marmot annotation is required. Parameters are not supported.

inspect and generate install the declarations before Marmot analyzes queries that consume them. generate also writes the disposable aggregate views.sql in the shared output folder (src/generated/sql/views.sql here). generate --check verifies that aggregate and fails if the database contains a managed view_* without a declaration.

migrate reconciles declared views after forward migrations. reset reconciles them after migrations and before seeds, so seed SQL can read declared views. Both commands accept --source-root; without it they use marmot.toml or src. Pass --deny-view-warnings in deployment checks to reject stale managed views. When schema_output is configured, both commands write the deterministic schema dump after the database lifecycle succeeds.

Marmot replaces the complete declared view set transactionally. It drops every declared view, creates every current definition, then prepares a zero-row query against each one. That final preparation catches missing dependencies, cycles, and incompatible output contracts. A failure rolls back to the previous view set.

Removing a source file does not drop the installed view. Add an explicit forward migration with DROP VIEW IF EXISTS, then run the audit:

cargo run -- audit-views --database path/to/app.db --source-root path/to/src
cargo run -- audit-views --database path/to/app.db --source-root path/to/src --deny-warnings

The audit prints copyable migration SQL for database-only view_* objects. It never executes that removal itself.

SQLite exposes declared types for direct view columns and explicit casts, so Marmot can retain those generated types. SQLite does not preserve useful NOT NULL metadata through a view, and an uncast expression may have no declared type. Marmot handles those cases conservatively: view results are nullable, and untyped expressions generate rusqlite::types::Value. Use CAST in the view definition when an expression needs a stable generated type.

Run migrations:

cargo run -- migrate \
  --database path/to/app.db \
  --migrations-dir db/migrations

Run seeds:

cargo run -- seed \
  --database path/to/app.db \
  --seeds-dir db/seeds

Production-safe bootstrap data is separate from development and test fixtures:

cargo run -- bootstrap \
  --database path/to/app.db \
  --bootstrap-dir db/bootstrap

bootstrap_dir is optional. Reset runs it before seeds_dir when configured. Seed and bootstrap filenames use lowercase letters, digits, and underscores. Unlike migrations, they do not need a numeric prefix because Marmot reruns every file in lexical filename order.

Reset a database, then run migrations and seeds:

cargo run -- reset \
  --database path/to/app.db \
  --migrations-dir db/migrations \
  --seeds-dir db/seeds

Write the database schema in deterministic object order, or verify that a committed dump is current:

cargo run -- dump-schema --database path/to/app.db --output db/schema.sql
cargo run -- dump-schema --database path/to/app.db --output db/schema.sql --check

The dump contains schema only. It has no timestamps or migration data, so a reset does not manufacture history-only diffs.

Design Notes

The generator should emit boring concrete code. Runtime speed should come from staying close to hand-written rusqlite: cached prepared statements, positional parameter binds, positional row access, concrete row structs, and no dynamic mapper layer. SQL files can use named parameters for readability, but generated runtime SQL lowers them to dense positional slots so SQLite does not do a name lookup on every call.

SQLx's SQLite analyzer is useful reference material for closing inference gaps. In particular:

  • declared SQLite type mapping
  • statement description
  • result-column nullability
  • fallback inference from EXPLAIN
  • offline metadata shape

Marmot should borrow ideas carefully, and only copy code when there is a clear reason and the license notice is preserved. SQLx should not be part of generated runtime code.

Generation cache

marmot generate skips an owner only when its inputs and published output bytes match the last successful run. generate --force always regenerates. generate --check always performs analysis and checks binding declarations; it neither reads nor writes the cache.

The input fingerprint includes:

  • Effective target configuration after CLI and environment overrides, temporal settings, serialization settings, and the selected config file's bytes.
  • Discovered companion SQL paths and bytes, and their adjacent Rust module paths. Rust module contents are checked by --check; editing a function body alone does not require SQL generation.
  • View SQL membership and bytes under both source_root/db_views and view_source_root/db_views, including when those roots differ.
  • Migration and configured bootstrap SQL membership and bytes, and init_sql.
  • The running executable's SHA-256, covering generator and dependency changes even without a version bump.
  • The database file's birth time and, on Unix, device and inode, plus ordered SQLite schema definitions. A reset with identical schema still invalidates the cache. Filesystems without birth-time support run generation in full.

Receipts live in .local/marmot/ beside each source root. Their filenames identify the existing source, database and output paths by digest. Keep this folder ignored and local to the checkout. From that source root's parent, clear the cache with rm -rf .local/marmot.

Receipts include hashes of adjacent bindings and managed shared output. Missing, modified or obsolete output triggers normal generation and repair. Marmot's own output never enters its input fingerprint. Missing or corrupt receipts cause a full run; cache I/O failure leaves generation usable. Receipts are published only after all selected targets succeed, and only when their non-schema inputs stayed unchanged through generation. Schema changes made by view reconciliation are recorded after the successful run. Schema dumps remain owned by database lifecycle commands.

Receipt publication verifies the schema snapshot used for analysis as well as source inputs. Analysis reconciles views first, then reads schema and query facts inside one SQLite read transaction. If an in-place schema change occurs after analysis, that run publishes no receipt for its old bindings; the next run regenerates. analyzer::analyze_project_snapshot returns the analyzed project and its schema identity for callers that need this guarantee.

Column value sets

Put value_sets.toml in a generator owner's source_root to bind a closed Rust enum to exact TEXT columns:

module = "crate::value_sets"

[sets.NoticeStatus]
values = ["draft", "published"]
columns = ["notices.status"]

Marmot writes value_sets.rs in the configured shared output folder. Declare it at the configured Rust path, for example:

#[path = "generated/sql/value_sets.rs"]
pub mod value_sets;

Generated params and results use NoticeStatus, with Option where nullable. Enums implement ToSql, FromSql and as_str. Unknown stored text fails the read with its original value in the error. Adding a value adds a variant, so exhaustive matches must be updated. Deleting the declaration removes the generated file on the next generation; remove its Rust module declaration too.

SQL validation follows the declared column through aliases, joins, named params, comparisons, IN, CASE and direct INSERT/UPDATE values. It rejects invalid literals and conflicting parameter types. Expressions that transform a declared value without preserving its identity fail generation; return the column and transform it in Rust. JSON_OBJECT, JSON_ARRAY and JSON_GROUP_ARRAY can pack validated arguments into SQLite text, including through CAST to TEXT. Their existing generated result representation stays unchanged and never becomes an enum. Each compound SELECT arm is validated with its own table bindings; enum result positions and parameters must agree across arms. Declared-column compounds require explicit projections. A single INSERT SELECT source can assign a valid literal, a typed parameter or a same-set column to a declared target. Transformed assignments, compound INSERT SELECT into declared targets and scalar-subquery enum results remain unsupported. Other owners adopt the same columns by importing the home registry from their own source_root/value_sets.toml:

imports = ["../../domain_core/src/value_sets.toml"]

Paths are relative to the importing source root. A shared home uses its crate-named module path, such as domain_core::value_sets, and exposes that module publicly. Importers use its enums without generating copies. They may also declare their own sets; only local sets generate a module. Imports name home registries directly: imported registries must declare sets and cannot import others. Missing homes, duplicate set names or duplicate column bindings fail generation. Imported registries participate in generation freshness checks. Owners without imports or declarations and raw SQL writers remain responsible for their own inputs.

A set may add rust_attributes = ['#[derive(serde::Serialize)]', '#[serde(rename_all = "snake_case")]'] to place those attributes on its generated enum. Each string must contain exactly one valid outer Rust attribute. The owner supplies the dependencies and checks attribute meaning and feature selection by compiling its crate. Defaults add no dependencies or output. This lets an island contract re-export the home enum while keeping its serialization, TypeScript and schema traits. Verify the wire contract when adding attributes.

Each set can also configure Rust emission:

[sets.NoticeStatus.rust]
visibility = "pub(crate)"
as_str_visibility = "pub(crate)"
emission = "always"

Visibility defaults to pub; as_str_visibility defaults to the enum's visibility and cannot exceed it. emission defaults to always; test wraps output in #[cfg(test)], and none emits no Rust items. All modes validate SQL. Generated bindings require always. Shared imported types must remain public.

Before adopting an existing column, trace its writers and stored vocabulary. Replace the superseded handwritten enum and string comparisons in the same change. ADR 0009 defines ownership, read failures and import constraints. No SQLite constraint or table rebuild is needed.

Scoped IDs

A gate can produce an ID that child queries require. Declare its type in the consuming domain owner's source_root/scoped_ids.toml:

module = "domain_core::scoped_ids"

[ids.ScopedOrderId]
gates = ["../../checkout/src/orders.sql#get_order"]

The gate's companion SQL names the produced result column:

-- func: get_order
-- produces: id = domain_core::scoped_ids::ScopedOrderId
SELECT id, status FROM orders
WHERE org_id = @org_id AND user_id = @user_id AND id = @order_id;

A child query names the parameter that requires that proof:

-- func: list_items
-- consumes: order_id = domain_core::scoped_ids::ScopedOrderId
SELECT id, name FROM line_items WHERE order_id = @order_id;

Other owners import the home registry with their own source-root scoped_ids.toml, using paths relative to that source root:

imports = ["../../domain_core/src/scoped_ids.toml"]

The home owner declares the generated module at its configured Rust path:

extern crate self as domain_core;
#[path = "generated/sql/scoped_ids.rs"]
pub mod scoped_ids;

Marmot generates one type and the registered gates' execution helpers in the home owner's shared output. Gate-owner bindings delegate to those helpers and map the returned rows. Multiple gates can produce the same type. A helper always runs its registered SQL; no public raw constructor or FromSql implementation exists. Each registered SQL file must have its Rust companion.

Pass the returned ID to child params. Other params keep their ordinary types. A raw i64 doesn't compile. The token borrows the connection, and child bindings reject a token from another connection. Keep gates and children in the same synchronous database operation; the token cannot escape to an async task or outlive that connection. Use .get() when an existing separately scoped read or response field needs the raw value.

Production requires a nonnullable INTEGER result from an ordinary read-only gate. A producing gate establishes its own authorization and cannot consume a scoped ID. Home registries are imported directly; transitive imports are not supported. An unknown type, missing registered producer, mismatched directive or invalid parameter fails generation. The registry, imported homes and gate SQL participate in generation freshness checks.

For deliberate cross-tenant SQL, -- unscoped: <reason> records a nonempty reason and cannot coexist with scope directives. It doesn't change SQL or waive authorization. Queries without directives retain their existing types and output. ADR 0010 defines the visibility and lifetime boundary.

SQL plan inspection and migration checks

marmot check-migrations db/migrations replays numbered migrations in memory. It checks the final schema's Boolean markers and rejects CHECK constraints outside those markers. Triggers require the nearest ancestor marmot.toml to list them in structural_triggers; triggers containing RAISE are rejected. The command reads scalar declarations but does not run configured initialization SQL, seeds or bootstrap data, or open the configured application database. Duplicate migration numbers fail discovery.

marmot check-plans inspects raw companion SQL using EXPLAIN rather than executing application statements. It requires a single configured database, source_root, a schema dump (--schema or schema_output) and a JSON policy:

cargo run -- check-plans --policy db/plan-policy.json --schema db/schema.sql --report plan-report.json

A minimal policy is {"version":1,"fixed_tables":{},"exceptions":[]}. Fixed-table entries map table names to explanations for their bounded size. Reports identify scans of growing tables, temporary sorts, unresolved reads and growing output. Exceptions bind a statement to its source and plan hashes, owner, reason, follow-up and exact findings. Inspect query_plan_policy::Policy and Report for the serialized contract. These are static plan findings, not timings or proof of production performance.

Use --baseline FILE --capture-initial-baseline for an explicit first baseline, then --baseline FILE to check it and --ratchet to record accepted reductions. --baseline-base FILE also checks that the baseline has not grown relative to a prior version. Repeated --owner-config PATH selects companion roots whose configured database and scalar declarations match the check configuration.

marmot changed-statements --base REV --owner-config marmot.toml inventories raw SQL changes between a committed base and HEAD. --repo-root and --platform-root default to the current directory. Repeat --owner-config for multiple owners; --before-owner-config supplies the prior owner registry when it differs. Use this inventory to choose statements for application-owned measurement. Marmot does not execute a request workload or enforce runtime statement budgets.

About

Typed Sqlite SQL generator for Rust

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages