Skip to content
Spools
Documentation
On this page

Database

Records and the CRM's own tables are kept through one port, the store. Server code asks it questions in terms of tables and conditions, never SQL or an ORM, so what is underneath is a choice you make in src/spool.server.ts.

Adapter When
pglite() Trying a Spool out, development, tests. Postgres inside the server process: nothing to install
postgres() Deployments. Any Postgres 15 or newer (tested on 17): Supabase, Neon, RDS, Fly, your own
prisma({ contract }) The same, through the Prisma 8 client, which is a release candidate today

All three pass the same integration tests, and postgres and prisma read and write the same tables.

PGlite#

ts
database: pglite(),                          // in .data/pglitedatabase: pglite({ dataDir: "memory" }),     // gone when the process ends

Its tables are made when it starts and kept up with the config from then on. It adds tables, columns and indexes, and never drops, renames or retypes a table or a column, so a field you remove from the config leaves its column behind. A required field added to an object that already has records is left empty on them. The one thing it removes is an index a table no longer declares: an index holds no data, and a unique one left behind would go on refusing rows the tables now allow. So a data directory made by an earlier version keeps working after an upgrade that changes what must be unique.

One process can open a data directory at a time. Stop the dev server before bun run db:seed, and use postgres() where several instances run.

Postgres#

ts
database: postgres(),                        // DATABASE_URL, or POSTGRES_URLdatabase: postgres({ maxConnections: 20 }),
  • DATABASE_URL wins. Without it POSTGRES_URL is used, which Supabase's and other hosting integrations set.
  • sslmode=require in the URL means TLS with the certificate checked. sslmode=no-verify is TLS without checking it. POSTGRES_URL with require is relaxed to no-verify, because the Supabase pooler's chain isn't one a client trusts.
  • On Supabase's transaction pooler (port 6543) prepared statements are turned off. Use the session pooler or a direct connection for migrations.

Schema and migrations#

bun run crm:gen writes prisma/schema.prisma from crm.config.json, the system tables, and any tables your adapters keep. An object has a table, and so has each relations field that owns its links: <object>_<field>, with source_id and target_id, one row per pair, and a foreign key on each that deletes the row with either record. Prisma's CLI migrates a Postgres from it, whichever adapter the server uses:

sh
bun run db:push                       # development: make the database matchbun run db:plan -- --name add-tier    # production: write a migrationbun run db:migrate                    # and apply it

Every table has row-level security on with no policies, and spools harden (which db:push and db:migrate run) takes Supabase's Data API roles off them. The app connects as a privileged role.

Uniqueness rules#

An object's unique rules are unique indexes in the database, partial when a rule has where:

sql
CREATE UNIQUE INDEX "visits_oneOpenVisit_<hash>" ON "public"."visits" ("member", "job_id")  WHERE "checked_out_at" IS NULL

PGlite makes them from the config as it starts (packages/spools/src/server/store/schema-sql.ts), and the Prisma schema has them as @@index([member, jobId], unique: true, where: sql`"checked_out_at" IS NULL`, name: "visits_oneOpenVisit") (packages/spools/src/crm/codegen.ts), which Prisma 8 applies to Postgres: Prisma's PSL has no partial @@unique, but its @@index takes unique and a where predicate, and names the index <name>_<hash of what it says>. Both are made from one function (conditionSql), so the two say the same WHERE. A rule that changes is a new index under a new name; the old one is dropped (by Prisma's migration, or by PGlite as it starts).

The data layer looks for a clash before it writes and refuses it as a Conflict. The index is what holds when two writes race past that look, and the write it refuses is said as the same Conflict (clashOr in packages/spools/src/server/record-rules.ts, which asks again once the failed transaction is undone). Code that catches DatabaseError for one of the CRM's own unique indexes (synced emails, sequence runs) is unchanged: those are system tables.

Adding or changing a rule on a database that has records. Postgres won't make a unique index over rows that already share values, so check first:

sh
bun run crm:genbunx spools rules             # lists each group of records that breaks a rule, by id# put them right: change or delete all but one of each, then run it againbun run db:push               # developmentbun run db:plan -- --name unique-visits && bun run db:migrate   # production

spools rules reads the config on disk, so run it after the edit and before the migration. It exits non-zero while any rule is broken. PGlite starts all the same over records that break a rule: it says so in a warning, makes the rest, and the data layer keeps the rule for new writes until the records are put right and the server restarts. Removing a rule drops its index and loses no data.

Change signals#

change_signals holds a "last changed" mark for each object and each record (packages/spools/src/server/signals.ts): a key (jobs, jobs:<id>) and a stamp made anew on every change. The data layer touches it after every create, change and delete of a record, and every activity, task and note on one: once the change is kept (afterCommit in store/store.ts, which runs work when the outermost transaction commits, never when it is undone), and never in a way that can fail the change. A page asks whether its keys moved with one read of an indexed table (Live updates). The table grows by a row per record ever changed, and is safe to empty: a page that finds its mark gone simply reloads once.

Record scopes#

Seven system tables (activities, tasks, notes, favorites, record_folders, file_uploads, sequence_runs) have a nullable scope column with an index on it: a copy of the scope of the record each row hangs off. It is empty and unused unless crm.config.json has scopes, and an object named there gets an index on its scope field. Upgrading to the version that added them is one schema change and no data change: bun run crm:gen, then bun run db:push in development, or bun run db:plan -- --name record-scopes and bun run db:migrate for a production database. When you turn scopes on, bun run db:scopes fills the column in for rows that were already there, and puts it right again after any change to which objects are scoped.

Scopes are kept by a guard every store is behind (packages/spools/src/server/store/scope.ts), so an adapter you write inherits them by building its store with makeStore. Code with nobody signed in reaches a scoped table only inside asSystem(...), and changes a record of any object, a shared one included, only there too.

The guard hands your backend the query already narrowed. One part of that is in the order: a sort by a related record's column (['company', 'name']) reaches a backend as { related: ['company', 'name'], where } when the related object is scoped, and a row whose related record doesn't meet where must sort as a row with no related record. A backend built on sqlBackend gets this from selectSql. One that writes its own ORDER BY has to write the condition too, or refuse the order: never drop the condition and sort by the bare column. The Prisma adapter writes the same subselect through relatedOrderText, for a related column of any kind (a record's title can be a field of any type), and the scope tests run it against a real database.

A store call can fail with ScopeRefused as well as DatabaseError: the guard refusing it, in words for staff. It is a failure of its own, so Effect.catchTag('DatabaseError', ...) written for a unique index never takes a refusal for a row that was already there.

The guard also asks more of some writes than a store without scopes does. A row that points at a scoped record holds that record (lock) until the row is written, a link of a many-to-many relation holds each scoped record it joins until it is written, and deleting a record that scoped records point at or are linked to holds it while they are counted, so all of these are transactions. Your backend's lock must be a real row lock (SELECT ... FOR UPDATE) for these to mean anything with more than one connection.

A links table (contacts_tags) has no scope column: a link belongs to the scope of each scoped record it joins, so the guard narrows it through its two relations, with the some condition every backend already answers. A links table with a scoped object at either end refuses a call with nobody said, like a scoped object's table.

A read of the first rows of each group (perGroup) is narrowed like any other find: the scope is part of the condition your backend is handed, and the cut comes after the conditions, so a person gets the first rows of each group that they can reach, never rows or gaps shaped by ones they can't. A count beside it (countValues) is narrowed the same way. This is why a backend must never cut the groups before it applies the condition, or read every row and cut afterwards. selectSql writes the condition inside the statement that numbers the rows, and the scope tests check it on every store that ships.

Rows are held in one order everywhere (inHoldOrder in store/hold.ts): records first, table by table in the order of the tables' names and within a table by primary key, then the rows of links tables, table by table in the same way. Creating, changing and deleting a record hold through it (holdRecords and holdLinks in records.ts), and so does the guard, for the record a row points at, the records a link joins, and a record that moves scope or is deleted. With scopes, a change also holds the scoped records its relation fields point at, with everything else and in that order, so what the guard holds afterwards is held already. Code of your own that holds rows of several tables in one transaction should take them with holdAll from the same file, or two changes can each end up waiting for the other.

Using the store#

Server code in the framework, and an adapter that keeps its own tables, reach the database like this:

ts
import { asc, contains, or } from '../server/store/query'import { Store } from '../server/store/store'import { Task } from '../server/store/tables'const store = yield * Storeconst open =  yield *  store.find(Task, {    where: { assigneeId: user.id, completedAt: null },    filter: or(contains('title', 'call'), contains('title', 'email')),    order: [asc('dueDate', 'last')],    limit: 50,  })

where is columns that must equal a value, and null means empty. filter is anything else: comparisons, text, relations, full-text search (packages/spools/src/server/store/query.ts). A links table is a table like any other (linkTables and linkSide in store/objects.ts): each object's table has a relation to its rows of it, so "has this tag" is some('tagsLinks', eq('targetId', id)), with no condition of its own for an adapter to learn. A row's TypeScript type follows from its table, and update, remove and lock refuse to run with no condition of the caller's own, whoever is asking.

The first rows of each group#

perGroup asks for no more than so many rows for each value of a column, in one read:

ts
// The three tasks due soonest for each of these people.const soonest =  yield *  store.find(Task, {    filter: oneOf('assigneeId', people),    order: [asc('dueDate', 'last'), asc('id')],    perGroup: { by: 'assigneeId', limit: 3 },  })
  • The rows that share a value of by are a group, and rows with nothing in that column are a group too.
  • order settles which rows are a group's first. End it with a column that leaves no ties (the id), or which of two equal rows comes back is the database's choice.
  • The rows come back in order, all groups together, and limit and offset then count those rows. where, filter, select and include mean what they always do.

Use it where the alternative is one query for each row of a page. A list of fifty tags reads the first hundred contacts of each this way: two reads of the links table (how many each tag has, then these rows) whether a tag has three contacts or thirty thousand. The answer is bounded, at the limit times the number of groups. The work the database does is not: it passes over every row that matches, as a count does, so keep the conditions to the groups you are showing.

Writes that belong together go in a transaction: everything in it is kept, or none of it.

ts
const record =  yield *  store.transaction(    Effect.gen(function* () {      const made = yield* store.insert(Invoice, values)      yield* store.insert(InvoiceLine, { invoiceId: made.id, ...line })      return made    }),  )

A failure, a bug or the request going away undoes what the program had written. Inside one, store.lock(table, { where: { id } }) holds a row until the transaction ends, so reading a row and then writing something that depends on it can't be interleaved with someone else doing the same. One call takes its rows in the order of their ids. A transaction that holds rows of several tables must take the tables in the same order as every other that holds the same rows, or two of them can each wait for the other. There is one order (store/hold.ts), which everything that writes links and the scope guard both go by: table name, then id. First the records (holdRecords in records.ts): a change holds its record and the records it names, a new record the records it names, a delete its record. Then the links whose other end is not among those (holdLinks): the ones a list that replaces lets go of, and all of a deleted record's. Only then is anything written. On Postgres a statement that fails ends its transaction, so inside one a unique index is not something to run into and catch: hold what the new row depends on, look for it, then add it. Creating, changing and deleting a record are each a transaction: a record is never saved without its line on the timeline. Keep a transaction to store calls: code that reaches the store some other way (an app's hook) is on another connection and doesn't see what isn't kept yet.

Your own code in src/app/extensions.ts uses the promise functions instead (Extending): createRecord, listRecords and the rest run hooks, the timeline and automations, which the store knows nothing about.

Tests#

sh
bun run test:integration                                  # PGlite, nothing to set upTEST_STORE=postgres DATABASE_URL=... bun run test:integrationTEST_STORE=prisma   DATABASE_URL=... bun run test:integration

Point DATABASE_URL at a database made for tests, with the schema pushed (bun run db:push in apps/starter). The tests write to it.

The tests of record rules, role access and change signals (rules.test.ts, role-access.test.ts, signals.test.ts), an app's own door (door*.test.ts, idempotency.test.ts, rate-limits.test.ts) and modules (modules.test.ts, module-rules.test.ts) run on Spools of their own, on the store TEST_STORE names (packages/spools/tests/support/fixture-store.ts). On a real Postgres each has a database of its own beside the one DATABASE_URL names, with its name after it (_rules, _door, _modules, _module_rules), on the same server. The tests make it if it isn't there, empty it, and push the Spool's schema to it as an app's is: the Prisma schema spools gen would write (modules' objects and private tables in it, uniqueness rules as partial unique indexes), its contract emitted, and prisma db update. The Prisma projects are written to packages/spools/tests/fixtures/stores (not committed). Claims and limits that must hold across servers (idempotent requests, the database rate limiter, uniqueness rules) are raced from several runtimes at once, each with a pool of its own (tests/support/servers.ts).

The record-scope tests (scopes-*.test.ts) run on a Spool of their own, whose config is not the starter's, so on a real Postgres they use a second database: the one DATABASE_URL names with _scopes after it (spools_test_scopes), on the same server. They make it if it isn't there, push their schema to it with Prisma (packages/spools/tests/fixtures/scoped/prisma, written by bun run test:scopes:gen in packages/spools) and empty it at the start of each run. On a server where the tests may not create a database, make one yourself and name it with TEST_SCOPES_DATABASE_URL.

The tests of many-to-many relations have a config of their own (packages/spools/tests/fixtures/relations.config.json), and so a database of their own on Postgres: the one DATABASE_URL names with _relations after it, on the same server. Make it and push that config's schema to it before a run on postgres or prisma:

sh
DATABASE_URL=... bun run --cwd packages/spools db:push:relations

It creates the database if it isn't there, writes the fixture's Prisma schema and contract (not committed) and pushes them. Those tests empty that database's records each time they start.