The table block
The table block declares one table of the application: its columns, how a row is shown, the
rules every write must obey, the scripts that run on a write, its states, and the changes to it
that destroy data.
table events "Events" { display: title scope: season
title text required "Title" season ref(seasons) required "Season" starts_at datetime required "Starts" ends_at datetime "Ends" kind enum(open "Open", limited "Limited") required "Kind" capacity int "Capacity" { min: 1 } status lifecycle published_at datetime "Published at"
check ends_at >= starts_at "The end must not be before the start." require capacity when kind = limited "A limited event needs a capacity." unique(title, starts_at) "An event with this title already exists at that time."
after insert -> logic/event-created.ts
lifecycle status "Status" { state draft default "Draft" state published public "Published" state cancelled gone "Cancelled"
transition publish draft -> published "Publish" { access: board set published_at = now when published_at is empty } transition cancel draft, published -> cancelled "Cancel" { access: board deny when starts_at < now "An event that has started cannot be cancelled." after -> logic/event-cancelled.ts } }}The scope: line needs an application scope on the table seasons, and the access: lines need
a role board. The two scripts must exist in logic/. Each line in this example has a section
below.
table <name> "<Label>" { <columns, properties and statements>}By convention, the tables of an application are in schema.mtd, in the root directory of the
application. An application can spread its tables over several files.
The name is an identifier in snake_case, such as events or fee_groups. It cannot contain
a dot or a hyphen. The engine stores the table as <app>__<name>, so table events in
app sports_club is sports_club__events. Pages, rules and references name the table by its
name only.
The compiler refuses these names:
| Name | Reason |
|---|---|
a name that starts with mtd_ or edg_, in any case |
the engine keeps its own tables in these namespaces. See Reserved table names. |
a name that another table block of the application already has |
the message names the line of the first declaration |
The label is optional. Today the engine shows it in one place: the corner cell of a
matrix whose rows are this table. With no label, the matrix shows
the name.
Columns
Section titled “Columns”Every line in the body that is not a property or a statement is a column:
capacity int "Capacity" { min: 1 }A column line is a name, a type, modifiers, an optional label and an optional block of
properties, in that order. The types, the modifiers and the properties are on
Column types. A column can have the same name as a keyword of this page.
For example, check text "Check" is a column, because a type follows the name.
The engine adds five columns to every table. You cannot declare them:
id, the primary key. The engine writes it.created_at,created_by,updated_atandupdated_by. The engine writes them on every write.
The compiler refuses a column with one of these names. It also refuses two columns that need the
same stored name, for example a column photo_mime beside an img column photo.
The properties and statements can be in any order, and between the columns. A property can be written once per block.
display
Section titled “display”display: last_name, first_namedisplay: names the columns that show a row wherever another row refers to it: a ref cell in a
report, the options of a select, a CSV export and a row lookup. The engine joins the values with
, and leaves out the empty ones. So display: last_name, first_name shows Miller, Anna.
Show a reference by its name
Section titled “Show a reference by its name”A ref column in a display shows the display of the row it refers to, not its id. That display
can name a ref too:
table enrolments "Enrolments" { display: student student ref(students) required "Student" course ref(courses) required "Course"}
table marks "Marks" { display: enrolment, assessment enrolment ref(enrolments) required "Enrolment" assessment ref(assessments) required "Assessment"}A mark shows Miller, Anna, Exam 2: the enrolment shows its student, and the student shows
last_name, first_name. A display can follow at most four references.
The engine reads the display of the referenced row without the access rules of that row’s page.
A reader who can see a mark can see the name of its student. A display can never contain a
sensitive column, in any table that it reaches.
Choose between columns with coalesce
Section titled “Choose between columns with coalesce”display: coalesce(member, guest_name), eventcoalesce(a, b, …) shows the first of its columns that has a value. A signup of a member shows
Miller, Anna, Summer party. A signup of a guest shows Gil, Summer party. A ref column in
coalesce shows its display. coalesce needs at least two columns. It is the only function that
a display takes.
When there is no display:, the engine uses the first match of these rules:
- the column
name; - the column
title; - the first
requiredtextcolumn.
A sensitive column is never taken by these rules. If no column matches, the engine shows the
row’s id.
The compiler refuses these values:
- a column that the table does not declare. The message names the nearest column.
- a
sensitivecolumn, and asensitiveref. A display is read in places where no grant is checked. The message names the columns that you can use instead. - a second
display:line. Write all columns on one line, separated by commas. - a path such as
post.title. Writepost: the reference already shows the post’s display. - a column that is in the display twice.
- an
img, amulti, or a computed or aggregate column. A display shows stored values of one column each. The message names a column that you can use instead. - a display that follows more than four references. The message shows the references in order.
- a display that comes back to its own table, for example two tables whose displays name each other, or a category that shows its parent. The message shows the loop.
coalescewith one column, or with amulti, alist, animgor a computed column.
scope: seasonscope: puts the table under the application’s scope. The value is the path from this table to
the scope’s table, through ref columns. The application side is
scope in the app block.
scope: seasonscope: course.termThe engine then adds the scope’s condition to every read and every write of the table: reports,
forms, exports, the options of a select and exists(...). A table without scope: is not
filtered, even when it refers to the scope’s table. The compiler does not add a scope by itself.
When the path has one step, such as scope: season, the engine writes that column itself on an
insert, from the scope that the session chose. A request cannot supply it, and a form shows it as
a value, not as a control.
The compiler refuses these values:
| Refused | Reason |
|---|---|
any scope: when the app block declares no scope |
there is nothing to reach |
| a path of more than 3 steps | every step is a subquery in every query on the table. Store the reference closer. |
a path that does not end at a ref to the scope’s table |
the message names the paths that do |
a step through a ref column that is not required |
a row with an empty step would be in no scope, and no page would show it. Make the column required, or give the table its own required reference to the scope’s table. |
A page whose access: is public cannot read a scoped table. This includes the
display of a scoped table: a public page cannot show a ref whose display reaches a
scoped table, in a cell, a select or its title. A region with its own rule that needs a login can.
See Security.
check <condition> [at <field>] "<Message>"A check is a condition that every row of the table must meet. The message is on the same line,
after the condition, and it is mandatory. With at <field>, the message shows under that field.
Read Place the message under a field.
check ends_at >= starts_at "The end must not be before the start."check points >= 0 and points <= 15 "Points are between 0 and 15."The engine refuses a save when the condition is false. When the condition has no answer because a value that it compares is empty, the save is not refused. So the first example accepts an event with no end. Read Empty values in a rule.
The condition can read the columns of the row, the rows that its ref columns point to, computed
columns, aggregates, today and now. It can also ask about other rows of the table with
exists(…) and count(…). See Read the other rows of a key.
A check holds for every writer, so it cannot read the request.
The compiler refuses these conditions:
- a condition that reads
:user.…,:route.…or another value of a page. Put a rule about the request in the form asdeny when, or in a hook. - a condition that names a column that the table does not have.
- a
checkwith no message. - an
atthat names a field that the compiler refuses. See the next section.
For the task, read Check a value against the row.
Place the message under a field
Section titled “Place the message under a field”By default, the message of a check shows above the form, because a check is about the whole
row. Write at and the name of a field before the message to show it under that field:
check ends_at >= starts_at at ends_at "The end must not be before the start."check status != confirmed or not exists(room.bookings where status = confirmed and id != :this.id and starts_at < :this.ends_at and ends_at > :this.starts_at) at starts_at "This room is already booked in that time."The form shows the message like the error of a field. The control has aria-invalid="true", the
message is the error of the control and the control is described by it. The form keeps the values
that the person typed. The page needs no JavaScript. A check shows one message, because the first
rule that fails decides.
- The name is a field of the same table. It must be a field that holds one stored value, such as
a
text,int,datetime,enumorrefcolumn. Write arefby its field name:at room. atis not a reserved word. A column can still be calledat. The compiler readsatas the placement only after a complete condition.- A form without the field shows the message above the form. This is also true for a transition, which submits no field. The message shows beside the transition buttons.
- A sheet shows the message on the cell of that row and column, when the sheet has the column. Otherwise it shows the message in the sentence of the save.
requiretakes noat. Its message already shows on the column that it names.
The compiler refuses these:
- a name that the table does not declare. The message offers the nearest stored field.
- a field that holds no stored value: a computed column, an aggregate, a
list, amulti, animg, afile, or a column that the engine writes, such asid. - a
refwritten as its stored column, such asroom_id. Writeroom. - a path with a dot, such as
at room.name. - a
sensitivefield. Whether a form draws a sensitive control depends on the grants of the reader. The message would stand in different places for different roles, and its place would show a reader without the grant that the rule is about that field. Removeat, or choose another field.
Read the other rows of a key
Section titled “Read the other rows of a key”A check can also ask about other rows of its table, such as the bookings of the same room. Use
exists(…) or an inline
count(…) over a declared list column. Inside their where,
:this.<column> names a stored column of the row that the rule judges.
check <condition using exists(<path>.<list> where … :this.<column> …)> "<Message>"check <condition using count(<path>.<list> where … :this.<column> …) compared with a value> "<Message>"check status != confirmed or not exists(room.bookings where status = confirmed and id != :this.id and starts_at < :this.ends_at and ends_at > :this.starts_at) "This room is already booked in that time."check status != confirmed or count(shift.roster where status = confirmed and id != :this.id) < shift.needed "This shift already has all the volunteers it needs."The two lines are from different tables. The first needs a ref column room and a
bookings list(bookings.room) column on the rooms table. The second needs a ref column
shift, a roster list(assignments.shift) column and an int column needed on the shifts
table. Write the whole rule on one line. A rule cannot continue on the next line.
- The relation is a
listormulticolumn. A path ofrefcolumns can come before it, such asroom.bookings. The compiler writes the join. - A row without a key passes the rule. When
roomis empty, theexistsmatches no row. To require a key, addcheck room is not empty or resource is not empty "A booking needs a room or equipment." - Which rows block is your condition. The engine does not decide it. In the first example only a
confirmedbooking blocks, so arequestedbooking can overlap another one. The save that confirms it, a form or a transition, is the one that the rule can refuse. - An interval is half-open.
starts_at < :this.ends_at and ends_at > :this.starts_atlets one booking end when the next one begins. - The rule ignores who saves. The
existsand thecountapply no access rule, no app scope and no:user.existssees rows in agonestate.countleaves them out. - The refusal is one message above the form, unless you write
at. Addat starts_atbefore the message to show it under the start time. - Empty values. Inside the
where, a comparison with an empty value is false. Declarestarts_atandends_atasrequiredwhen the rule needs them. - The compiler adds an index for the range. When the
wherecompares a column of the other rows with a:thiscolumn using>or>=, such asends_at > :this.starts_at, the compiler adds an index on the key and that column, hereroom_idandends_at. The comparison in the other direction,starts_at < :this.ends_at, gets no index. An existing app gets the index with its next deploy. The deploy plan shows it as acreate_indexstep, and you do not have to acknowledge it. - The cost depends on where the new row falls. The engine runs the question once for each save of the table, and twice for a form save (the check before the write and the decision in the write). With the index, the question reads the rows that end after the new row. On an Apple M3 Pro, with 10,000 bookings of one room, the median time of the question was 0.04 ms for a booking after all the others, 0.07 ms after 99 percent of them, and 0.04 ms for a booking that the rule refuses. It was 1.2 ms for a free slot in the middle of the past and 2.3 ms for a slot before every other booking. With 1,000 bookings, these were 0.16 and 0.27 ms. A whole form save took 1.0 ms with the rule and 0.93 ms without it, at 10,000 bookings of one room.
The compiler refuses these:
- a name that the table does not declare. The message offers the nearest stored field.
- a field that holds no stored value: a computed column, an aggregate, a
list, amulti, animg, afile, or a column that the engine writes, such asid. - a
refwritten as its stored column, such asroom_id. Writeroom. - a path with a dot, such as
at room.name. - a
sensitivefield. Whether a form draws a sensitive control depends on the grants of the reader. The message would stand in different places for different roles, and its place would show a reader without the grant that the rule is about that field. Removeat, or choose another field.
Read the other rows of a key
Section titled “Read the other rows of a key”A check can also ask about other rows of its table, such as the bookings of the same room. Use
exists(…) or an inline
count(…) over a declared list column. Inside their where,
:this.<column> names a stored column of the row that the rule judges.
check <condition using exists(<path>.<list> where … :this.<column> …)> "<Message>"check <condition using count(<path>.<list> where … :this.<column> …) compared with a value> "<Message>"check status != confirmed or not exists(room.bookings where status = confirmed and id != :this.id and starts_at < :this.ends_at and ends_at > :this.starts_at) "This room is already booked in that time."check status != confirmed or count(shift.roster where status = confirmed and id != :this.id) < shift.needed "This shift already has all the volunteers it needs."The two lines are from different tables. The first needs a ref column room and a
bookings list(bookings.room) column on the rooms table. The second needs a ref column
shift, a roster list(assignments.shift) column and an int column needed on the shifts
table. Write the whole rule on one line. A rule cannot continue on the next line.
- The relation is a
listormulticolumn. A path ofrefcolumns can come before it, such asroom.bookings. The compiler writes the join. - A row without a key passes the rule. When
roomis empty, theexistsmatches no row. To require a key, addcheck room is not empty or resource is not empty "A booking needs a room or equipment." - Which rows block is your condition. The engine does not decide it. In the first example only a
confirmedbooking blocks, so arequestedbooking can overlap another one. The save that confirms it, a form or a transition, is the one that the rule can refuse. - An interval is half-open.
starts_at < :this.ends_at and ends_at > :this.starts_atlets one booking end when the next one begins. - The rule ignores who saves. The
existsand thecountapply no access rule, no app scope and no:user.existssees rows in agonestate.countleaves them out. - The refusal is one message above the form, unless you write
at. Addat starts_atbefore the message to show it under the start time. - Empty values. Inside the
where, a comparison with an empty value is false. Declarestarts_atandends_atasrequiredwhen the rule needs them. - The cost grows with the rows of one key. The engine runs the question once for each save of the table. It reads every row of the key. On an Apple M3 Pro, the median time was 0.05 ms for 100 bookings of one room, 0.15 to 0.34 ms for 1,000, and 1.1 to 3.0 ms for 10,000. The time is linear in the rows of the key. In the test, an extra index on the key and the end time did not change the plan, because an overlap test has two ranges.
The compiler refuses these:
:thisanywhere other than thewhereof anexists(…)or acount(…)in acheckor in the condition of arequire … when. In a listing, a form, a computed column, an aggregate column or awhere:, there is no row being judged. In the rule itself, write the column without the colon.:thisfollowed by a path, such as:this.shift.needed. Write the walk in the rule, outside the aggregate:shift.needed.:thison a column that is not stored, such as alist, an aggregate, a computed column, or a column that the engine writes. Arefis:this.room, and never:this.room_id.count(…)anywhere other than a table rule. To show or store a count, declare an aggregate column.- a
gonestate in thewhereof acount(…). Useexists(…)to ask about agonerow. - a
sensitivecolumn in thewhereof anexists(…)or acount(…). Whether other rows pass a test on that column would show in the refusal that every writer reads. - a relation that is a table name, or a column that is not a
listor amulti.
The engine decides such a rule inside the transaction of the write. Two people who save at the same moment cannot both pass it. See Rules on every write.
require
Section titled “require”require <column> when <condition> "<Message>"A require makes one column mandatory while a condition is true. The message is on the same
line, after the condition, and it is mandatory.
require capacity when kind = limited "A limited event needs a capacity."The engine refuses a save when the condition is true and the column is empty. An empty text
counts as empty. A bool column that is false is not empty. When the condition has no answer,
the column is not mandatory.
A form shows the message on the field of that column. The form also marks the field as required while the condition is true. If the form has no field for the column, the message shows above the form.
The compiler refuses the same conditions as for check, and also a column that the
table does not declare. The condition can use exists(…) and count(…) with :this, as a
check can. See Read the other rows of a key.
unique
Section titled “unique”unique(<column>, <column>, …) "<Message>"unique(…) says that no two rows can hold the same combination of values in these columns. The
message is on the same line and is optional.
unique(title, starts_at) "An event with this title already exists at that time."To make one column unique, write unique(name) or the unique modifier on the column. See
Modifiers and properties. A unique modifier and
a unique(…) statement over the same column are one rule, and the statement’s message is used.
The compiler makes each rule a unique index in the database file. The engine checks the rule before it writes, so the person reads the message and never a database error. If two people save at the same moment, the index refuses the second write, and the engine shows the same message.
- Empty values never collide. A row with an empty value in one of the columns is never a
duplicate. So
unique(event, member)allows many signups with no member. - Every row counts. A value in a row that the person cannot see is still taken.
- With no message, the engine shows “This value is already in use.”
- For one column, the message shows on the field of that column. For several columns, it shows above the form.
The compiler refuses a column that the table does not declare.
Rules on every write
Section titled “Rules on every write”check, require and unique are the table’s rules. The engine evaluates them against the
candidate row. This is the stored row, with the defaults, the submitted values and the form’s
set values applied. It is the row that the save would write.
The engine evaluates the rules on these writes:
- every save of a form or a sheet, before the write;
- every transition, against the row after the move;
- a second time inside the write, when a
beforehook changed the row.
A rule that asks about other rows of its table, with exists(…) or count(…), is decided
inside the transaction of the write, after the before hooks, on the row that the write
will store. Every tenant write goes through one writer, so a second save cannot slip in between
the rule and the write. The earlier evaluation still runs, and it shows the refusal as a form
with the person’s input in it. The evaluation in the transaction decides. This applies to:
- a form: an insert or an update. A delete writes no row, so no rule applies;
- a transition;
- a sheet save. The sheet checks each row after the rows that it saved before it, so a new row counts against the rows above it in the same save. The sheet checks the changed rows in the order of the save and then the new rows. A row that fails is not written, and it does not count against the rows after it. The sheet shows the message of every row that fails. If any row fails, the save writes nothing.
The check and require rules are evaluated in source order, and the first one that fails
decides the message. They are not constraints in the database file. A tool that writes to the
file directly is not checked.
| Rule | Where the message shows |
|---|---|
check |
above the form. With at <field>: on that field. Above the form when the form has no such field. |
require |
on the field of the column. Above the form when the form has no such field. |
unique with one column |
on the field of the column. Above the form when the form has no such field. |
unique with several columns |
above the form |
| any rule, on a transition | beside the transition buttons |
Empty values in a rule
Section titled “Empty values in a rule”A rule works like an SQL CHECK constraint. A comparison with an empty value has no answer, and
the rule is not refused:
notover a comparison with no answer has no answer.check points >= 0 and points <= 15accepts an emptypoints.require capacity when kind = limiteddoes not apply whilekindis empty.- A
boolcolumn alone is never empty in a rule. An emptyboolcounts as false.
To refuse the empty case, say so in the rule. Use require, or write the test for emptiness:
check reminder_minutes is not empty and reminder_minutes > 0.
This applies only to check and require. In where:, access rules, deny when, show_when:
and computed values, a comparison with an empty value is false.
before and after
Section titled “before and after”before <event> -> <script>after <event> -> <script>A hook runs a TypeScript module on a write to the table. The event is insert, update or
delete. The script is a path in the application directory, such as logic/event-created.ts.
before insert -> logic/count-words.tsbefore update -> logic/count-words.tsafter insert -> logic/event-created.tsA table can bind several hooks to one event. They run in source order. On one write, the table’s
hooks run before the hooks of the form. A form binds its own hooks with before save and
after save. See Add business logic with hooks.
The compiler refuses these hooks:
| Refused | Reason |
|---|---|
an event other than insert, update and delete, such as save |
save is a form’s event. The message names the three events. |
a script that does not end in .ts |
a hook runs a TypeScript module |
a path that starts with / or contains .. |
the script must be in the application directory |
| a script that does not exist | the compiler knows the files when it compiles a directory. The message names the nearest script. |
insert, update and delete
Section titled “insert, update and delete”| Event | The hook runs on |
|---|---|
insert |
a save that creates a row, from a form or a sheet |
update |
a save that changes a row, from a form or a sheet |
delete |
a delete, from a form or a sheet |
A transition does not run the insert or update hooks. It runs its own hooks. See
before and after in a transition.
The hook receives the row with stored column names. A ref column season is
row.season_id.
before
Section titled “before”A before hook runs inside the transaction of the write. It runs after the form’s
deny when and before the statement that writes.
- The hook can change the row. Whatever it changes is checked again against the column types and the table’s rules. If it changes a column that the engine owns, the write is refused.
- The hook can refuse the write with
throw ctx.error("name", { … }), wherenameis a message declared inmessages. The person reads that message in their language, and nothing is written. A sentence in place of a name is shown as written. ctx.dbcan read the application’s tables. It cannot write, and it cannot send mail.
Mark a column that a before insert or before update hook writes with the derived modifier.
See Mark a column that the hook writes.
When a sheet’s save runs a before hook on each row, the sheet saves at most 50 rows at a time,
instead of 200.
An after hook runs after the commit, in its own transaction.
- It sees the row as it is stored. On an
updateit also receives the previous row. - It cannot roll back the write, and its failure never shows to the person who saved.
- The engine logs a failure and writes it to the audit log.
ctx.dbcan read the application’s tables, andctx.mailcan send at most 5 mails.
Limits of a hook
Section titled “Limits of a hook”Every hook run has 100 ms of wall-clock time, then a 300 ms grace period, 32 MiB of memory and at
most 50 database calls. A before hook that goes past a limit refuses the write. A script that
cannot run refuses every write that binds it, and only those writes. A result completed at or
after 100 ms is refused even if the timer runs late. The grace period lets the script stop;
it does not extend the time allowed for a successful result. There is no ctx.http.
The memory limit counts everything the script allocates, also what it frees. Measured values:
a hook that reads 2,000 rows with ctx.db.query and adds up one column allocates 8.4 MiB. A hook
that builds 10,000 small objects and calls JSON.stringify on them allocates 21 MiB. A hook that
reads 7,000 rows (about the most that a query of six columns can return) allocates 22 MiB. A hook that reads 7,000 rows
and also converts them to JSON allocates 29 MiB, which is near the limit. The largest hook in the
tests of the engine allocates 1.1 MiB.
A hook may not hand the engine a long string to turn into code or into a pattern. The engine parses nested input with recursion, and a deeply nested string would stop the whole server. These limits apply:
| What | Limit | What happens above it |
|---|---|---|
| The source file of a hook module | 16 KiB (16,384 bytes) | The module cannot run. The writes that bind it are refused. Other hooks are not affected. |
A string given to eval, Function, or to the constructors of async and generator functions |
4,096 characters, all arguments together | The call throws a TypeError with code E_CODE_TOO_LARGE. A hook can catch it. |
A pattern given to RegExp, to compile, or to match, matchAll and search as a string |
16,384 characters | The call throws a TypeError with code E_PATTERN_TOO_LARGE. A hook can catch it. |
A regular expression literal in the source (/ab+c/) counts toward the 16 KiB of the file and
nothing else. The largest hook module in the example applications is 1.1 KiB.
eval runs its code in the global scope, even when it is called as eval(code). It does not see
the local variables of the function that calls it.
The module of a hook
Section titled “The module of a hook”A hook module is a TypeScript file. The binary turns it into JavaScript with esbuild when the
tenant opens, and validate, install, dev, deploy, upgrade and test run the same step
first. The file you stored stays as you wrote it.
| What | Effect |
|---|---|
Type annotations, interface, type, generics, as, satisfies, !, declare |
Removed. The engine does not check them: a hook with a wrong type still runs. |
enum, namespace, class parameter properties |
Turned into JavaScript that runs. |
?., ??, object spread and newer syntax |
Rewritten for ES2017, which the sandbox runs. |
import { defineHook } from "@matterdata/sdk" |
Allowed. It is the only import. defineHook is also available without it. import type is allowed from the same module. |
Any other import, require("…"), import("…") or export … from "…" |
Refused with file:line:col of the module name. A hook module cannot load another file. |
| An import that TypeScript removes because it is only used as a type | Not an error: it produces no code. |
export default, export const, export type |
Allowed. Nothing is exported to anything. |
The refusals name the line and the column of your .ts file. A syntax error, a refused
RegExp pattern, and the stack of an error that a hook throws (in the server log) all point into
the file you wrote and never into the generated JavaScript. When a position has no counterpart in
your file, the message says so and gives the generated position.
The 16 KiB limit above applies twice: to your file, and to the JavaScript that is made from it. Rewriting new syntax for ES2017 can make a module larger. The message for the second case gives both sizes.
matterdata sdk <app-dir> writes the types of @matterdata/sdk and of every table for tsc; see
Write a hook in TypeScript with types. That
declaration is a .d.ts file in .matterdata/. The loaders skip .d.ts files, directories that
start with a dot, and node_modules, so it is never read as a module.
A .ts file that no hook names is stored but never turned into JavaScript. The compiler reads the
text of every .ts file for ctx.error calls, so write a message name as a plain string literal.
lifecycle
Section titled “lifecycle”lifecycle <column> "<Label>" { state <name> <flags> "<Label>" transition <name> <from>, <from> -> <to> "<Label>" [icon <name> [only]] { … }}A lifecycle is a set of states and the moves between them. It declares its column, and the column changes only through a transition. For the task, read Move a record through states.
lifecycle status "Status" { state draft default "Draft" state published public "Published"
transition publish draft -> published "Publish" { access: board }}The lifecycle declares the column status as an enum. Its values are the states, in the order
you write them. Their captions are the states’ labels, and the column’s label is the lifecycle’s
label. Reports, filters, stats regions and exports show it like any other enum column.
The column belongs to the engine:
- A new row starts in the
defaultstate. - A request cannot set the column. A form that names it in
fields:shows the state as a value, not as a control. - A
seton the column is refused when the engine opens the application.
A page that shows one row of the table in a form or a detail region shows the current state
and a button for each transition. The label of the lifecycle is the heading. With no label, the
heading is “Status”.
A transition may name an icon after its label: transition publish review -> published "Publish" icon send { … }. The button then shows the icon before the label. Add only
to show the icon alone. The label stays as the button’s accessible name and its tooltip. A
transition with no label uses its name.
In a condition, status.public and status.gone are true when the row is in a state with that
flag. To test one state, compare the column: status = draft, status != archived or
status in (draft, review). Only these two flags can follow the dot. The compiler
refuses status.draft, and the message shows the comparison to write instead
(write: status = draft). It refuses status.default in the same way.
The compiler refuses these lifecycles:
- another column with the name of the lifecycle, such as
status enum(…) "Status". The lifecycle declares the column already. The message tells you to writestatus lifecycleinstead, and it says when the values, captions or label were different from the lifecycle’s. - a
status lifecycleline with a label, a flag or a block, a line with no lifecycle of that name in its table, and a second line for the same lifecycle. - a second
lifecyclein one table. A second set of states belongs in a table of its own. - a lifecycle with no
state, or with nodefaultstate. - a state that no chain of transitions leads to from the default state. A transition from a state to itself does not count, and neither do two states that only lead to each other.
The compiler warns, and still compiles, when the column of the lifecycle and another enum
column of the table have the same set of values. The order does not matter. A misspelt name
causes this. With status enum(draft, review) "Status" and lifecycle stats "Status", the
lifecycle declares a second column stats. The warning is at the lifecycle keyword and names
both columns. To repair it, write lifecycle status and replace the status enum(…) line with
status lifecycle. An enum that holds only some of the states does not cause the warning.
Place the column
Section titled “Place the column”The column stands where the lifecycle is written, among the columns of the table. To put it
somewhere else, write its name and the word lifecycle on a line of its own:
title text required "Title"status lifecyclepublished_at datetime "Published on"
lifecycle status "Status" { state draft default "Draft" state published public "Published" transition publish draft -> published "Publish" { access: board }}The line only places the column, so it has no label, no flags and no block. The order of the
columns is part of the database schema, and a changed order rebuilds the table on the next
upgrade. A table that was written with an enum column beside its lifecycle keeps its schema
when that line becomes status lifecycle.
state <name> <flags> "<Label>"A state is one value of the column’s enum. The flags come before the label. The label is
optional, and it is the caption of the value. With no label, the engine shows the name.
lifecycle status "Status" { state draft default "Draft" state review "In review"
transition submit draft -> review "Send for review" { access: member }}| Flag | Effect |
|---|---|
default |
A new row starts in this state. Exactly one state has it. |
public |
status.public includes this state. |
gone |
status.gone includes this state. Lists, stats regions, counts, matrix axes and the choices of a ref or multi field leave out a row in this state, and a public page answers 410 for it. |
public does not filter a page by itself. A page must say where status.public to show only
public rows.
gone marks a row as retired: deleted, withdrawn or replaced. The row stays in the database,
and staff can still open it. Do not use gone for an archive that readers can still open. For
that, use a public state that the front page’s where: leaves out.
gone does filter, in these places:
- Listings. A
report, alistand asheetleave out the rows in agonestate. Their CSV and XLSX exports, their calendar feeds and the sheet’s grid leave them out too. This is true on every page, also on pages that only staff can open. A search or a filter cannot bring the rows back. Afilter:on the lifecycle column does not offer thegonestates. - Counts. A
statsregion leaves out the rows in agonestate, and it shows no tile for agonestate. Acount,sum,minormaxcolumn leaves them out too (Column types: gone). So “3 comments” beside a record agrees with the list of its comments. - A public page. A page with
access: publicanswers 410 Gone for a row in agonestate. The page shows the engine’s own error text and nothing of the row. This happens even when the page’sdata … wheredoes not admit the row. A row that the route’s scope or the application’s scope does not admit is still a 404. - Choices. A
reformultifield does not offer a row in agonestate, on a form or in the grid. A save that picks one anyway is refused on the field. A record that already points at such a row keeps it: its edit form shows the row as selected, and a save that sends it back is accepted. You can also tick new rows beside it. A new record and a duplicate cannot pick it. - Matrix axes. An axis of a
matrixleaves out the rows in agonestate, unless the axis saysgone: show, as for a region below.
exists(...) still sees the rows in a gone state. It is a condition that you write in full,
often in an access rule, so it means exactly what it says. As a result, exists(...) and a
count above zero can disagree when the related rows are in a gone state.
A page that is not public shows a row in a gone state as before. Staff can open the row and
move it back with a transition.
To list the rows in a gone state, write gone: show in the region:
report of posts "Archived posts" { columns: title, status where: status = archived gone: show}gone: show works in a report, a list, a sheet, a stats region and a matrix axis. The
engine then leaves out no row, the where: decides, and a filter: on the lifecycle column
offers every state. show is the only value. The compiler refuses gone: show on a table
that has no gone state.
The compiler refuses a where: that names a gone state when the region does not say
gone: show. Without it, the region reads no row in a gone state, so the condition does
nothing useful: status = archived is never true, and status != archived leaves out rows
that are already left out. The where: names a gone state when it compares the lifecycle
column with that state (status = archived, status != archived), or tests the flag
(status.gone). A named condition that does one of these also counts.
status != draft and status.public name no gone state.
The compiler refuses these states:
- the name
public,goneordefault. These words are flags. - a name that the lifecycle already declares.
- a second
defaultstate. - a state that no transition leads to, unless it is the
defaultstate. - a flag after the label. The message shows the line in the correct order.
For an archive state, declare a move into it, such as
transition archive active -> archived. Add
transition restore archived -> active when readers need to restore a row.
transition
Section titled “transition”transition <name> <from>, <from> -> <to> "<Label>" { access: <roles or rights> set <column> = <value> when <condition> deny when <condition> "<Message>" before -> <script> after -> <script>}A transition moves a row from one of the <from> states to the <to> state. The label is the
text of the button. With no label, the button shows the name.
lifecycle status "Status" { state draft default "Draft" state published public "Published" state cancelled gone "Cancelled"
transition publish draft -> published "Publish" { access: board } transition cancel draft, published -> cancelled "Cancel" { access: board }}The button is absent when the reader cannot perform the transition, and when the row is not in
one of the <from> states. A POST is checked again:
- The
<from>states and the reader’s row filter are part of the update statement. If the row moved in the meantime, nothing is written, and the page says “The status is now “…”. Reload the page.” - A row that the reader cannot see is a 404.
The move runs in one transaction, in this order: deny when, the table’s unique, check and
require over the moved row, the before hooks, then the update. The update also writes the
set columns, updated_at and updated_by. After the commit, the engine writes a
row.transition event to the audit log and runs the after hooks. Then the page reloads.
The compiler refuses these transitions:
- a transition with no
access. - a
<from>or a<to>that the lifecycle does not declare. - a name that the lifecycle already declares.
requires. A transition refuses withdeny when.
access
Section titled “access”lifecycle status "Status" { state draft default "Draft" state published "Published"
transition publish draft -> published "Publish" { access { author where author = :user.person_id editor } }}access names the roles or rights that can perform the transition. It is mandatory. It has the
same two forms as a page’s access: a list on one line, or a block with one rule per role and an
optional row filter. See Access rules and rights.
The row filter can read only the moved table. A filter on another table is refused when the
engine opens the application. The compiler refuses a role that the app block does not declare.
set <column> = <value> when <condition>set writes a column as part of the move. The when part is optional. When its condition is not
true, the column keeps its value.
lifecycle status "Status" { state draft default "Draft" state published public "Published"
transition publish draft -> published "Publish" { access: board set published_at = now when published_at is empty }}The value and the condition can read the row and the rows that it refers to. The compiler refuses
a column that the table does not have. The engine refuses these set lines when it opens the
application: a set on the lifecycle column, on a column that the engine owns, and on an img or
a multi column.
deny when <condition> "<Message>"deny when refuses the move when its condition is true. The message is on the same line and is
mandatory.
lifecycle status "Status" { state draft default "Draft" state cancelled gone "Cancelled"
transition cancel draft -> cancelled "Cancel" { access: board deny when starts_at < now "An event that has started cannot be cancelled." }}The engine decides the deny when only when the button is pressed, inside the transaction. It
does not hide the button. The message shows beside the buttons, and the other buttons stay
usable.
Use an access rule with where when the button must be absent for those rows.
Use deny when when the person needs a refusal message after pressing it.
before and after in a transition
Section titled “before and after in a transition”before -> <script>after -> <script>A transition’s hook has no event word, because the event is the transition.
- A
beforehook runs inside the transaction, after the table’s rules. It can refuse the move withthrow ctx.error("name")(seemessages). It cannot change the row: abeforehook that changes the row refuses the move. - An
afterhook runs after the commit. It sees the row after the move and receives the row before the move as well. An amendment from an after hook is refused in its own transaction and reported as a hook failure; the completed move remains committed.
The compiler refuses the same scripts as for a table’s before and after,
and an event word such as after update.
approvals
Section titled “approvals”An approvals: policy on a transition collects confirmations from 1–9 distinct logins.
The press that meets the count and required roles moves the row. Earlier presses save a vote
and leave the state unchanged. Approvals work with ordinary HTML forms, without JavaScript.
lifecycle status { state draft default "Draft" state submitted "Submitted" state approved "Approved" state paid "Paid" transition submit draft -> submitted "Submit" { access: board } transition pay approved -> paid "Pay" { access: treasurer }transition approve submitted -> approved "Approve expense" { access: board, treasurer approvals: 2 { including board including treasurer excluding creator, submitter covers lines } set approved_at = now}}| Declaration | Effect |
|---|---|
approvals: <n> |
Require 1–9 different eligible logins. approvals: 1 is supported. |
including <role> |
Reserve one required role for a different person. Repeat for more roles. |
excluding creator, submitter |
Refuse the login that created the row or entered its current source state. Either exclusion can be used alone. |
covers <relation> |
Include the full related rows. At most two list or multi relations, at most 500 rows per relation. |
Required roles must belong to the transition’s named application roles. public,
authenticated, anonymous visitors, and system actors cannot approve. A login with both
board and treasurer fills one required slot. Extra people may approve while a required
role is missing; reaching the count alone does not promise completion.
The page must provide a form or detail for the owner and a list, report, or sheet for every
covered relation. One allowed region must admit the entire covered set and all its sensitive
stored fields. A filtered subset, missing grant, hidden or out-of-scope child refuses approval
with a generic message. Pagination and search do not reduce the approved set. Gone child rows
are included and need explicit gone: show review access.
Confirmation covers every stored author value, stored reference key, file/image metadata and
multi membership. Root lifecycle, audit metadata and calculated values are excluded. Covered
child lifecycle states are included. A referenced display name changing does not change the
stored key: declare covers when the target content itself needs approval. Review the complete
content disclosure beside the action before approving.
A pending edit makes earlier votes stale. Approve updated content replaces that person’s pending vote; the replaced pending fact is not kept as completed history. A no-op leaves the vote valid, and an exact revert in the same state stay can make it valid again. A repeated confirmation of unchanged content keeps the original comment and time. A comment is optional, escaped plain text, with a limit of 500 Unicode characters.
Pending votes count only while the account exists, is enabled and holds an eligible role, including roles supplied by tenant groups. A required role must have admitted the approver’s row at the original press and still be held now. Other earlier approvers’ full row conditions are not replayed. A person who still sees the row can withdraw their own pending vote after losing an approval role. Completed votes cannot be withdrawn.
Progress and completed history are private to admitted approvers and the creator under the page’s normal row and scope access. A person’s own pending vote remains available for withdrawal. History records identities, role snapshots, comments, times and the requirements satisfied at completion. It lasts until the owner is deleted and does not preserve a readable copy of past content.
reopen
Section titled “reopen”Completed owner and covered content is protected. A form, sheet, seed, or retention operation cannot change it under an active obligation. State-only successors, such as marking an expense paid, preserve the protection. No-op saves are allowed.
lifecycle status { state draft default "Draft" state submitted "Submitted" state approved "Approved" state paid "Paid" transition submit draft -> submitted "Submit" { access: board } transition approve submitted -> approved "Approve" { access: board } transition pay approved -> paid "Pay" { access: treasurer }transition reopen approved, paid -> draft "Reopen for changes" { access: board, treasurer reopen: approve}}reopen: <approval-transition> [, ...] belongs to an ordinary transition. It retires the named
completion certificates atomically, preserves their history, and starts a fresh state stay.
Edit, submit, and collect fresh confirmations afterwards. Independent obligations not named by
this reopen continue to protect the content. Returning a pending row needs no reopen: marker.
The compiler checks the protected states and all paths into and out of them. Only the approval
transition may enter its protected set from outside, and every protected state must have a
path to a marked reopen. Ordinary successors cannot set protected author values. A protected
legacy row with missing or stale approval evidence may be reopened, but cannot be edited or
advanced using the missing evidence. An unknown legacy submitter requires return and resubmit
when excluding submitter is used.
Schema, coverage, encoding, and protected-path changes may require reopening affected records before deployment. Changing the required count or roles never moves a record automatically and does not rewrite completed history. Deleting an owner deletes its own history, but still refuses if that owner is covered by a surviving protected record.
Content checks are bounded to 4 MiB of encoded content, 10,000 total multi memberships, and 500 affected owners per mutation. Exceeding a bound refuses the operation; it never approves or protects only a subset.
rename
Section titled “rename”rename <previous name> to <current name>rename tells the migration that a column has a new name and keeps its data. Without it, a
missing column and a new column look like a delete and an add, and the migration refuses to
delete the data.
mobile text "Mobile number"
rename phone to mobileThe compiler refuses these lines:
- a
<current name>that the table does not declare. - a
<previous name>that the table still declares. Delete the old declaration. - a column renamed to itself.
The migration refuses these renames, when it compares the new model with the installed one:
- a
<current name>that the installed table already has. Drop that column first, or choose a name that nothing uses. - a chain (
atob,btoc) or a swap in one release. Split it into two releases. - a rename that also changes the number of stored columns, such as
texttoimg. - a rename of a
multicolumn.
The line can stay in the source after the rename ran. When it matches nothing, the migration reports it as unused and continues.
retype
Section titled “retype”retype <column> keep ["Reason"]retype <column> scale ["Reason"]retype tells the migration what the stored numbers of a column meant when the column changes
from int to decimal(n), or back. The database keeps the same
whole numbers either way, and only you know whether a stored 145 meant 145 or 14.5.
keep: the stored numbers already were the number with its places.145stays145and now reads 14.5 in adecimal(1). Use it for a column that held tenths or hundredths by hand.scale: the stored numbers were whole numbers. The migration converts them so the number you see stays the same:145becomes 145.0, stored as1450. From adecimalback to anint, it divides, and it stops if a value has a digit after the point.
raw_points decimal(1) "Raw points"
rename raw_points_tenths to raw_pointsretype raw_points keep "The int held tenths: 145 was 14.5 points."Without a retype, the migration refuses the change and shows both lines. Name the column by
its current name, so retype works together with rename.
The compiler refuses a retype of a column that the table does not declare, of a column that is
not an int or a decimal, and a second retype of the same column.
Other number changes need no retype. A decimal that gets more places is multiplied, for
example decimal(1) to decimal(2). A decimal that gets fewer places is divided, and the
migration stops if a value has a digit in a place that goes. money to decimal(2) keeps every
stored number, because both store hundredths.
Like rename, the line can stay in the source after the migration ran. When it matches nothing,
the migration reports it as unused and continues.
drop <column> !destructive "<Reason>"In a table, drop acknowledges that a column and its stored data are deleted. A column that is
gone from the source has no declaration left, so the acknowledgement is written in its table.
The reason is optional, and the migration plan records it.
drop fax !destructive "The club has no fax machine."The migration deletes a column only when its drop line is present. Without it, the migration
is refused, and the message names the line to write. For a versioned column, the line also
deletes the column’s history.
The compiler refuses these lines:
- a
dropwithout!destructive, and any other word after!. - a column that the table still declares. Delete the declaration too.
matterdata upgrade applies the migration to an organization that holds data. For a column that
it deletes, it also needs -allow-destructive <app>.<table>.<column>, or
-allow-destructive <app>.<table>.
To delete a whole table, write drop table in the app block. See
drop in the app block. To delete only the history of a column, write
drop versions of.
versions
Section titled “versions”versions keep 20 within 1yversions sets how much history the table keeps for its versioned columns. It is optional, and
the default is the 20 newest versions of each row. The compiler refuses it in a table with no
versioned column. The forms and the limits are on
The versions statement.
retention
Section titled “retention”retention 2y after created_atretention sets how long the table keeps a row, or one column of it, counted from a date. The
engine deletes what is past the window once a day. The windows, the paths and the refusals are on
retention. A new or shorter rule needs an
acknowledgement in the app block. See retention in the app block.