Expand description
Dialect-agnostic SQL primitives shared by the Postgres (cratestack-sqlx)
and SQLite (cratestack-rusqlite) backends.
This crate carries the type definitions every backend agrees on:
SqlValue/SqlColumnValue— value envelopes used to bind dataCreateModelInput/UpdateModelInput/UpsertModelInput— traits the codegen emitsFilter/FilterExpr/FieldRef— query ASTOrderClause/SortDirection— ordering ASTModelDescriptor/ModelColumn/CreateDefault— schema metadata baked into compiled code byinclude_schema!
Rendering SQL strings, executing queries, and any DB-driver coupling live in the backend crates.
Structs§
- Coalesce
Expr - Left-hand operand of a coalesce-based filter — chain a comparator
method to turn it into a
FilterExpr. - Coalesce
Filter COALESCE(col_a, col_b, ...) <op> <value>— left-hand expression is the first non-null among the listed columns; right-hand side is a bound value via the usualFilterValueenvelope. Lets schemas express the “ranked-fallback compare” pattern that shows up in outbox / scheduler tables, where a single row carries several time columns and the dispatcher wants the earliest non-null one.- Create
Default - Field
Ref - Filter
- Json
Text Path - Left-hand operand of a
json_get_textfilter — chain a comparison method (.eq,.lt,.is_null, …) to produce aFilterExpr. - Model
Column - Model
Descriptor - Order
Catalog - One model’s order-by surface: its own sortable scalar columns
(
(api_name, sql_column)) and its own to-one relation edges. Exactly oneOrderCatalogis emitted per model, regardless of how many distinct relation paths pass through it. - Order
Clause - Order
Relation Edge - One to-one relation edge out of a model.
targetpoints at the related model’s own catalog soresolve_order_targetcan keep walking further segments; to-many relations are never represented here (mirroring the codegen’s existing to-one-only walk), so a key that names one simply fails to resolve. - Orderable
- Marker for a path whose hops are all to-one, so a scalar at the end of it can be rendered as a correlated subquery and used for ordering.
- Postgres
Dialect - Postgres dialect —
$Nplaceholders. - Projection
- Result of a
.select(...)-projected read. Holds the model with only the selected columns populated — non-selected fields carry their type’sDefault::default()value (""forString,0for integers,NoneforOption<T>, etc.). - Relation
Filter - Relation
Hop - One traversed relation edge: the FK linkage plus how the related rows
are quantified (
ToOnefor a plain to-one hop,Some/Every/Nonefor a to-many hop under a quantifier). - Relation
Include - Typed handle for an
.include(...)call on a query builder. Carries everything the runtime needs to issue the side-load query for a to-one relation: a function pointer that extracts the FK value from a parent row, and a static descriptor of the related model. - Resolved
Order Target - A dotted sort key resolved down to the relation hops to traverse plus
the terminal scalar column, ready for
crate::order_value_sql. - Spatial
Point - Builder returned by
crate::pointfor assembling a spatial filter. Holds nothing but the lat/lng pair until a comparator is chained. - SqlColumn
Value - Sqlite
Dialect - SQLite dialect —
?Nplaceholders. - Unorderable
- Marker for a path that has crossed a to-many hop. Ordering accessors are
not implemented for this marker, which reproduces the old guarantee that
asc()/desc()simply did not exist past a to-many relation — a compile error, not a runtime failure. - View
Descriptor
Enums§
- Conflict
Target - Conflict target for an upsert. Defaults to the model’s primary key
(matching the previous PK-only behavior).
Columnslets callers upsert on an arbitrary unique tuple — most commonly a natural key that’s distinct from the PK (e.g.(owner_id, provider)on a per-owner-and-provider settings row, or(pairing_id, slot)on a per-slot envelope). - Create
Default Type - Filter
Expr - Filter
Op - Filter
Value - Json
Filter - JSON / JSONB filter predicates. Two flavors:
- Null
Order - Where NULLs sort relative to non-NULL values. PostgreSQL’s default is
NULLS LASTforASCandNULLS FIRSTforDESC; SQLite’s default isNULLS FIRSTfor both. CrateStack pins the framework default toNULLS LASTso listings stay deterministic across backends and so soft-deleted rows (typedOption<DateTime>that surface asNonefor visible rows) don’t muscle their way to the top of every listing. Override per-clause viaOrderClause::nulls_firstwhen scheduler / outbox queries want fresh-as-null tasks at the head of the queue. - Order
Target - Relation
Quantifier - Sort
Direction - Spatial
Filter - PostGIS spatial filter primitives. v1 ships two ops that cover the “is point inside this zone” / “is this point within radius of that zone” cases — the rest of the ST_* surface can land on demand.
- SqlValue
Traits§
- Create
Model Input - Dialect
- Backend SQL dialect.
- Into
Column Name - Anything that can name a single SQL column. Lets
coalesceaccept both bare&'static strcolumn names and typedFieldRefhandles, so callers don’t have to choose between schema-rooted typing and ad-hoc strings at the call site. - Into
SqlValue - Model
Primary Key - Accessor for a model’s primary key. Implemented by the macro on every
generated model struct so the batch operations can pair returned rows
back to the position of their input PK in the request, producing a
BatchItemResultwith the rightindexand aNotFoundentry for any requested PK that didn’t come back. - Read
Source - Anything a read-path query builder needs to plan and emit SQL.
- Update
Model Input - Upsert
Model Input - Input shape for the upsert primitive —
INSERT … ON CONFLICT (<pk>) DO UPDATE ….sql_values()must include the primary-key column (so the backend can target the conflict), andprimary_key_value()exposes the PK separately so the runtime can issue aSELECT … FOR UPDATEbefore the upsert to driveCreatedvs.Updatedevent / audit semantics. - Write
Source - Anything a write-path query builder needs on top of
ReadSource— create defaults, update / delete policy slots, audit + retention + versioning state, upsert column list, emitted event topics.
Functions§
- coalesce
- Build a
COALESCE(...)left-hand operand. The returnedCoalesceExprcarries the column list; chain a comparator method (.lte,.eq,.is_null, …) to produce aFilterExprthe query builders can consume. - find_
duplicate_ sql_ value - Detect the first duplicate value in a list of
SqlValues, used for batch_upsert input deduplication. Linear-scan withPartialEqrather than the hashed variant incratestack-corebecauseSqlValue::FloatandSqlValue::Decimaldon’t admit a soundHashimpl. - is_
orderable - Whether every hop is to-one. Ordering through a to-many hop is not
expressible as a scalar correlated subquery, so generated
asc()/desc()accessors are gated on this (previously enforced by simply not emitting those methods past a to-many hop). - order_
value_ sql - Build the correlated-subquery expression that yields
columnat the end ofhops, relative to the table reached by the first hop. - point
- Geographic point (WGS-84 lng/lat). The naming follows the PostGIS
ST_MakePoint(x, y)convention —lngis the X axis (longitude),latis the Y axis (latitude). Don’t accidentally swap them; the engine has no way to detect it and your filter will silently match points across the world. - resolve_
order_ target - Walk
key(dot-separated, e.g."author.profile.nickname") throughcatalog, following to-one relation edges one segment at a time and resolving the final segment against the current model’s scalar columns. - wrap_
filter - Fold a scalar
FilterExproutward through the traversed path, applying each hop’s quantifier. Mirrors what the macro previously emitted as nestedFilterExpr::relation*(...)token trees.