gen-models-macros 0.5.1

Derive macros for Gen persistence models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# 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:

```rust
use gen_models::{Direction, ModelSelect};

#[derive(Debug, PartialEq, ModelSelect)]
#[model_select(table = "samples")]
pub struct Sample {
    #[model_select(primary_key)]
    pub name: String,
    pub is_reference: bool,
}
```

The derive owns the model's table metadata and row decoder, adds `Sample::select(conn)`, and
generates `SampleSelect`:

```rust
let samples = Sample::select(conn)
    .name_contains("foo")
    .is_reference(true)
    .order_by(SampleSelect::Name, Direction::Asc)
    .limit(10)
    .offset(3)
    .load()
    .expect("should load samples");
```

`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 around `Sample::select(conn).load()`.

Every selectable field receives an exact-match method:

```rust
Sample::select(conn).is_reference(true);
```

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:

```rust
Sample::select(conn).name_in(["sample-a", "sample-b"]);
```

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:

```rust
Sample::select(conn).name_contains("reference");
```

Use `_case_insensitive` when the complete string must match while ignoring case:

```rust
Sample::select(conn).name_case_insensitive("REFERENCE");
```

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:

```rust
Sample::select(conn).name_like("ref_%");
```

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`:

```rust
let children = BlockGroup::select(conn)
    .parent_block_group_id(parent_id)
    .load()
    .expect("should load child block groups");

let roots = BlockGroup::select(conn)
    .parent_block_group_id_is_null()
    .load()
    .expect("should load root block groups");
```

## Cacheable foreign keys

Opt a foreign-key field into generated relation accessors by naming its target model and a skipped
runtime cache field:

```rust
use gen_models::{ForeignKeyCache, ModelSelect};

#[derive(ModelSelect)]
#[model_select(table = "annotations", from_row = annotation_from_row)]
struct Annotation {
    #[model_select(foreign_key(Accession, cache = cached_accession))]
    accession_id: HashId,
    #[model_select(skip)]
    cached_accession: ForeignKeyCache<Accession>,
}
```

This generates `get_accession(conn)` and `set_accession(Arc<Accession>)`. The getter returns the
attached object when its `id` still matches the foreign key, otherwise it loads the target by its
`id`; a missing required target is reported as `QueryReturnedNoRows`. An `Option<Id>` foreign key
instead generates a getter and setter using `Option<Arc<Target>>`; a null ID returns `None`, while
a dangling non-null ID remains an error. Foreign-key field names must end in `_id`, the named cache
field must exist, use `#[model_select(skip)]`, and have type `ForeignKeyCache<Target>`; the target
model must expose an `id` field. The target's `id` field is its primary key because the getter loads it with `get_by_id`. A getter
returns a matching cached object or loads and retains a successful database result at runtime;
failed loads are not cached. Cloning a model copies its current cached Arc into an independent cache
cell. The setter updates the in-memory foreign key and cache without writing to the database; it
does not invalidate other model caches.

## 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`.

```rust
let sample = Sample::select(conn)
    .name("sample-a")
    .get()
    .expect("should query sample");
```

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:

```rust
let sample = Sample::select(conn)
    .get_by_id("sample-a")
    .expect("should query sample by primary key");

let samples = Sample::select(conn)
    .query_by_ids(["sample-b", "sample-a", "sample-b"])
    .expect("should query samples by primary key");

let deleted = Sample::select(conn)
    .delete_by_ids(["retired-a", "retired-b"])
    .expect("should delete samples by primary key");
```

`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:

```rust
#[derive(ModelSelect)]
#[model_select(table = "memberships")]
struct Membership {
    #[model_select(primary_key)]
    organization: String,
    #[model_select(primary_key)]
    username: String,
}

let membership = Membership::select(conn)
    .get_by_id(("genhub", "alice"))
    .expect("should query a composite primary key");

let memberships = Membership::select(conn)
    .query_by_ids([("genhub", "alice"), ("genhub", "bob")])
    .expect("should query composite primary keys");
```

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:

```rust
let samples = Sample::all(conn).expect("should load all samples");
```

`Sample::all(conn)` is exactly `Sample::select(conn).load()`. For a historical read, construct the
selector explicitly and call `.with_ref(history_ref).load()`.

Models that need to retain the selected view can declare a runtime-only field:

```rust
#[model_select(history_ref)]
pub history_ref: Option<String>,
```

The field is omitted from SQL columns and starts as `None`; selector loads stamp it with the ref
passed to `.with_ref(...)`. Joined model projections retain the same ref. Generated foreign-key
getters pass their owning model's ref to related selectors, so lazy relation lookups stay in the
view from which the owner was loaded. Models with a custom row decoder should initialize this field
to `None`; the selector fills it after decoding. Keep runtime origin metadata out of serialized and
Cap'n Proto representations.

## 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:

```rust
let names: Vec<String> = Sample::select(conn)
    .name_contains("foo")
    .order_by(SampleSelect::Name, Direction::Asc)
    .only(SampleSelect::Name)
    .load()
    .expect("should load sample names");
```

Pass a tuple of field constants to return typed tuples:

```rust
let samples: Vec<(String, bool)> = Sample::select(conn)
    .order_by(SampleSelect::Name, Direction::Asc)
    .only((SampleSelect::Name, SampleSelect::IsReference))
    .load()
    .expect("should load selected sample fields");
```

Fields may come from both the base selector and joined selectors:

```rust
let rows: Vec<(String, String)> = Sample::select(conn)
    .join_filtered_on(
        SampleSelect::Name,
        BlockGroupSelect::SampleName,
        BlockGroup::select(conn).collection_name("example"),
    )
    .only((SampleSelect::Name, BlockGroupSelect::Name))
    .load()
    .expect("should load fields from both joined models");
```

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:

```rust
let rows: Vec<(Sample, BlockGroup)> = Sample::select(conn)
    .join_filtered_on(
        SampleSelect::Name,
        BlockGroupSelect::SampleName,
        BlockGroup::select(conn).collection_name("example"),
    )
    .models::<(Sample, BlockGroup)>()
    .load()
    .expect("should load both joined models");
```

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. If a model has skipped
fields and no custom `from_row`, those fields are initialized with `Default::default()` in both
direct loads and joined model tuples. A model with a custom `from_row` and skipped fields keeps its
custom construction path and must provide a manual `SelectableModel` implementation to participate
in `.models()`.

## Ordering and pagination

Ordering uses generated field constants, so misspelled or removed column names fail at compile
time:

```rust
let samples = Sample::select(conn)
    .order_by(SampleSelect::Name, Direction::CaseInsensitiveAsc)
    .order_by(SampleSelect::IsReference, Direction::Desc)
    .limit(25)
    .offset(50)
    .load()
    .expect("should load ordered samples");
```

Use `order_by_relevance` to retain ranked search behavior entirely in SQL:

```rust
let names = Collection::select(conn)
    .with_ref(history_ref)
    .name_like(format!("%{search}%"))
    .order_by_relevance(CollectionSelect::Name, search)
    .order_by(CollectionSelect::Name, Direction::Asc)
    .limit(10)
    .only(CollectionSelect::Name)
    .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::Asc`
- `Direction::Desc`
- `Direction::CaseInsensitiveAsc`
- `Direction::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:

```rust
#[derive(ModelSelect)]
#[model_select(
    table = "memberships",
    default_sort(username = "asc", organization = "desc")
)]
struct Membership {
    #[model_select(primary_key)]
    organization: String,
    #[model_select(primary_key)]
    username: String,
}
```

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.

```rust
let historical_samples = Sample::select(conn)
    .with_ref("main~1")
    .name_contains("foo")
    .load()
    .expect("should load historical samples");
```

`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:

```rust
let samples = Sample::select(conn)
    .with_ref(history_ref)
    .load()
    .expect("should load samples at the optional history ref");
```

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:

```rust
let samples = Sample::select(conn)
    .name_contains("sample")
    .join_on(SampleSelect::Name, BlockGroupSelect::SampleName)
    .order_by(SampleSelect::Name, Direction::Asc)
    .load()
    .expect("should load joined samples");
```

`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:

```rust
let samples = Sample::select(conn)
    .join_filtered_on(
        SampleSelect::Name,
        BlockGroupSelect::SampleName,
        BlockGroup::select(conn).collection_name("example"),
    )
    .load()
    .expect("should load samples in the collection");
```

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:

```rust
let paths = Path::select(conn)
    .collection_name("example")
    .sample_name("reference")
    .load()
    .expect("should load joined paths");
```

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 `limit` and `offset` unset; 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:

```rust,ignore
use gen_models::ModelSelectError;

fn matching_samples(conn: &Connection) -> Result<Vec<Sample>, ModelSelectError> {
    Sample::select(conn).name_contains("foo").load()
}
```

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:

```rust
#[derive(ModelSelect)]
#[model_select(table = "examples")]
pub struct Example {
    #[model_select(primary_key)]
    #[model_select(column = "display_name")]
    pub name: String,

    #[model_select(skip)]
    pub derived_value: String,
}
```

The derive also accepts advanced struct-level options:

```rust,ignore
#[derive(ModelSelect)]
#[model_select(
    table = "samples",
    alias = "sample_rows",
    source = sample_source,
    select = "sample_rows.name, sample_rows.is_reference"
)]
pub struct Sample {
    pub name: String,
    pub is_reference: bool,
}
```

- `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 = false` disables historical reads. If omitted, historical reads use the configured
  table name.
- `#[model_select(history_ref)]` marks an `Option<String>` model field that records the selector's
  history ref at runtime. It is excluded from SQL columns and is not persisted. Custom row decoders
  should initialize it to `None`; the selector fills it after decoding.
- `from_row = path::to::function` supplies a `fn(&Row) -> rusqlite::Result<Model>` for models that
  need custom row decoding. Without `from_row`, skipped fields are initialized with
  `Default::default()`; with it, the custom decoder must construct every skipped field. The derive
  reads selectable fields by their configured SQL column names.
- `alias = "..."` sets the SQL alias used to qualify generated columns. Aliases and field-level
  `column` values are single SQL identifiers; generated SQL always double-quotes them and treats
  punctuation such as `.` as part of the identifier.
- `source = path::to::function` supplies a `fn(Option<&str>) -> String` that renders the `FROM`
  source. 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:

```rust,ignore
fn example_from_row(row: &gen_models::select::Row) -> gen_models::select::SqlResult<Example> {
    let name: String = row.get("name")?;
    Ok(Example {
        uppercase_name: name.to_uppercase(),
        name,
    })
}

#[derive(ModelSelect)]
#[model_select(
    table = "examples",
    history = false,
    from_row = example_from_row
)]
pub struct Example {
    pub name: String,
    #[model_select(skip)]
    pub uppercase_name: String,
}
```

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`:

1. Accepts a non-generic struct with named fields.
2. Reads the model and field-level `model_select` attributes.
3. Generates private model metadata and row decoding from `table`, `history`, and `from_row`.
4. Generates the selector struct, typed field constants, filter methods, and `SelectQuery`
   implementation.
5. Generates `Model::select(conn)`, `Model::all(conn)`, selector `get()`, and selector
   `get_by_id(...)`, `query_by_ids(...)`, and `delete_by_ids(...)` when a primary key is available.

At runtime, [`gen-models::select`](../gen-models/src/select.rs):

1. Stores generated filters, ordering, joins, pagination, and the optional history ref.
2. Builds requested join conditions from typed field constants supplied by the caller.
3. Quotes every structured table, alias, and column identifier, then renders one `SELECT` statement
   for the base model and its joined sources.
4. Fallibly converts and binds every runtime value through `rusqlite`; list filters use `rarray`
   relations to retain input order and avoid interpolating placeholder lists.
5. 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_on` call 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.
- `only` supports projections of one through 16 fields from selected and joined models.
- `models` supports generated decoders for skipped fields that implement `Default`. Models with
  skipped fields and a custom `from_row` need a manual `SelectableModel` implementation to join.
- Generated code references `gen_models`, so downstream consumers should use the macro through the
  `gen-models` crate under its standard crate name.