---
doc-schema-version: 1
summary: "Rules for code that touches SQL, database workers, transactions, integrity checks, or DB-backed caches"
read_when:
  - Changing SQL, database workers, or transactions
  - Adding an integrity check or a DB-backed cache
title: "Database code change rules"
---

Shared-state read producers hand over commands that remain unchanged until completion.
Fresh selectors and registry-owned immutable topology need no transport copy or
immutability scan. A producer borrowing mutable arrays, records, or configuration
captures them before handing the command to the reader; native worker messaging
still serializes the command. Capture before lazy snapshot preparation can yield.

- Kysely for ordinary SQLite; raw SQL only for schema, migrations, bootstrap, justified primitives. Write transactions synchronous: plan async work first, reread authoritative rows, then write; no Promise or `await` in transaction callbacks.
- Database access: worker threads (read-only worker scope, SQLite writer broker), never Gateway main thread; main thread only awaits results and installs published facts. Exceptions: boot admission, migrations, Doctor/CLI one-shots, lock primitives. Existing main-thread access = legacy: never add more; migrate what you touch.
- SQLite format/schema/integrity/index/table checks: once per physical DB per process load, shared across workers/handles; never add repeats, remove when touched. Clean-close seals skip startup validation; Doctor/explicit verification keep checks. [Lifecycle](/reference/database-schemas/integrity-and-recovery#integrity-checks).
- Gateway owns every DB/state; writer receipts invalidate caches, uncovered reads stay direct. No foreign-commit probes; remove when touched. Outside writers use Gateway or exclusive offline custody. Keep live authority/snapshots; [contract](/reference/database-schemas/integrity-and-recovery#gateway-database-ownership).

[Database access in workers](/reference/database-schemas/worker-access) describes the worker owners these rules apply to.
