gen-models-macros
gen-models-macros provides the ModelSelect derive used by gen-models to create typed,
fluent SQLite selectors for persisted models. It replaces handwritten query-parameter structs and
string-based ordering with methods and field constants generated from the model itself.
This crate is intended to be used through gen-models, which re-exports ModelSelect and provides
the runtime selector implementation.
Basic usage
Derive ModelSelect on a named-field struct and provide its table name:
use ;
The derive owns the model's table metadata and row decoder, adds Sample::select(conn), and
generates SampleSelect:
let samples = select
.name_contains
.is_reference
.order_by
.limit
.offset
.load
.expect;
load() returns Result<Vec<Sample>, ModelSelectError>. Filter values, history refs, limits, and
offsets are passed to SQLite as bound parameters rather than interpolated into SQL.
Generated API
For a model named Sample, the derive generates:
SampleSelect<'conn>, the fluent query builder.- Typed field constants such as
SampleSelect::Name. Each constant carries its model, SQL column, and Rust value type. Sample::select(conn), the preferred selector constructor.Sample::all(conn), a convenience wrapper aroundSample::select(conn).load().
Every selectable field receives an exact-match method:
select.is_reference;
Every selectable field also receives an _in method for matching any value from a typed
iterator. The result follows the values' first-occurrence order, repeated input values are
deduplicated, and empty iterators match no rows:
select.name_in;
An empty iterator renders an explicit 0 = 1 predicate. This preserves empty-set semantics while
avoiding invalid IN () SQL; omitting the filter instead would incorrectly match every row.
List values are bound through SQLite's rarray virtual table. Each list uses one array parameter
per selected column, so long lists do not consume one SQLite parameter per value. The renderer
counts those array parameters together with scalar filters, history refs, and pagination; a query
that exceeds the connection's variable limit returns ModelSelectError::InvalidSelector before
SQLite executes it.
String fields also receive a case-insensitive _contains method:
select.name_contains;
Use _case_insensitive when the complete string must match while ignoring case:
select.name_case_insensitive;
Exact, multi-value, contains, and case-insensitive values are bound SQL parameters. In
particular, % and _ in user input are ordinary characters rather than LIKE wildcards.
Use _like when the input is a SQL pattern:
select.name_like;
Patterns are bound parameters and preserve % (any sequence) and _ (one character).
_like uses the connection's native LIKE case behavior. _contains remains a literal
substring match. Nullable string fields receive _like too; SQL NULL values do not match.
Option<T> fields receive an _is_null method in addition to an exact-match method that accepts
T:
let children = select
.parent_block_group_id
.load
.expect;
let roots = select
.parent_block_group_id_is_null
.load
.expect;
Loading one model or all models
Use get when a selector must match at most one model. It returns
Result<Option<Model>, ModelSelectError>: None means no row matched, while multiple matches
produce ModelSelectError::MultipleResults.
let sample = select
.name
.get
.expect;
The derive infers a field named id as a single-column primary key. Mark every field in an
explicit primary key with #[model_select(primary_key)]; this generates get_by_id,
query_by_ids, and delete_by_ids on the selector:
let sample = select
.get_by_id
.expect;
let samples = select
.query_by_ids
.expect;
let deleted = select
.delete_by_ids
.expect;
query_by_ids has the same ordered and deduplicated behavior as the generated _in filter.
delete_by_ids returns the number of affected rows, quotes the generated table and primary-key
identifiers, and chunks large inputs. It must be called on a fresh selector because filters,
joins, ordering, pagination, and historical refs do not define writable row sets.
For a composite primary key, the methods accept tuples in field declaration order and match each
tuple as one key rather than combining independent IN filters:
let membership = select
.get_by_id
.expect;
let memberships = select
.query_by_ids
.expect;
Skipped fields cannot be primary keys. Models without an id field or an explicit primary_key
attribute receive none of these primary-key convenience methods.
To load every current model, use the generated convenience method:
let samples = all.expect;
Sample::all(conn) is exactly Sample::select(conn).load(). For a historical read, construct the
selector explicitly and call .with_ref(history_ref).load().
Selecting specific fields
Call only after configuring the query to return selected fields instead of complete models. A
single field returns that field's Rust type:
let names: = select
.name_contains
.order_by
.only
.load
.expect;
Pass a tuple of field constants to return typed tuples:
let samples: = select
.order_by
.only
.load
.expect;
Fields may come from both the base selector and joined selectors:
let rows: = select
.join_filtered_on
.only
.load
.expect;
The field constants determine the return type and preserve the order of values in each tuple. Use
a one-element tuple such as (SampleSelect::Name,) when a Vec<(String,)> is preferable to a
Vec<String>.
only is the terminal query-shaping step: apply filters, joins, ordering, limits, and offsets
before it, then call load. A projection can contain up to 16 fields. Every projected field's
model must be the base selector or one of its joins.
Selecting complete joined models
Call models with a tuple of model types to return complete models from both sides of a join:
let rows: = select
.join_filtered_on
.
.load
.expect;
The tuple order determines both the SQL column order and the returned tuple order. Every model must
be the base selector or one of its joins. Like field projections, model tuples support one through
16 entries. Write a one-element tuple such as .models::<(Sample,)>() when needed.
The derive generates an offset-aware, fallible row decoder for this API. A model containing a
#[model_select(skip)] field does not receive that decoder because a complete value cannot be
constructed from the selected columns.
Ordering and pagination
Ordering uses generated field constants, so misspelled or removed column names fail at compile time:
let samples = select
.order_by
.order_by
.limit
.offset
.load
.expect;
Use order_by_relevance to retain ranked search behavior entirely in SQL:
let names = select
.with_ref
.name_like
.order_by_relevance
.order_by
.limit
.only
.load?;
The typed field must belong to the selector and have type String or Option<String>.
Ranking uses CASE WHEN field = ? THEN 0 WHEN lower(field) = lower(?) THEN 1 WHEN field LIKE ? || '%' THEN 2 WHEN field LIKE '%' || ? || '%' THEN 3 ELSE 4 END.
Case-sensitive exact equality ranks first under the usual column collation, followed by
case-insensitive exact equality using SQL lower (ASCII by default, without a promise of
Unicode case folding). Prefix and contains use native SQL LIKE behavior. Search
values are bound and their % and _ characters remain wildcards in the LIKE branches.
Relevance only orders; use the matching _like filter to exclude unrelated rows. Unmatched
rows, including NULL, receive rank 4 from ELSE and sort after all matched rows.
Relevance and field ordering are appended in call order and replace the default sort. Chain
field ordering for deterministic ties. A joined selector carries its relevance ordering into
join_filtered_on, including all bound search values. Historical reads and projections use
the same SQL ordering before LIMIT/OFFSET. Existing _in filters retain their input-order
precedence ahead of explicit ordering, including relevance.
Available directions are:
Direction::AscDirection::DescDirection::CaseInsensitiveAscDirection::CaseInsensitiveDesc
Configure deterministic ordering beside the table name with default_sort. Entries are applied in
the order written, regardless of model field declaration order, and an explicit .order_by(...)
replaces the complete default:
The accepted values are "asc", "desc", "case_insensitive_asc", and
"case_insensitive_desc". The example sorts by username first and uses organization as its
descending tie-breaker.
An offset without an explicit limit is supported; the runtime renderer emits SQLite's unlimited
LIMIT -1 form before the offset.
Historical queries
Use with_ref to read a Dolt history ref. Omitting with_ref reads the current working state.
let historical_samples = select
.with_ref
.name_contains
.load
.expect;
with_ref also accepts Option<T> when T can be converted into a string. This lets callers
forward an optional ref without branching; None retains the current working state:
let samples = select
.with_ref
.load
.expect;
For the default source, a historical query reads dolt_at_<table>(:history_ref). When selectors
are joined, the same history ref is applied to every source. If both selectors specify refs, they
must be equal.
Tables support historical reads by default. Set #[model_select(history = false)] on models for
ordinary SQLite tables that do not have a Dolt history table; those models cannot use with_ref.
Joins
Selectors join on two generated field constants, so the relationship is checked by Rust and does not require a foreign-key metadata query:
let samples = select
.name_contains
.join_on
.order_by
.load
.expect;
join_on constructs an unfiltered selector for the model carried by its right-hand field. Use
join_filtered_on to carry another selector's filters and ordering into the query:
let samples = select
.join_filtered_on
.load
.expect;
Calling load directly on either joined selector returns instances of the selector on the left,
so these queries return Vec<Sample>. Use only for typed fields from either side of the join, or
models for complete joined models.
The join fields must have the same generated join type. Nullable columns normalize Option<T> to
T for this check, so an optional foreign key can join its non-null primary key; incompatible
types such as String and i64 fail to compile. Compatible fields are rendered as one quoted
equality, such as "samples"."name" = "block_groups"."sample_name". Repeating an identical join
reuses its insertion-ordered entry and combines the filters. Reusing one alias with a different
source or condition is rejected.
A helper can hide a common relationship while retaining model-specific filter syntax:
let paths = select
.collection_name
.sample_name
.load
.expect;
Joined selectors must:
- Use the same database connection.
- Use the same historical ref, when explicitly set on both selectors.
- Use a consistent source and condition when reusing a source alias.
- Leave
limitandoffsetunset; apply pagination to the outer selector after the join.
Violating these requirements, or joining from a field whose source has not been selected, records
a selector-construction error. The next load(), get(), or projection load returns that error.
Error handling
load() and get() return ModelSelectError for selector construction, unsupported historical
queries, database preparation, query execution, row decoding, result-row iteration, and
projections that refer to a model that was not selected or joined.
get() additionally returns ModelSelectError::MultipleResults when the selector matches more
than one model. Callers can propagate these errors directly:
use ModelSelectError;
Selector construction errors, such as joining from an unselected model, combining different
connections, or reusing an alias with a different condition, are deferred so fluent builder
methods remain concise and are returned as ModelSelectError::InvalidSelector at execution.
Using with_ref when any selected source has history = false returns
ModelSelectError::HistoryNotSupported.
Configuration attributes
Fields use their Rust field name as the SQL column name by default. Override or omit a generated
field with model_select attributes:
The derive also accepts advanced struct-level options:
table = "..."is required and supplies the selector's table metadata.default_sort(field = "direction", ...)configures the selector's default ordering. Entry order defines sort precedence, and each entry names a selectable Rust model field.history = falsedisables historical reads. If omitted, historical reads use the configured table name.from_row = path::to::functionsupplies afn(&Row) -> rusqlite::Result<Model>for models that need custom row decoding. This is required when any field usesskip; otherwise the derive reads every field by its configured SQL column name.alias = "..."sets the SQL alias used to qualify generated columns. Aliases and field-levelcolumnvalues are single SQL identifiers; generated SQL always double-quotes them and treats punctuation such as.as part of the identifier.source = path::to::functionsupplies afn(Option<&str>) -> Stringthat renders theFROMsource. Its SQL must expose the configured alias and honor the optional history ref when needed.select = "..."replaces the default<alias>.*select list. Its result must still match the generated or custom row decoder.
For example, a model with a non-persisted field can supply its construction explicitly:
Every derived model must provide table. A view over another model's table should name that table
and use alias, source, select, or from_row when its source or decoding differs.
source and select are trusted, compile-time raw SQL escape hatches rather than identifiers, as
are clauses passed directly to SqlFilter::new. Their authors are responsible for quoting every
identifier and binding runtime values. They must never be populated from runtime input.
How it works
The implementation is split between compile-time generation and runtime execution.
At compile time, ModelSelect:
- Accepts a non-generic struct with named fields.
- Reads the model and field-level
model_selectattributes. - Generates private model metadata and row decoding from
table,history, andfrom_row. - Generates the selector struct, typed field constants, filter methods, and
SelectQueryimplementation. - Generates
Model::select(conn),Model::all(conn), selectorget(), and selectorget_by_id(...),query_by_ids(...), anddelete_by_ids(...)when a primary key is available.
At runtime, gen-models::select:
- Stores generated filters, ordering, joins, pagination, and the optional history ref.
- Builds requested join conditions from typed field constants supplied by the caller.
- Quotes every structured table, alias, and column identifier, then renders one
SELECTstatement for the base model and its joined sources. - Fallibly converts and binds every runtime value through
rusqlite; list filters userarrayrelations to retain input order and avoid interpolating placeholder lists. - Maps full base-model loads through the generated or custom fallible row decoder, or typed field and model projections through fallible decoders generated for their selected types.
The renderer names its synthetic rarray relations with an indexed __model_select_* prefix.
The prefix distinguishes renderer-owned aliases from model aliases during SQL review, and the
indexes keep multiple IN filters and composite-key columns distinct within one statement.
The runtime support cannot live in this proc-macro crate. A proc-macro executes inside the compiler and can export procedural macros, but it cannot export the normal reusable runtime types needed by all generated selectors. It also has no access to the query's live database connection. Keeping the SQL renderer in ordinary Rust provides one implementation that can be tested and reviewed without expanding every derive.
Current limitations
- Only structs with named fields are supported.
- Generic model structs are not supported.
- At least one field must remain selectable after applying
skip. - Each
join_oncall expresses one equality; composite join conditions are not yet supported. - A source alias can only refer to one source and join condition in a query.
onlysupports projections of one through 16 fields from selected and joined models.modelssupports tuples of one through 16 selected and joined models without skipped fields.- Generated code references
gen_models, so downstream consumers should use the macro through thegen-modelscrate under its standard crate name.