Ulabase

Your data

Constraints

A constraint is a rule about a whole collection, such as no negative balance or no double booking; every write that would break it is refused.

A constraint is a rule about your data that looks at the whole collection. A schema checks one document at a time. A constraint is checked against all the documents of the collection, on every write.

Use it for rules that no single document can express: no account balance below zero, no two orders holding the same seat, never more stock committed than exists.

What you get:

  • Rules no client can break. A write that would break a constraint is refused by the service, whoever sends it.

  • Rules written once. A constraint is a pipeline saved with the collection, so your app does not repeat the check.

The Constraints page: what a constraint costs

How a constraint is written

You write an aggregation pipeline that searches for trouble, then say whether finding something means the rule holds or breaks.

Field Meaning

Name

Identifies the rule, unique within the collection. It comes back in the error, so make it readable: noNegativeBalance.

Message

Returned to whoever made the write. Write it for them: an account balance cannot be negative.

The rule holds when the pipeline returns

nothing: the pipeline looks for what must not exist. something: the pipeline looks for what must exist. In a setup file the two are holdsWhen: 'empty' and holdsWhen: 'notEmpty'.

Pipeline stages

The pipeline itself, a JSON array. It runs against the collection after the write, inside the same transaction.

Most rules are the nothing kind: look for the forbidden state, and the rule holds as long as the search comes back empty.

[
  { "$match": { "balance": { "$lt": 0 } } }
]

Save that as noNegativeBalance with holds when set to nothing, and no write can leave a negative balance behind.

A constraint’s pipeline takes no parameters. The rule is checked on every write, whoever made it, so there is no request to take a value from and $var and $ifvar have no effect. The editor hides Add pagination and the variables guide for the same reason.

Constraints are stored in the collection’s metadata under constraints, the same way aggregations are stored under aggrs.

A constraint’s pipeline follows the rules of an aggregation, so the stages that reach other collections are refused: $lookup, $graphLookup and $unionWith, as well as $out and $merge. A constraint can check only the documents of its own collection.

Add a constraint

  1. Expand the collection.

  2. Click Add constraint.

  3. Fill in name, message, when the rule holds, and the pipeline.

  4. Click Test to try the pipeline against the data you have now (see below).

  5. Click Create.

An empty pipeline is refused: it would match everything, which is never what a rule means.

Check a rule before you save it

Test runs the rule’s pipeline against the collection as it stands and gives the answer in the rule’s terms:

  • The data you have satisfies this rule: nothing to fix.

  • These documents already break the rule: a write would now be refused because of exactly these documents.

  • The rule is not satisfied: the pipeline found nothing: for a something rule, the thing that must exist is missing.

Do this before saving. A rule saved against data that already breaks it will refuse writes that have nothing to do with the offending documents.

Turn a rule off

Each rule has a Disable button. While you investigate, disable the rule: the definition is kept, and Enable turns it back on.

What it costs, and what your app must do

A collection with at least one enabled constraint is written inside a transaction. Every write to it is checked against every enabled rule and rolled back if one is violated.

Your client code has to handle one consequence: two concurrent writes to the same collection can conflict. The one that loses is refused with 409 Conflict and is not applied. Send it again as it was.

A violated rule is also a 409, and retrying it only repeats the answer. The body tells the two apart:

Body Meaning

"retryable": true

A write conflict. Nothing was applied. Send the same request again.

"constraint": "<name>"

A rule was violated, with the offending documents in violations. Retrying will not help.

Nothing else sets retryable, so the whole check is one line:

const res = await fetch(url, { method: 'POST', body, headers });

if (res.status === 409) {
  const error = await res.json();

  if (error.retryable) {
    // another write changed the same data at the same moment: send the request again
  } else {
    // the write breaks a rule: error.constraint is its name, error.violations the documents that break it
  }
}

Retry with a short backoff and a few attempts. A conflict that keeps repeating means contention: look at what is writing to the collection.

Do it from the command line

You can keep your constraints in git and apply them with ulabase setup. The step below adds a rule to accounts that refuses a negative balance. The rules of a collection are its constraints list, and the step replaces only its own rule, found by name:

import { defineSetup, step } from '@ulabase/cli';

// the rule holds when the pipeline finds no account with a negative balance
const noNegativeBalance = {
  name: 'noNegativeBalance',
  message: 'an account balance cannot be negative',
  holdsWhen: 'empty',
  stages: [{ $match: { balance: { $lt: 0 } } }],
};

// read the rules saved in the settings of accounts
const constraints = async (service: any): Promise<any[]> =>
  (await (await service.fetch('/accounts/_meta')).json()).constraints ?? [];

export default defineSetup('Accounts rules', [
  step('noNegativeBalance constraint', {
    async check({ service }) {
      // the rule is up to date when its stages and message match
      const found = (await constraints(service)).find(c => c.name === noNegativeBalance.name);
      return JSON.stringify(found?.stages) === JSON.stringify(noNegativeBalance.stages)
          && found?.message === noNegativeBalance.message;
    },
    async apply({ service }) {
      // keep the other rules, and replace this one
      const others = (await constraints(service)).filter(c => c.name !== noNegativeBalance.name);
      await service.fetch('/accounts', {
        method: 'PATCH',
        body: JSON.stringify({ constraints: [...others, noNegativeBalance] }),
      });
    },
  }),
]);

With holdsWhen: 'empty' the rule holds when the pipeline finds nothing; notEmpty is the opposite. "enabled": false turns a rule off.

The service checks the rules when the step writes them: a duplicate name or an empty pipeline fails with 400. Run the pipeline as an aggregation first. If your data already breaks the rule, every write is refused.

  • Aggregations: the same pipeline editor, for pipelines you expose as endpoints

  • Schemas: validates one document’s shape, which a constraint does not do

  • Indexes: a unique index is the cheap rule across documents, when uniqueness is all you need