Semantius Logo
DocsData CatalogBusiness LogicJsonLogic Extensions

JsonLogic Extensions

On this page

Semantius extends the standard JsonLogic spec with additional variables and operators tailored to record-level computed fields, validation rules, and row-level select rules. This page documents the extensions and the shape each rule takes; all standard operators (if, and, or, var, ==, +, map, filter, reduce, etc.) work as described in the JsonLogic overview. Rollup filters use a compiled subset of their own, described under Rollup fields.


Rule shapes

Each extension point stores its rules in a fixed shape.

computed_fields

An array of entries, each naming the field it writes:

[
  { "name": "subtotal", "jsonlogic": { "*": [{ "var": "quantity" }, { "var": "unit_price" }] } },
  { "name": "total", "jsonlogic": { "+": [{ "var": "subtotal" }, { "var": "tax" }] } }
]
  • Entries run in the order listed, and each result is written into the row before the next entry runs, so total above reads the subtotal just computed.
  • A dotted name such as settings.theme writes into a key of a JSON column.
  • The jsonlogic may be a literal scalar or list: a constant is a legitimate value for a field. An object with several keys is refused (90923), even as a constant.
  • A field that an entry names gets the ctype computed (computed_label on the label column). Forms show it disabled, and any value a client sends is overwritten.
  • required still applies to a computed field, unless the field also has an input_type_rule: such a field gets no database required check. The check runs after the rule, so it refuses a write whose rule produced no value.
  • A computed entry cannot write a rollup field (90907), though it can read one.

Existing records follow the rule. Saving a new or changed entry applies it to the records that already exist, and does the same when the field it names is added later. Only records whose value moves are written, and each one goes through the entity’s normal write path, so its validation rules run. This is a recalculation, not an edit: it moves no updated_at and writes no audit row, queue message or RACI event. If any record cannot take its new value, because a validation rule or a constraint refuses it or the rule itself fails, the whole save is refused (90908) and nothing is left half applied. When any record has to be written, other writes to the entity’s table, and to the tables that write reaches (the rest of an is_a or has_a family, rollup parents), wait until the save commits.

During this pass a rule sees $mode as "update", $old as the record itself, and $user_id as the user who saved the rule. An insert-only stamp such as {"if": [{"==": [{"var": "$mode"}, "insert"]}, {"var": "$user_id"}, {"var": "$old.created_by"}]} therefore keeps the value it already holds, while a rule that stamps $now or $user_id unconditionally moves on every record: a $user_id stamp writes the id of the user who saved the rule into all of them.

Removing an entry writes nothing. The field keeps the values it holds, now as ordinary data, and loses the computed ctype.

validation_rules

An array of entries, each with its own error code and message:

[
  {
    "code": "99001",
    "message": "Quantity must be at least 1",
    "hint": "Enter a positive quantity",
    "jsonlogic": { ">=": [{ "var": "quantity" }, 1] }
  }
]
  • code, message and jsonlogic are required (90902, 90903, 90904). hint is optional.
  • code is the error code the failure raises, and it must lie between 99000 and 99999 (90905). Class 99 is reserved for rule authors, so a code never collides with a platform error. Two entities may use the same code for different things: clients translate class 99 errors by entity and code together.
  • The jsonlogic must be a single operation (90919). See Checks when a rule is saved.
  • A failing rule raises its message with a JSON hint holding entity (the table name), rule (the code) and your hint, if given. It never copies values of the row into the error. To put a value in the message, use throw_error with parameters inside the rule.

Rules the platform itself ships carry "source_module": "platform" and a 90xxx code. Rules you write never do.

select_rule

A single JsonLogic operation that returns truthy for the rows the caller may see:

{ "or": [{ "has_permission": "tickets:read_all" }, { "==": [{ "var": "assignee_id" }, { "var": "$user_id" }] }] }
  • {} means no rule, and the entity’s view_permission decides alone. Once a rule is set, it takes the place of view_permission, and it also decides which rows an update or delete can reach.
  • An update or delete reaches a row only when the caller holds the entity’s edit_permission and the rule passes on the row as stored. The row an insert or update writes is held to edit_permission only, so an editor can write a row outside the rule: the write returns it, and from then on the editor can no longer read, update or delete it.
  • A rule that raises an error on a row hides that row. The database logs a warning naming the entity once per transaction, without the error message, which could quote a value of the hidden row.
  • For an is_a or has_a entity, the row the rule sees includes the fields of its base entities.

input_type_rule

A rule on a field that returns its input mode for the record being edited:

{ "if": [{ "==": [{ "var": "status" }, "closed"] }, "readonly", "default"] }
  • The result must be one of default, required, readonly, disabled or hidden, and it replaces the field’s static input_type. A rule that throws, or returns anything else, keeps the static mode, and the form shows why.
  • It runs in the browser only (see In the browser), so it is a presentation aid, never a security gate.
  • It may be a literal, and {} means no rule.

Checks when a rule is saved

Every rule is checked when its entity or field is saved, so a mistake is refused at save time instead of surfacing on an unrelated record later:

  • Unknown operators. A rule that names an operator the engine does not implement is refused (90909), wherever it stands, including a branch of an if that rarely runs and a field’s input_type_rule. The error names the rule’s place: select_rule, validation_rules[0], computed_fields[2] or <field>.input_type_rule.
  • One operation. A select_rule or a validation rule must be an object with exactly one key (90919). The engine reads anything else (a literal such as true, false, 0 or a string, an object with two keys) as a plain value, so the rule would never be evaluated: a value is not a rule. Computed fields and input_type_rule may be literals. An object with several keys is refused anywhere else in a rule as well (90923), since the engine reads it as a value too.
  • Argument counts. An operator given a number of arguments it does not take is refused (90921). The engine ignores an extra argument and reads a missing one as null, so {">=": [{"var": "n"}, 1, 10]} would drop the 10.
  • Literal arguments. A literal argument of the wrong kind is refused (90922), for example a date unit, part, pattern or duration the date operators do not take, a RACI letter other than the four, a throw_error code outside class 99 or a parameter list throw_error would refuse, or a permission, field or entity name that is empty or not text. An argument that is itself an operation is evaluated when the rule runs, and is not checked.
  • Variables with no value. A var that reads a name with no value where it is read is refused (90924): a $ name other than $today, $now, $user_id, $old and $mode, or, inside the logic of map, filter, reduce, all, none or some, any $ name or a name that a let or set_record outside the operator binds.
  • Renames. A field that any rule names cannot be renamed (90275): change the rule first, then rename. A field read through a set_record alias in another entity’s rule is not detected. Renaming an entity rewrites the entity argument of every set_record that names it in the computed_fields, validation_rules and select_rule of every entity, its own included. An input_type_rule is never rewritten.

The error names the rule’s place as 90909 does. For 90921 to 90924 its hint also carries path, the JSON pointer of the mistake inside the rule, such as /if/0/>=.

Unknown operators and the one-operation check (90909, 90919) run on every write of the entity or field, so an entity that already stores a rule failing them (restored from a dump, for example) cannot be saved again until the rule is fixed. The other checks (90921 to 90924, and the checks that a computed field’s name and a validation rule’s message are text, 90900 and 90903) run only on a rule that is new or changed. A rule stored before them keeps working and does not block the writes that leave it alone. A stored select_rule that is not one operation hides every row.

The rules of an entity with managed set to false are stored and checked like any other, but the database does not enforce them.


Built-in variables

These variables are automatically available inside computed_fields, validation_rules, and select_rule expressions. Access them with the standard var operator, e.g. {"var": "$now"}.

VariableDescription
$todayThe current date in UTC (no time component). Useful for date comparisons such as “expires before today”.
$nowThe current timestamp in UTC. Useful for stamping fields like submitted_at or comparing against a deadline.
$user_idThe id of the currently authenticated user. In computed fields and validation rules it is null when the expression runs outside a user session (for example during a background job).
$oldA snapshot of the record’s previous state, available on update and delete (where it holds the row being removed). null on insert. Use it to compare new vs. old values, e.g. {"!=": [{"var": "status"}, {"var": "$old.status"}]}.
$modeThe operation being performed: "insert", "update", or "delete". Use it to scope a rule to a particular operation, for example to forbid deletion with {"!=": [{"var": "$mode"}, "delete"]}.

Built-in variables are scoped to the record being evaluated. They are not written back to the record, they exist only for the duration of the expression. A field of the record with the same name is shadowed by the variable.

Availability by context

computed_fields and validation_rules run during a mutation and see all five variables. select_rule runs during a read and sees only $today, $now, and $user_id. $old and $mode are not bound in a select rule: a read has no previous image and is not a mutation, so they would be meaningless there. A select rule never sees a null $user_id: a read without a valid session is refused with a permission error (42501) before the rule runs.

Inside map, filter, reduce, all, none and some, var reads the element instead of the record (current and accumulator in reduce), so a field of the record is out of reach there. A rule that reads a $ variable, or a name an outer let or set_record binds, inside the operator’s logic is refused when it is saved (90924).

Evaluation on delete

validation_rules also run on delete, evaluated against the row being removed (bound as the root context, with $old set to that same row and $mode equal to "delete"). A rule that evaluates falsy aborts the delete, so a rule such as {"!=": [{"var": "$mode"}, "delete"]} forbids deletion outright. computed_fields still run on delete, but their output is discarded, since there is no surviving row to write it to. A statement that deletes many rows is judged one row at a time, and a single refusal aborts the whole statement.


Custom operators

Bind a local variable: let

Evaluates an expression once and exposes the result under a name for the body that follows.

Form: {"let": ["<name>", <value>, <body>]}

{
  "let": [
    "total",
    {"+": [{"var": "subtotal"}, {"var": "tax"}]},
    {">": [{"var": "total"}, 100]}
  ]
}

Use it to avoid recomputing the same sub-expression multiple times or to make complex rules more readable.


Fetches an entire record from another entity by its id and binds it to a name, then evaluates the body with that record available.

Form: {"set_record": ["<name>", "<entityName>", <idExpression>, <body>]}

{
  "set_record": [
    "customer",
    "customers",
    {"var": "customer_id"},
    {"==": [{"var": "customer.status"}, "active"]}
  ]
}

The lookup runs through the same access boundary as a normal read. The bound name resolves to null when the referenced record does not exist or when the current user does not have permission to view it. These two cases are deliberately indistinguishable, so a rule cannot use set_record to probe whether a record the caller is not allowed to see exists. Use dotted paths in var to read fields of the loaded record (e.g. {"var": "customer.email"}).

The id may be a number, text, a UUID or a TypeID, whatever the target entity’s key type is. A whole number produced by arithmetic, such as 5.0, is read as 5. An id that does not fit the key type raises 90238 for a caller who can see the entity in the catalog. Anyone else gets null, which is also what an unknown entity or a null id binds.


Check the current user’s permission: has_permission

Returns true when the current user holds the named permission, false otherwise. Without a valid session it raises a permission error (42501), and that is exactly when $user_id is null in a computed field or validation rule. The name may be an expression, such as {"var": "view_permission"}.

Form: {"has_permission": "<permission_name>"}

{"if": [
  {"has_permission": "orders:approve"},
  "approved",
  "pending_review"
]}

Enforce a permission: require_permission

Returns true when the current user holds the named permission, and raises a permission error (42501, hint code 90101) otherwise. The write is then refused with that error, not with the rule’s code and message; to return your own, use has_permission and let the rule fail. Use it inside an if, so the check applies only to the action it guards: a validation rule that is only require_permission refuses every insert, update and delete by a user without the permission.

Form: {"require_permission": "<permission_name>"}

Only holders of orders:delete_order may delete an order:

{"if": [
  {"==": [{"var": "$mode"}, "delete"]},
  {"require_permission": "orders:delete_order"},
  true
]}

Check the current user’s RACI role: is_raci_actor

Returns true when the current user holds a role assigned the given RACI letter for the process that governs an (entity, to_state) transition, and false otherwise. Without a valid session it raises a permission error (42501).

The RACI letter is one of responsible, accountable, consulted, or informed. The first two arguments name the governed table and the target lifecycle state; together they select the process gate, and the operator then checks the current user’s roles against that process’s RACI matrix.

Form: {"is_raci_actor": ["<entity>", "<to_state>", "<letter>"]}

{"if": [
  {"and": [
    {"==": [{"var": "status"}, "approved"]},
    {"!=": [{"var": "$old.status"}, "approved"]},
    {"!": {"is_raci_actor": ["orders", "approved", "accountable"]}}
  ]},
  {"throw_error": "Only the accountable approver can approve this order"},
  true
]}

Use it in validation_rules to gate a transition on the caller’s RACI role. The rule above refuses to move an order into approved, or to create one there, unless the caller holds the accountable role for that gate. It tests the move, not the state, so every other write passes, including edits of an order that is already approved and its deletion. It is the governance analog of has_permission for processes that are driven by a RACI matrix rather than a flat permission name.


Require that a RACI consultation occurred: has_consultation

The companion to is_raci_actor for the C (Consulted) letter of RACI. Where is_raci_actor checks who the caller is, has_consultation reports whether a consulted role has responded for the record.

Returns true when an acted consulted event already exists for the record in the process that governs an (entity, to_state) gate, that is, a raci_events row with raci = 'consulted' and status = 'acted', and false otherwise. A caller who holds no role with a RACI assignment on that process always gets false. Without a valid session it raises a permission error (42501). The third argument is the id of the record being gated, usually read from the current row with {"var": "id"}.

The operator only reports, and it ignores consult_mode. Holding a record back is the platform’s gate: when a record enters the state of a gate that emits events, every consulted and informed role of the process gets a pending event. While the event of a consulted role whose assignment has consult_mode = 'block' is not acted, an update of the record keeps its other changes but leaves each state column a gate governs at its stored value. A blocking consultation therefore holds the record’s next move, not the move into the state that raised it.

Form: {"has_consultation": ["<entity>", "<to_state>", <record_id>]}

{"if": [
  {"and": [
    {"==": [{"var": "$old.status"}, "approved"]},
    {"==": [{"var": "status"}, "shipped"]},
    {"!": {"has_consultation": ["orders", "approved", {"var": "id"}]}}
  ]},
  {"throw_error": "No consulted role has responded yet"},
  true
]}

Use it in validation_rules to hold up the record’s next move. With a gate on orders at approved that emits events, the rule above refuses to move an order from approved to shipped until a consulted role has acted on the consultation that entering approved raised. It tests the move, not the state, so every other write passes, the one that enters approved included. It covers what the platform’s gate does not: the gate holds the move only while a block consultation is not acted, and it runs before the rule, which then sees no move. A caller outside the process gets false, so only a participant can ship the order.


Detect a field change on update: value_changed

Returns true when the named field’s value differs from its previous value on update, and true on insert (treating a new record as “changed”). Returns false only when the field’s value is the same as before.

It reads a top-level field only: a dotted name such as settings.theme is not followed into a JSON column, so on an update it is always false. On delete it is false, since the row being removed is compared with itself, and in a select_rule, which has no $old, it is always true.

Form: {"value_changed": "<field_name>"}

{"if": [
  {"value_changed": "status"},
  {"throw_error": "Status changes require manager approval"},
  true
]}

Concatenate strings with SQL semantics: concat

Concatenates all arguments into a single string. null arguments become empty strings (mirroring SQL CONCAT), and non-string values (numbers, booleans, arrays, objects) become PostgreSQL’s text of their JSON value: [1, 2], {"a": 1}, and a stored decimal keeps its digits, as in 10.50.

Form: {"concat": [<value1>, <value2>, ...]}

{"concat": ["Order #", {"var": "id"}, " for ", {"var": "customer_name"}]}

In the database, concat and the standard cat give the same result.


Test a string against a regular expression: is_match

Tests whether a string value matches a regular expression pattern. Returns true on a match, false otherwise. null values always return false. A malformed pattern raises an error (2201B).

Form: {"is_match": [<value>, "<pattern>"]}

{"is_match": [{"var": "email"}, "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"]}

Useful in validation rules for format checks (email, phone, postal code, SKU prefix) without needing a separate constraint mechanism. The database matches with PostgreSQL regular expressions and the browser with JavaScript’s, so keep to the features both share: anchors, character classes, groups, alternation and quantifiers.


Move a date: date_add

Adds a whole number of units to a date, or an ISO 8601 duration. A negative amount subtracts. The result has the same type as the input: a date stays a date.

Form: {"date_add": [<date>, <amount>, "<unit>"]} or {"date_add": [<date>, "<duration>"]}

{"date_add": [{"var": "term_end"}, {"-": [0, {"var": "notice_period_days"}]}, "day"]}

Units are year, quarter, month, week, day, hour, minute, and second. A duration can come from a duration field or be written directly, such as "P1M2DT3H". Adding a month to the last days of a month lands on the end of the shorter month, so January 31 plus one month is February 28.

All date operators work in UTC, whatever the time zone of the session or browser. They accept ISO 8601 dates such as 2026-12-31 and 2026-12-31T10:00:00Z, and a date-time with no offset is read as UTC. A missing date or the empty string gives null, and so does a missing or empty date_add amount, so a record with no date can still be saved. Any other value is an error, and so is a time-based unit on a value with no time of day, except in date_diff, which also counts hours, minutes and seconds between two dates.

Computed fields run when a record is written. Store a date that depends on the record’s own fields, as above, rather than a count of days from $today, which would be out of date by tomorrow.


Measure between dates: date_diff

Returns the whole units that have elapsed from the second date to the first, as an integer truncated toward zero. It takes the units listed under date_add.

Form: {"date_diff": [<end>, <start>, "<unit>"]}

{"date_diff": [{"var": "term_end"}, {"var": "$today"}, "day"]}

A month counts only once the same day of the month has been reached again, so January 31 to February 28 is 0 months.


Read one part of a date: date_part

Returns one field of a date as an integer.

Form: {"date_part": [<date>, "<part>"]}

{"date_part": [{"var": "start_date"}, "quarter"]}

Parts are year, iso_year, quarter, month, week (ISO), day, weekday (Monday is 1), day_of_year, hour, minute, second, and epoch.


Find the start of a period: date_trunc

Returns the start of the period that contains a date. A week starts on Monday. It takes the units listed under date_add.

Form: {"date_trunc": [<date>, "<unit>"]}

{"date_trunc": [{"var": "invoice_date"}, "month"]}

For the last day of a month, truncate to the month, add one month, and subtract one day.


Get a calendar date: to_date

Returns the calendar date in UTC of a date, a date-time, or a number of seconds since 1970.

Form: {"to_date": <value>}

{"to_date": {"var": "submitted_at"}}

Format a date as text: date_format

Renders a date as text, for example in a computed label.

Form: {"date_format": [<date>, "<pattern>"]}

{"date_format": [{"var": "term_end"}, "Dy, DD Mon YYYY"]}

A pattern is made of YYYY, YY, Q, MM, Mon, Month, DD, Dy, Day, HH24, MI, and SS, with spaces or any of - / . : , between them. Month and day names are in English.


Raise a validation error: throw_error

Aborts the current operation with the given error message. Typically used as a branch of an if expression to enforce a business rule with a custom message.

Form: {"throw_error": "<message>"} or {"throw_error": ["<message>", "<code>", [<name>, <value>, ...]]}

{"if": [
  {"<": [{"var": "quantity"}, 1]},
  {"throw_error": "Quantity must be at least 1"},
  true
]}

The short form raises code 99000. The long form takes a code of your own and named parameters that a client can place into its own translated wording:

{"throw_error": [
  "Order ${id} is already shipped",
  "99017",
  ["id", {"var": "id"}]
]}
  • The code must lie between 99000 and 99999 (90911).
  • The parameters are a flat list of name, value, name, value. A list rather than an object, because JsonLogic would read {"id": 3} as a call of an operator named id. An odd-length list is refused (90914).
  • Each value is evaluated and keeps its JSON type, so a number arrives as a number and a client can pluralize or format it. A value must be a scalar, not an object or an array (90913).
  • hint, code, entity, rule and field are reserved names (90912).
  • The message is a template: ${id} names a parameter, and the client substitutes it.

Inside a validation rule the error also carries entity and rule (the rule’s code); inside a computed field, entity and field (the computed field’s name).


In the browser

The form in the Semantius app evaluates two kinds of rules in the browser, with the same operators and the same coercion rules as the database:

  • input_type_rule runs only there.
  • computed_fields run there as a live preview: when the user changes an input, the form recomputes the computed fields so they show their new values before the save. Opening a record does not recompute it. The server recomputes on every write, and its value is the one stored.

validation_rules and select_rule run only in the database.

The form also runs the server’s save-time checks on a field that holds a rule while it is edited: when the field loses focus, and on every keystroke after a first attempt to save. A mistake in a rule is then refused in the form before it reaches the server.

What differs in the browser:

  • $today, $now and $user_id are bound. Computed fields also get $old and $mode ("insert" or "update"); an input_type_rule gets neither.
  • $now is the browser’s clock when the rule runs, not the start of the database transaction.
  • Numbers are floating point in the browser and exact decimals in the database, so 0.1 + 0.2 shows 0.30000000000000004 while the user types, and 0.3 is stored.
  • is_match uses JavaScript’s regular expressions in the browser and PostgreSQL’s in the database. \b is a word boundary in the browser and a backspace in the database, where the word boundary is \y, and (?i) works only in the database.
  • set_record rows are fetched over the API as the signed-in user, so a record the user cannot see binds null, as it does on the server. Until the row has arrived, the rule is skipped.
  • is_raci_actor and has_consultation read the database and cannot run in the browser. They raise an error there when evaluation reaches them, and an input_type_rule then falls back to the static input mode. if, and and or evaluate only the arguments they need, so a branch that is not taken never reaches them.
  • A rule that throws leaves the computed field at its current value, or the field at its static input mode, and the form shows the error under the field, though not in view mode or on a hidden field. The error does not block saving.

A rollup field shown as a number has a link to the child records. The link filters by the link field only, not by the rollup’s filter, so the list can differ from the number shown.


Errors

Errors raised while a rule is saved or evaluated. Codes in the 90xxx range belong to the platform; your own rules raise 99xxx codes.

CodeRaised when
42501A permission error: require_permission fails (hint code 90101), or has_permission, is_raci_actor, has_consultation, a select_rule or set_record is evaluated without a valid session (90001, or 90002 to 90005 or 90009 for a token that is refused) or for a user with no enabled account (90006).
2201Bis_match is given a malformed pattern.
22008A date operator got a value shaped like a date that is no real date, such as 2026-02-30.
22009A date operator got a date-time whose offset is out of range, such as +99.
90238A set_record id does not fit the target entity’s key type.
90258A required field is missing, also when a computed rule produced no value for it.
90275A field that a rule names is renamed.
90900, 90901A computed_fields entry lacks its name or its jsonlogic, or its name is not text (90900).
90902, 90903, 90904A validation_rules entry lacks its code, message or jsonlogic, or its message is not text (90903).
90905A validation rule’s code is not between 99000 and 99999.
90906A platform validation rule ("source_module": "platform") carries a code outside class 90.
90907A computed_fields entry names a rollup field.
90908A changed computed rule cannot be applied to an existing record.
90909A rule names an unknown operator (at save time).
90910A rule stored without passing the save names an unknown operator (at evaluation time).
90911 to 90914throw_error got a code outside class 99, a reserved parameter name, a non-scalar parameter value, or an odd-length parameter list.
90915A date operator got a value that is not an ISO 8601 date or date-time.
90916A date unit or part is unknown, or needs a time of day the value does not have.
90917date_format got a pattern it does not support.
90918date_add got an amount that is neither a whole number nor an ISO 8601 duration.
90919A select_rule or validation rule is not a single operation.
90920Arithmetic has no finite result: division or % by zero, or an operand that is text carrying no number.
90921An operator is given a number of arguments it does not take (at save time).
90922A literal argument is of the wrong kind, such as an unknown date unit or RACI letter (at save time).
90923A rule holds an object with several keys (at save time). At the top of a select_rule or validation rule it is 90919.
90924A rule reads a variable that has no value where it is read (at save time).
99000 to 99999Your validation rules and throw_error calls.