Skip to content

A view is a shape

2 / 11 · declaring in the full document · PDF

Everything a view declares is either decoded from the view's own row or loaded by a query of its own. Columns, JSON columns, embedded structs and enums stored in columns come from the row of the root query, each under an alias equal to its path. A to-one reference contributes only its foreign key to the row; the referenced rows, the elements of each collection and each level of a recursive collection are fetched by queries of their own, with the keys of the rows above.

Left: the declaration of TaskView with an id key, a name, a JSON labels column, an embedded Window with prefix due_, an embedded enum State, a to-one assignee, a notes collection ordered by created_at, and a recursive children collection with depth 2; the Window struct and the State enum below it. Right: a zone for one row of task in the $root query holds four boxes: columns id and name and the JSON labels; the embedded struct as due.start and due.end in columns due_start and due_end; the enum, whose state.$tag names the variant and whose state.Blocked.reason is a column; and the reference's key, $ref.assignee. Arrows carry the keys of the rows down to three queries: assignee, a to-one reference; notes, a collection; and children, recursive to depth 2. Along the bottom, what the derive generates for each view: the shape, a decoder per database, an encoder per database, and a comparison for save_changes.

Columns and paths. A field without a relationship attribute is a column of the view's table, named like the field unless column names it; Option<T> is nullable, and a NULL in a non-Option field fails with Error::Decode MPA-VIEW-5. The path of a field is its name joined with . below embedded values, references, collections and variants, such as state.Blocked.reason MPA-CORE-4, and every selected column's alias is its path MPA-PLAN-2. A json field is read and written with serde MPA-VIEW-6.

Embedded values and enums. An embedded struct lives in columns of the containing row, with an optional prefix; embedded values nest and prefixes concatenate MPA-VIEW-7. An enum with data has a tag column naming the variant; its variants' fields are columns of the row by default MPA-SUM-2, or rows of a table per variant MPA-SUM-3. Decoding is strict: a NULL or unknown tag, a missing variant row, or a non-NULL column of another variant is an error unless the enum is lenient MPA-SUM-4.

Relationships. to_one(fk) references another view by the foreign key in this row; an Option reference is None on a NULL key, and a required one whose row is missing fails with Error::MissingReference MPA-VIEW-8. child(fk) is a collection whose rows have fk equal to this row's key, with order_by, a many-to-many through table, an index column, a map key, or recursion with depth or recursive = "cte" MPA-VIEW-9. Invalid attributes are compile errors that name the attribute MPA-VIEW-11.