@orkestrel/scaffold 0.0.135 → 0.0.136
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +167 -4
- package/dist/agents/skills/orkestrel-publish/scripts/wave.js +20 -5
- package/dist/bin/main.js +3 -3
- package/dist/host/AGENTS.md +1 -1
- package/dist/host/agents/orchestration.md +2 -2
- package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +201 -8
- package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +24 -5
- package/dist/host/claude/agents/orkestrel.md +7 -7
- package/dist/host/claude/agents/reviewer.md +1 -1
- package/dist/host/claude/rules/documentation.md +1 -1
- package/dist/host/claude/rules/patterns.md +2 -2
- package/dist/host/claude/rules/workspace.md +9 -4
- package/dist/host/configs/helpers.ts +21 -6
- package/dist/host/guides/contract.md +198 -163
- package/dist/host/guides/database.md +760 -300
- package/dist/host/guides/indexeddb.md +80 -66
- package/dist/host/guides/relation.md +56 -32
- package/dist/host/guides/scaffold.md +8 -2
- package/dist/host/guides/sqlite.md +44 -23
- package/dist/host/guides/test.md +7 -3
- package/dist/host/manifest.json +19 -19
- package/dist/host/scripts/browsers.sh +0 -0
- package/dist/host/scripts/codex.sh +0 -0
- package/dist/host/scripts/cursor.sh +0 -0
- package/dist/host/scripts/deps.sh +0 -0
- package/dist/host/scripts/npm.sh +0 -0
- package/dist/host/scripts/ollama.sh +0 -0
- package/dist/host/tests/config.test.ts +71 -3
- package/dist/src/core/index.cjs +103 -26
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +31 -5
- package/dist/src/core/index.d.ts +31 -5
- package/dist/src/core/index.js +103 -27
- package/dist/src/core/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Database
|
|
2
2
|
|
|
3
|
-
> One typed database API for keyed rows, fluent queries, cursors, and
|
|
4
|
-
>
|
|
5
|
-
>
|
|
3
|
+
> One typed database API for keyed rows, batches, fluent queries, cursors, and
|
|
4
|
+
> transactions, running unchanged over an in-memory map, a JSON file, SQLite, or
|
|
5
|
+
> IndexedDB.
|
|
6
6
|
|
|
7
7
|
A table is a contract. Declare a `tables` map of
|
|
8
8
|
[`ContractShape`](contract.md)s once, and the row type, write-time admission,
|
|
@@ -10,8 +10,8 @@ JSON-Schema introspection, and seed data all flow from that one
|
|
|
10
10
|
declaration — no separate schema, no annotations, no `as`.
|
|
11
11
|
|
|
12
12
|
The design stance is native first, under the rule Contract invariant 3 places. A backend
|
|
13
|
-
implements keyed read/write/insert/delete,
|
|
14
|
-
`
|
|
13
|
+
implements keyed read/write/insert/delete, each with a list overload that applies every row
|
|
14
|
+
or none, an ordered `scan`, and key listing, and declares through `plan` which part of each read its engine answers; the
|
|
15
15
|
core's engine runs only the residual. A backend without `plan` inherits the whole WHERE /
|
|
16
16
|
order / page / aggregate surface from that engine over `scan`.
|
|
17
17
|
So this is deliberately not an ORM and not a query abstraction layer: there is
|
|
@@ -23,8 +23,8 @@ persistent drivers ship alongside it: a trusted-mode SQLite driver in
|
|
|
23
23
|
[`src/server`](../src/server) (surfaced through `@orkestrel/database/server`)
|
|
24
24
|
with native querying, paging, counting, aggregation, transactions, and atomic migration,
|
|
25
25
|
and an IndexedDB driver in [`src/browser`](../src/browser)
|
|
26
|
-
(surfaced through `@orkestrel/database/browser`) whose plan answers one
|
|
27
|
-
|
|
26
|
+
(surfaced through `@orkestrel/database/browser`) whose plan answers one ranked access path
|
|
27
|
+
over the primary key or an index, with its order, page, and count — beside the I/O-free `MemoryDriver` and the
|
|
28
28
|
file-persisted `JSONDriver`, whose reads the core answers over `scan`.
|
|
29
29
|
|
|
30
30
|
## Surface
|
|
@@ -71,27 +71,31 @@ produces the JSON Schema, and seeds fixtures.
|
|
|
71
71
|
|
|
72
72
|
### Factories
|
|
73
73
|
|
|
74
|
-
| Name | Kind | Signature | Summary
|
|
75
|
-
| ----------------------- | -------- | --------------------------------------------------------------------------------- |
|
|
76
|
-
| `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema.
|
|
77
|
-
| `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`.
|
|
78
|
-
| `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path.
|
|
79
|
-
| `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) =>
|
|
80
|
-
| `createIndexedDBDriver` | function | `(name: string) => DriverInterface` | Creates a persistent IndexedDB `DriverInterface` for a browser database name.
|
|
74
|
+
| Name | Kind | Signature | Summary |
|
|
75
|
+
| ----------------------- | -------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
76
|
+
| `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema. |
|
|
77
|
+
| `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`. |
|
|
78
|
+
| `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path. |
|
|
79
|
+
| `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) => SQLiteDriverInterface` | Creates a trusted-mode, server-native SQLite `SQLiteDriverInterface` for a database path, or for `:memory:` when explicitly requested. |
|
|
80
|
+
| `createIndexedDBDriver` | function | `(name: string) => DriverInterface` | Creates a persistent IndexedDB `DriverInterface` for a browser database name. |
|
|
81
81
|
|
|
82
82
|
### Classes
|
|
83
83
|
|
|
84
|
-
| Name
|
|
85
|
-
|
|
|
86
|
-
| `Database`
|
|
87
|
-
| `DriverIterator`
|
|
88
|
-
| `
|
|
89
|
-
| `
|
|
90
|
-
| `
|
|
91
|
-
| `
|
|
92
|
-
| `
|
|
93
|
-
| `
|
|
94
|
-
| `
|
|
84
|
+
| Name | Kind | Signature | Summary |
|
|
85
|
+
| ------------------------ | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
86
|
+
| `Database` | class | `new <T extends TableMap = TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Exposes a typed view over one shared internal lifecycle and storage context. |
|
|
87
|
+
| `DriverIterator` | class | `new <T>(source: AsyncIterator<T>, guard: () => void) => AsyncIterableIterator<T>` | Forms the internal continuation boundary for a root driver async iterator. |
|
|
88
|
+
| `ScopedStorage` | class | `new (source: StorageInterface, guard: () => void) => StorageInterface` | Forms the lifetime boundary of a driver's scoped storage: each member runs the guard, then forwards to the storage it wraps. |
|
|
89
|
+
| `StorageJournal` | class | `new (source: StorageInterface) => StorageJournalInterface` | Records the prior row of each key a scope writes or deletes, on its first touch, and restores those keys on request — the transaction floor for a driver without `transaction`. |
|
|
90
|
+
| `MemoryDriver` | class | `new () => DriverInterface` | Implements the reference `DriverInterface` — nested maps, no I/O. |
|
|
91
|
+
| `JSONDriver` | class | `new (path: string) => DriverInterface` | Implements a persistent `DriverInterface` backed by a single JSON file — the reference `MemoryDriver` plus file load / flush. |
|
|
92
|
+
| `SQLiteDriver` | class | `new (options: SQLiteDriverOptions) => SQLiteDriverInterface` | Implements the `SQLiteDriverInterface` over SQLite — the server-native, trusted-mode backend built on the published `@orkestrel/sqlite` synchronous wrapper. |
|
|
93
|
+
| `IndexedDBDriver` | class | `new (name: string) => DriverInterface` | Implements the `DriverInterface` over IndexedDB — the persistent browser backend, built on the published `@orkestrel/indexeddb` wrapper. |
|
|
94
|
+
| `IndexedDBBatchIterator` | class | `new (read: (position: AccessPosition \| undefined, size: number) => Promise<AccessBatch>, limit?: number) => AsyncIterableIterator<readonly Row[]>` | Iterates the batches of one stream, each read by its own call, past the position the previous batch reports, up to a total row limit. |
|
|
95
|
+
| `StreamPage` | class | `new (offset: number) => StreamPageInterface` | Tracks the matching-row position of one streaming page. |
|
|
96
|
+
| `JSONTransaction` | class | `new (memory: MemoryDriver, schema: readonly TableSchema[], identities: ReadonlyMap<string, object>) => JSONTransaction` | Owns the isolated memory store and schema of one JSON transaction. |
|
|
97
|
+
| `SQLiteTransaction` | class | `new (schema: ReadonlyMap<string, TableSchema>, identities: ReadonlyMap<string, object>) => SQLiteTransaction` | Owns the candidate schema and table identities of one SQLite transaction. |
|
|
98
|
+
| `SQLiteConnection` | class | `new (database: SQLiteDatabaseInterface) => SQLiteConnection` | Owns one open SQLite connection of the SQLite driver and the prepared statements it reuses, keyed by SQL text and bounded by `STATEMENT_LIMIT` with least-recently-used eviction. |
|
|
95
99
|
|
|
96
100
|
### Server
|
|
97
101
|
|
|
@@ -99,9 +103,11 @@ produces the JSON Schema, and seeds fixtures.
|
|
|
99
103
|
| ------------------------ | -------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
100
104
|
| `METADATA_TABLE` | const | `"_metadata"` | Names the reserved metadata table the `SQLiteDriver` creates on `open` to persist its stamped `DriverMetadata` (`version` + declared schema JSON) — the SQLite realization of the `metadata` / `stamp` driver hooks. |
|
|
101
105
|
| `PRAGMA_NAMES` | const | `readonly string[]` | Lists the PRAGMA names the `SQLiteDriver` admits in its `pragmas` option, each matched exactly; it refuses every other name, because one can change a read result the planner assumes. |
|
|
102
|
-
| `
|
|
106
|
+
| `STATEMENT_LIMIT` | const | `256` | Bounds the prepared statements one `SQLiteConnection` keeps, evicting the least recently used past it. |
|
|
107
|
+
| `validatePragmas` | function | `(pragmas: Readonly<Record<string, string \| number>> \| undefined) => void` | Validates the `pragmas` option of the SQLite driver: each name must pass `isPragmaName` and be one of `PRAGMA_NAMES`, matched exactly, and each value must pass `isPragmaValue`. |
|
|
103
108
|
| `planSQLiteQuery` | function | `(input: ReadInput, schema: TableSchema) => ReadPlan` | Splits a read into the part SQLite answers natively and the residual the core runs — the SQLite driver's `plan`. |
|
|
104
109
|
| `matchesSQLiteCondition` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether SQLite answers one `Condition` with the core engine's meaning. |
|
|
110
|
+
| `matchesSQLitePrefilter` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether SQLite applies a superset form of one `Condition` that the core then rechecks: `equals`, `not`, `any`, or `none` on a nested path under a declared `json` head, with scalar operands. |
|
|
105
111
|
| `findSQLiteColumn` | function | `(path: FieldPath, schema: TableSchema) => ColumnSchema \| undefined` | Resolves the declared column a field path names when SQLite answers it natively: a flat path to a declared `text`, `integer`, `real`, or `boolean` column. |
|
|
106
112
|
| `matchesPrimaryPin` | function | `(conditions: readonly Condition[], schema: TableSchema) => boolean` | Reports whether a WHERE fold pins its column references: every connector is `and` and one condition is `any` on the primary key. |
|
|
107
113
|
| `computeSuccessor` | function | `(prefix: string) => string \| undefined` | Computes the least text above every text that starts with a prefix, in code-point order — the exclusive upper bound of the `starts` range. |
|
|
@@ -115,50 +121,67 @@ Pure, server-only functions that turn a core `QueryInput` / `TableSchema` into
|
|
|
115
121
|
parameterized SQL text — the native-query payoff for a SQLite-backed driver.
|
|
116
122
|
None of these import a SQLite package; they speak strings and values only.
|
|
117
123
|
|
|
118
|
-
| Name | Kind | Signature | Summary
|
|
119
|
-
| ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
120
|
-
| `inferValueStorage` | function | `(value: unknown) => ColumnStorage` | Reads the storage type a nested (`json_extract`) operand encodes as from its runtime value, never as `json`.
|
|
121
|
-
| `
|
|
122
|
-
| `
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
125
|
-
| `
|
|
126
|
-
| `
|
|
127
|
-
| `
|
|
128
|
-
| `
|
|
129
|
-
| `
|
|
130
|
-
| `
|
|
131
|
-
| `
|
|
132
|
-
| `
|
|
133
|
-
| `
|
|
134
|
-
| `
|
|
135
|
-
| `
|
|
136
|
-
| `
|
|
137
|
-
| `
|
|
138
|
-
| `
|
|
139
|
-
| `
|
|
140
|
-
| `
|
|
141
|
-
| `
|
|
142
|
-
| `
|
|
143
|
-
| `
|
|
124
|
+
| Name | Kind | Signature | Summary |
|
|
125
|
+
| ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
126
|
+
| `inferValueStorage` | function | `(value: unknown) => ColumnStorage` | Reads the storage type a nested (`json_extract`) operand encodes as from its runtime value, never as `json`. |
|
|
127
|
+
| `inferSentinelType` | function | `(storage: ColumnStorage \| undefined) => 'blob' \| 'text'` | Reads the SQLite storage class of the sentinel a column that is both optional and nullable stores for explicit `null`. |
|
|
128
|
+
| `compileJSONTypeSQL` | function | `(path: readonly string[]) => string` | Compiles a nested `FieldPath` to the SQL expression that reads the JSON type at the path, through `compileJSONAccessSQL`. |
|
|
129
|
+
| `compileConditionSQL` | function | `(condition: Condition, schema: TableSchema, pinned?: boolean) => CompiledSQL` | Compiles one condition to its SQL fragment and the parameters it binds, with the core engine's meaning under SQL's three-valued `NULL` logic. |
|
|
130
|
+
| `compileNestedSQL` | function | `(condition: Condition) => CompiledSQL` | Compiles an `equals`, `not`, `any`, or `none` condition on a nested path to a form that tests the JSON type the path holds beside its value. |
|
|
131
|
+
| `compileWhereSQL` | function | `(conditions: readonly Condition[], schema: TableSchema) => CompiledSQL` | Folds the conditions into one WHERE clause, parenthesizing progressively left-to-right so the grouping matches the engine's `matchesQuery` fold. |
|
|
132
|
+
| `compileOrderSQL` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, pinned?: boolean) => string` | Compiles the ORDER BY clause from the order terms, ending with the primary key in the direction of the final term. |
|
|
133
|
+
| `compilePageSQL` | function | `(limit: number \| undefined, offset: number \| undefined) => CompiledSQL` | Compiles the LIMIT / OFFSET clause. |
|
|
134
|
+
| `compileQuerySQL` | function | `(input: QueryInput \| undefined, schema: TableSchema) => CompiledSQL` | Compiles a `QueryInput` into the SQL clause that follows a table name, with its bound parameters in clause order. |
|
|
135
|
+
| `compileInsertSQL` | function | `(schema: TableSchema, replace: boolean) => string` | Compiles the statement that inserts one row of a table, binding one parameter per declared column in schema order. |
|
|
136
|
+
| `quoteIdentifier` | function | `(identifier: string) => string` | Quotes a SQL identifier (a table or column name) so any characters are literal. |
|
|
137
|
+
| `compileFieldSQL` | function | `(path: FieldPath) => string` | Compiles a `FieldPath` to the SQL expression that reads it. |
|
|
138
|
+
| `compileJSONPathSQL` | function | `(keys: readonly string[]) => string` | Compiles the keys of a nested path to a SQL string literal holding its JSON path, each key a quoted label. |
|
|
139
|
+
| `compileJSONAccessSQL` | function | `(path: readonly string[]) => string` | Compiles the arguments a JSON function reads a nested path through: the head column, read only when it holds text, and the path's quoted labels. |
|
|
140
|
+
| `compileColumnSQL` | function | `(storage: ColumnStorage) => string` | Maps a portable `ColumnStorage` to its SQLite column type. |
|
|
141
|
+
| `compileAggregateSQL` | function | `(operation: AggregateOperation, column: FieldPath) => string` | Compiles an `AggregateOperation` over a `FieldPath`. |
|
|
142
|
+
| `matchesSQLiteAffinity` | function | `(declared: unknown, storage: ColumnStorage) => boolean` | Checks a declared SQLite type against a portable storage affinity. |
|
|
143
|
+
| `matchesAbsentPath` | function | `(error: unknown) => boolean` | Reports whether a caught filesystem error says that nothing is there to read. |
|
|
144
|
+
| `encodeValue` | function | `(value: unknown, column: ColumnSchema) => SQLiteValue` | Encodes a JS value to its stored `SQLiteValue` for a declared column. |
|
|
145
|
+
| `decodeValue` | function | `(value: SQLiteValue, column: ColumnSchema, context?: Readonly<Record<string, unknown>>) => unknown` | Decodes a stored `SQLiteValue` back to its JS value for a declared column — the exact inverse of `encodeValue`. |
|
|
146
|
+
| `encodeRow` | function | `(row: Row, schema: TableSchema) => SQLiteRow` | Encodes a whole `Row` to a `SQLiteRow` by its table's schema. |
|
|
147
|
+
| `decodeRow` | function | `(row: SQLiteRow, schema: TableSchema) => Row` | Decodes a stored `SQLiteRow` back to a `Row` by its table's schema. |
|
|
148
|
+
| `schemaToTable` | function | `(schema: TableSchema) => string` | Projects a `TableSchema` to its `CREATE TABLE IF NOT EXISTS` statement. |
|
|
149
|
+
| `schemaToIndexes` | function | `(schema: TableSchema) => readonly string[]` | Projects a `TableSchema` to its declared SQLite indexes. |
|
|
150
|
+
| `stepToSQL` | function | `(step: MigrationStep) => readonly string[]` | Projects one `MigrationStep` to SQLite DDL. |
|
|
151
|
+
| `compileBoundSQL` | function | `(sql: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Encodes condition operands for a SQL fragment using their declared or inferred storage. |
|
|
152
|
+
| `compileListSQL` | function | `(head: string, tail: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Compiles a membership list as one bound JSON parameter read through `json_each`, or as one parameter per operand when an encoded operand has no JSON form. |
|
|
153
|
+
| `compileGuardedSQL` | function | `(fragment: string, guard: string) => string` | Parenthesizes a fragment when a guard term joins it, and leaves a bare fragment bare. |
|
|
154
|
+
| `compileJoinedSQL` | function | `(parts: readonly CompiledSQL[], connective: string, empty: string) => CompiledSQL` | Joins SQL fragments with one connective, parenthesizing two or more, and returns a constant for none. |
|
|
144
155
|
|
|
145
156
|
### Browser
|
|
146
157
|
|
|
147
|
-
Pure functions behind the IndexedDB driver's planner
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
|
152
|
-
|
|
|
153
|
-
| `
|
|
154
|
-
| `
|
|
155
|
-
| `
|
|
156
|
-
| `
|
|
157
|
-
| `
|
|
158
|
-
| `
|
|
159
|
-
| `
|
|
160
|
-
| `
|
|
161
|
-
| `
|
|
158
|
+
Pure functions behind the IndexedDB driver's planner: it ranks the access paths a read's
|
|
159
|
+
conditions admit, keeps the one it picks native with the order and page that path serves,
|
|
160
|
+
and leaves the rest to the core engine.
|
|
161
|
+
|
|
162
|
+
| Name | Kind | Signature | Summary |
|
|
163
|
+
| -------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
164
|
+
| `conditionToRange` | function | `(condition: Condition) => IDBKeyRange \| undefined` | Translates one `Condition` to the `IDBKeyRange` it maps to, when its operator is one of the exact key comparisons over scalar operands; otherwise returns `undefined`. |
|
|
165
|
+
| `planIndexedDBQuery` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => ReadPlan` | Splits a read into the part IndexedDB answers natively and the residual the core runs — the IndexedDB driver's `plan`. |
|
|
166
|
+
| `findAccessPlan` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => AccessPlan` | Finds the one access path an IndexedDB read takes. |
|
|
167
|
+
| `deriveConditionPlan` | function | `(condition: Condition, schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path one condition admits on the primary key or on a single-column index, or `undefined` when it admits none. |
|
|
168
|
+
| `deriveCompoundPlan` | function | `(conditions: readonly Condition[], index: readonly string[], schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path a compound index admits for a read's conditions, or `undefined` when it admits none. |
|
|
169
|
+
| `deriveOrderPlan` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path an order alone admits: the index whose columns are the order's columns, read in one direction, or `undefined` when no such index serves it. |
|
|
170
|
+
| `rankAccessPlan` | function | `(plan: AccessPlan) => number` | Ranks an access path by the rule `findAccessPlan` reads: a lower rank wins. |
|
|
171
|
+
| `buildCompoundRange` | function | `(values: readonly Key[], condition?: Condition) => IDBKeyRange \| undefined` | Builds the key range over a compound index's array keys that binds its leading columns to `values` and, when given, its next column to a range condition. |
|
|
172
|
+
| `matchesAccessOrder` | function | `(plan: AccessPlan, order: readonly Order[], primary: string) => boolean` | Checks whether an access path reads its rows in an order, ties broken by primary key in the order's direction. |
|
|
173
|
+
| `matchesKeyList` | function | `(plan: AccessPlan, order: readonly Order[] \| undefined, primary: string) => boolean` | Checks whether a read lists the primary keys of its access path and sorts them, rather than walking its source in order. |
|
|
174
|
+
| `resolveCount` | function | `(count: number \| undefined) => number \| undefined` | Resolves the count a native `getAll`, `getAllKeys`, or `advance` call takes for a row count. |
|
|
175
|
+
| `narrowRange` | function | `(range: IDBKeyRange \| undefined, key: IDBValidKey, direction: IDBCursorDirection, open: boolean) => IDBKeyRange \| undefined` | Narrows a key range to the keys past one key in a cursor direction, for a stream that resumes after the final key of its last batch. |
|
|
176
|
+
| `readIndexNames` | function | `(database: IDBDatabase, stores: readonly string[]) => ReadonlyMap<string, readonly string[]>` | Reads the index names each listed store of a connected database holds, in one readonly transaction. |
|
|
177
|
+
| `INDEXABLE_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s that are valid, orderable IndexedDB keys. |
|
|
178
|
+
| `METADATA_STORE` | const | `"__metadata__"` | Names the reserved out-of-line store `__metadata__` the `IndexedDBDriver` stamps its `DriverMetadata` into. |
|
|
179
|
+
| `STREAM_BATCH_SIZE` | const | `500` | Holds the number of rows the `IndexedDBDriver` reads per batch when it streams. |
|
|
180
|
+
| `COUNT_LIMIT` | const | `4294967295` | Holds the largest count IndexedDB's `getAll`, `getAllKeys`, and cursor `advance` accept: the Web IDL `unsigned long` maximum, past which the engine refuses the call with a `TypeError`. |
|
|
181
|
+
| `mapIndexedDBError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy — the default mapping used everywhere except inside `migrate()`. |
|
|
182
|
+
| `mapMigrationError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy for use inside `migrate()` — the one context where `UPGRADE` means the migration itself failed, not a generic driver fault. |
|
|
183
|
+
| `deriveIndexedDBIndexName` | function | `(columns: readonly string[]) => string` | Derives an IndexedDB index name for a declared column group — a bare column name for a single-column index, a deterministic collision-free encoding for a compound one. |
|
|
184
|
+
| `schemaToStore` | function | `(schema: TableSchema) => StoreDefinition` | Projects a table schema into the IndexedDB wrapper's store definition. |
|
|
162
185
|
|
|
163
186
|
### Errors
|
|
164
187
|
|
|
@@ -181,35 +204,75 @@ whose every entry passes Contract's `isAuditFault` function.
|
|
|
181
204
|
The portable semantics every backend shares — pure, total functions the
|
|
182
205
|
driver never re-implements.
|
|
183
206
|
|
|
184
|
-
| Name | Kind | Signature
|
|
185
|
-
| ---------------------- | -------- |
|
|
186
|
-
| `compareValues` | function | `(left: unknown, right: unknown) => number`
|
|
187
|
-
| `matchesCondition` | function | `(row: Row, condition: Condition, scalars?: ReadonlySet<unknown>) => boolean`
|
|
188
|
-
| `matchesQuery` | function | `(row: Row, conditions: readonly Condition[], scalars?: ReadonlyArray<ReadonlySet<unknown>>) => boolean`
|
|
189
|
-
| `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]`
|
|
190
|
-
| `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]`
|
|
191
|
-
| `validatePage` | function | `(input?: QueryInput) => void`
|
|
192
|
-
| `
|
|
193
|
-
| `
|
|
194
|
-
| `
|
|
195
|
-
| `
|
|
196
|
-
| `
|
|
197
|
-
| `
|
|
198
|
-
| `
|
|
199
|
-
| `
|
|
200
|
-
| `
|
|
201
|
-
| `
|
|
202
|
-
| `
|
|
203
|
-
| `
|
|
204
|
-
| `
|
|
205
|
-
| `
|
|
206
|
-
| `
|
|
207
|
-
| `
|
|
207
|
+
| Name | Kind | Signature | Summary |
|
|
208
|
+
| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
209
|
+
| `compareValues` | function | `(left: unknown, right: unknown) => number` | Compares two arbitrary values under one total order — the comparator behind sorting and the range operators. |
|
|
210
|
+
| `matchesCondition` | function | `(row: Row, condition: Condition, scalars?: ReadonlySet<unknown>) => boolean` | Evaluates one `Condition` against a row — the per-operator predicate. |
|
|
211
|
+
| `matchesQuery` | function | `(row: Row, conditions: readonly Condition[], scalars?: ReadonlyArray<ReadonlySet<unknown>>) => boolean` | Folds a row through a list of conditions, joining each by its connector. |
|
|
212
|
+
| `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
|
|
213
|
+
| `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
|
|
214
|
+
| `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
|
|
215
|
+
| `buildBatch` | function | `(keys: Key \| readonly Key[], rows: Row \| readonly Row[]) => ReadonlyArray<readonly [Key, Row]>` | Assembles the entries of a storage write from its keys and rows, one row per key. |
|
|
216
|
+
| `computeRemoved` | function | `(keys: readonly unknown[], existed: readonly boolean[]) => readonly boolean[]` | Computes what a batch delete reports per key: true for the first occurrence of a key that held a row, and false for a miss and for every repeat of a key. |
|
|
217
|
+
| `computeFirstIndexes` | function | `(keys: readonly unknown[]) => ReadonlyMap<unknown, number>` | Computes the position of each key's first occurrence in a batch. |
|
|
218
|
+
| `applyKeys` | function | `(keys: Key \| readonly Key[], operation: (keys: readonly Key[]) => Promise<readonly boolean[]>) => Promise<boolean \| readonly boolean[]>` | Applies a keyed operation that takes a key list to a single key or a key list, and answers in the form the call took. |
|
|
219
|
+
| `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
|
|
220
|
+
| `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
|
|
221
|
+
| `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
|
|
222
|
+
| `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
|
|
223
|
+
| `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
|
|
224
|
+
| `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
|
|
225
|
+
| `requireColumns` | function | `(<T extends TableMap, K extends keyof T & string>(tables: T, name: K) => T[K]) & ((tables: TableMap, name: string) => ColumnMap)` | Requires one declared table's columns out of a table map. |
|
|
226
|
+
| `shapeToColumnStorage` | function | `(shape: ContractShape) => ColumnStorage` | Maps a column's `ContractShape` to its portable `ColumnStorage` — the value a `TableSchema` carries so a native backend can declare a real column. |
|
|
227
|
+
| `filterRows` | function | `(rows: readonly Row[], conditions: readonly Condition[]) => readonly Row[]` | Filters rows by a list of conditions — the shared basis for a table's count and aggregate paths (no sort/page, unlike `applyQuery`). |
|
|
228
|
+
| `equalsValue` | function | `(left: unknown, right: unknown) => boolean` | Compares two values structurally by SameValueZero leaves — the comparator behind conformance checks and any test/fixture that needs "same data", not "same reference". |
|
|
229
|
+
| `collectScalars` | function | `(values: readonly unknown[]) => ReadonlySet<unknown>` | Collects the scalar operands of a membership list into one set. |
|
|
230
|
+
| `matchesListed` | function | `(value: unknown, values: readonly unknown[], scalars?: ReadonlySet<unknown>) => boolean` | Checks whether a value equals one operand of a membership list. |
|
|
231
|
+
| `prepareScalars` | function | `(conditions: readonly Condition[]) => ReadonlyArray<ReadonlySet<unknown>>` | Collects one scalar set per condition, by position — the `scalars` argument of `matchesQuery`. |
|
|
232
|
+
| `normalizeReadInput` | function | `(input: ReadInput) => ReadInput` | Drops each clause a read does not hold, so an absent clause is an absent key. |
|
|
233
|
+
| `planRead` | function | `(storage: StorageInterface, table: string, input: ReadInput) => ReadPlan` | Asks a storage for its plan of a read, with the read normalized first. |
|
|
234
|
+
| `streamPlannedRows` | function | `(storage: StorageInterface, table: string, native: ReadInput, residual: ReadInput, step?: () => Promise<void>) => AsyncIterable<Row>` | Streams the native side of a plan and applies residual conditions and a residual page, stopping at `offset + limit` matches — step 3 of the read procedure. |
|
|
208
235
|
|
|
209
236
|
For `minimum` and `maximum`, `computeAggregate` compares each numeric value
|
|
210
237
|
with a scalar `Math.min` or `Math.max` call. The helper never passes a
|
|
211
238
|
row-sized argument list.
|
|
212
239
|
|
|
240
|
+
### Query door
|
|
241
|
+
|
|
242
|
+
Every read of a table passes this door before any driver call: the shape-derived guard of
|
|
243
|
+
`queryInputContract`, then a pass over the table's columns; see [The query door](#the-query-door)
|
|
244
|
+
for each refusal.
|
|
245
|
+
|
|
246
|
+
| Name | Kind | Signature | Summary |
|
|
247
|
+
| -------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
248
|
+
| `queryInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ conditions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["absent", "present"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["equals", "not", "above", "below", "from", "to"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["like", "glob", "starts", "ends"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["between"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["any", "none"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>]>>>; order: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; direction: import("@orkestrel/contract").LiteralShape<readonly ["ascending", "descending"]>; }, boolean \| import("@orkestrel/contract").ContractShape>>>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; offset: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; }, false>` | Declares a portable read, `QueryInput`, as a closed contract shape. |
|
|
249
|
+
| `queryInputContract` | const | `ContractInterface<QueryInput>` | Holds the compiled contract of a portable read, which a table admits every read through. |
|
|
250
|
+
| `maskUndefinedOperands` | function | `(input: unknown) => unknown` | Copies a read so that each `undefined` operand of `equals`, `not`, `any`, and `none` reads `null`, the form `queryInputShape` declares. |
|
|
251
|
+
| `restoreUndefinedOperands` | function | `(masked: QueryInput, source: unknown) => QueryInput` | Puts back the operands of a read whose masked form `maskUndefinedOperands` built and the query contract admitted. |
|
|
252
|
+
| `matchesIllFormedText` | function | `(value: unknown) => boolean` | Checks whether a value is a string holding a lone surrogate, which has no UTF-8 form. |
|
|
253
|
+
| `extractColumnHead` | function | `(column: unknown) => string \| undefined` | Extracts the leading column a column reference names: a column name, or the first key of a non-empty list of keys. |
|
|
254
|
+
| `scanAggregateFaults` | function | `(aggregate: unknown, columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds the faults of an aggregate: an operation outside `AGGREGATE_OPERATIONS`, and a column that is no column reference or that the table does not hold. |
|
|
255
|
+
| `cloneQueryInput` | function | `(value: unknown) => unknown` | Copies a read a table is about to admit, so a change its caller makes after admission never reaches the read. |
|
|
256
|
+
| `cloneQueryPart` | function | `(value: unknown) => unknown` | Copies one condition or ordering term of a read, with its list of keys and its operand list, reading each member once. |
|
|
257
|
+
| `scanQueryFaults` | function | `(input: unknown, columns: ReadonlyMap<string, ColumnSchema>, refused?: readonly AuditFault[]) => readonly AuditFault[]` | Finds what a read asks of a table's columns that they do not hold — the schema facts a shape cannot state. |
|
|
258
|
+
| `scanConditionFaults` | function | `(condition: unknown, path: readonly string[], columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds what one condition asks of a table's columns that they do not hold, under the rules `scanQueryFaults` states. |
|
|
259
|
+
| `scanColumnFaults` | function | `(column: unknown, path: readonly string[], columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds the fault of a column reference: an undeclared leading column, or a nested path under a column that is not `json`. |
|
|
260
|
+
| `scanOperandFaults` | function | `(value: unknown, path: readonly string[], column: ColumnSchema \| undefined, nullish: boolean) => readonly AuditFault[]` | Finds the fault of one operand against its column's storage class. |
|
|
261
|
+
| `findIllFormedColumn` | function | `(row: Row, columns: ReadonlyMap<string, ColumnSchema>) => string \| undefined` | Finds the first `text` column of a row whose string is not well-formed UTF-16. |
|
|
262
|
+
| `collectColumns` | function | `(columns: ColumnMap) => ReadonlyMap<string, ColumnSchema>` | Collects a table's column map into each column's portable schema, by name, in declaration order. |
|
|
263
|
+
|
|
264
|
+
### Recording
|
|
265
|
+
|
|
266
|
+
The rows-read instrument: a recorder wraps a real driver and counts the keys each storage call
|
|
267
|
+
addresses and the rows it returns or yields. A call log records calls; this counts rows too.
|
|
268
|
+
|
|
269
|
+
| Name | Kind | Signature | Summary |
|
|
270
|
+
| -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
271
|
+
| `StorageRecorder` | class | `new (source: DriverInterface) => StorageRecorder` | Wraps a driver and records the keys each storage member addresses and the rows it returns or yields, inside a transaction scope too — the rows-read instrument of a native-first reading. |
|
|
272
|
+
| `RecordedStorage` | class | `new (source: StorageInterface, record: (member: StorageMember, keys: number, rows: StreamPage) => void) => StorageInterface` | Forwards each required member of a storage in the form it received and reports each call when it is invoked: the member, the keys it addresses, and a counter of the rows it returns or yields. |
|
|
273
|
+
| `tallyCalls` | function | `(calls: readonly StorageCall[], member: StorageMember) => StorageTally` | Totals the calls, addressed keys, and returned rows of one member across recorded calls. |
|
|
274
|
+
| `streamRecordedRows` | function | `(source: AsyncIterable<Row>, rows: StreamPageInterface) => AsyncIterable<Row>` | Yields a source's rows, counting each row on a counter as its consumer pulls it. |
|
|
275
|
+
|
|
213
276
|
### Abort
|
|
214
277
|
|
|
215
278
|
| Name | Kind | Signature | Summary |
|
|
@@ -235,6 +298,7 @@ transform. Versioning drivers persist reconciliation metadata through the paired
|
|
|
235
298
|
| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
236
299
|
| `conformDriver` | function | `(factory: () => DriverInterface) => Promise<void>` | Runs the driver-conformance battery, throwing on the first violated invariant — the fail-fast entry point most callers (test setup, CI smoke checks) want. |
|
|
237
300
|
| `scanDriver` | function | `(factory: () => DriverInterface) => AsyncIterable<ConformanceFinding>` | Walks the driver-conformance battery against a fresh `DriverInterface` per phase, yielding one `ConformanceFinding` per violated invariant — the shared invariant suite every backend (in-memory, SQLite, IndexedDB) must uphold to be a drop-in `DriverInterface`. |
|
|
301
|
+
| `buildFailureFinding` | function | `(check: string, error: unknown) => ConformanceFinding` | Builds the finding a conformance phase yields when it throws, naming the phase. |
|
|
238
302
|
| `auditDriver` | function | `(factory: () => DriverInterface) => Promise<readonly ConformanceFinding[]>` | Runs the full driver-conformance battery and collects every violation — the audit entry point for a driver author who wants a complete report rather than a single fail-fast throw. |
|
|
239
303
|
| `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
|
|
240
304
|
| `readPlannedRows` | function | `(storage: StorageInterface, table: string, input: QueryInput, step?: () => Promise<void>) => Promise<readonly Row[]>` | Reads the rows of a read through a storage's plan — the read procedure `Table.records` runs and the conformance differential checks. |
|
|
@@ -261,6 +325,8 @@ Pure helpers behind the query engine's pattern matching.
|
|
|
261
325
|
| `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
|
|
262
326
|
| `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
|
|
263
327
|
| `isKey` | function | `(value: unknown) => value is Key` | Checks whether a value is a usable database key. |
|
|
328
|
+
| `isAggregate` | function | `(value: unknown) => value is Aggregate` | Checks whether a value is an `Aggregate`: one of `AGGREGATE_OPERATIONS` over a column name or a non-empty list of keys. |
|
|
329
|
+
| `isAggregateOperation` | const | `Guard<AggregateOperation>` | Checks whether a value is one of `AGGREGATE_OPERATIONS`. |
|
|
264
330
|
| `isScalar` | function | `(value: unknown) => value is Scalar` | Checks whether a value is a scalar: not an object and not a function. |
|
|
265
331
|
| `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
|
|
266
332
|
| `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
|
|
@@ -268,15 +334,18 @@ Pure helpers behind the query engine's pattern matching.
|
|
|
268
334
|
|
|
269
335
|
### Constants
|
|
270
336
|
|
|
271
|
-
| Name | Kind | Signature
|
|
272
|
-
| -------------------------- | ----- |
|
|
273
|
-
| `DEFAULT_PRIMARY` | const | `"id"`
|
|
274
|
-
| `
|
|
275
|
-
| `
|
|
276
|
-
| `
|
|
277
|
-
| `
|
|
278
|
-
| `
|
|
279
|
-
| `
|
|
337
|
+
| Name | Kind | Signature | Summary |
|
|
338
|
+
| -------------------------- | ----- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
339
|
+
| `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
|
|
340
|
+
| `NULLISH_OPERATORS` | const | `readonly ConditionOperator[]` | Lists the operators whose operand can be `null` on a nullable column and `undefined` on an optional one: `equals`, `not`, `any`, and `none`. |
|
|
341
|
+
| `AGGREGATE_OPERATIONS` | const | `readonly AggregateOperation[]` | Lists the aggregates a read can compute: `count`, `sum`, `average`, `minimum`, and `maximum`. |
|
|
342
|
+
| `PATTERN_OPERATORS` | const | `readonly ConditionOperator[]` | Lists the operators that match a string pattern, which read a `text` or `json` column: `like`, `glob`, `starts`, and `ends`. |
|
|
343
|
+
| `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
|
|
344
|
+
| `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
|
|
345
|
+
| `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
|
|
346
|
+
| `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
|
|
347
|
+
| `CONFORMANCE_ROWS` | const | `readonly Row[]` | Holds the `users` rows the conformance differential seeds: ties, an absent `age`, ASCII and non-ASCII case variants, a supplementary-plane character, an empty name, and a `[`. |
|
|
348
|
+
| `CONFORMANCE_READS` | const | `readonly ReadInput[]` | Holds the reads the conformance differential runs over `CONFORMANCE_ROWS`: every operator on a required text column and an optional integer column, `null` operands, `or` folds, a nested path, orders with ties, a page, and every aggregate. |
|
|
280
349
|
|
|
281
350
|
### Types
|
|
282
351
|
|
|
@@ -316,13 +385,23 @@ Pure helpers behind the query engine's pattern matching.
|
|
|
316
385
|
| `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
|
|
317
386
|
| `StorageInterface` | interface | `{ read(), write(), insert(), delete(), keys(), scan(), clear(), plan?(), records?(), aggregate?(), stream?(), migrate?(), metadata?(), stamp?() }` | Declares the storage operations available only inside a driver's transaction scope. |
|
|
318
387
|
| `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
|
|
319
|
-
| `DriverInterface` | interface | `{ open(), close(),
|
|
388
|
+
| `DriverInterface` | interface | `{ open(), close(), transaction?() }` | Declares the storage contract a backend implements: its engine's native operations first, and the core's engine only for the residual its plan returns. |
|
|
389
|
+
| `StorageMember` | type | `'read' \| 'write' \| 'insert' \| 'delete' \| 'keys' \| 'scan' \| 'clear' \| 'plan' \| 'records' \| 'stream' \| 'aggregate'` | Names a `StorageInterface` member a `StorageRecorder` observes. |
|
|
390
|
+
| `StorageCall` | interface | `{ member, keys, rows, scoped }` | Represents one storage call a `StorageRecorder` observed: the member, the keys it addressed, the rows it returned or yielded, and whether a transaction scope made it. |
|
|
391
|
+
| `StorageTally` | interface | `{ calls, keys, rows }` | Represents the calls, addressed keys, and returned rows of one member across recorded calls. |
|
|
392
|
+
| `StorageResult` | interface | `{ value, calls }` | Represents one measured operation's value and the storage calls it made. |
|
|
393
|
+
| `StreamPageInterface` | interface | `{ count, next() }` | Represents the matching-row position of one streaming page: `next` advances past one matching row and `count` reads the rows past the page's offset. |
|
|
394
|
+
| `StorageJournalInterface` | interface | `{ restore() }` | Records the prior row of each key a scope writes or deletes, on its first touch, and restores those keys on request. |
|
|
320
395
|
| `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
|
|
321
396
|
| `CompiledSQL` | interface | `{ sql, parameters }` | Represents a parameterized SQL fragment or statement plus its bind values. The `@orkestrel/database/server` entry point exports this type. |
|
|
322
397
|
| `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
|
|
323
|
-
| `
|
|
398
|
+
| `SQLiteDriverInterface` | interface | `{ pragma() }` | Represents the SQLite driver: the storage contract plus a read of one connection pragma. |
|
|
399
|
+
| `AccessPlan` | interface | `{ conditions, columns, prefix, index?, range?, keys? }` | Represents the one access path an IndexedDB read takes: the conditions it answers, the primary store or the index it reads, and the key range or key list it reads there. |
|
|
400
|
+
| `AccessBatch` | interface | `{ rows, position? }` | Represents one batch a stream reads in one transaction: its rows, and the position of its final entry, which the next batch reads past. |
|
|
401
|
+
| `AccessPosition` | interface | `{ key, primary }` | Represents the position of one entry in an access path: its key in the path's source and its primary key, which are the same key on the primary store. |
|
|
324
402
|
| `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
|
|
325
403
|
| `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
|
|
404
|
+
| `DatabaseTableOptions` | interface | `{ on?, error? }` | Options for one table handle that `table` returns. |
|
|
326
405
|
| `DatabaseInterface` | interface | `{ emitter, name, status, import(), export(), open(), close(), transaction(), migrate() }` | Represents a database — the ergonomic entry point that owns the driver and its tables. |
|
|
327
406
|
| `TableInterface` | interface | `{ emitter, name, primary, contract, get(), resolve(), has(), keys(), records(), count(), aggregate(), scan(), set(), add(), update(), remove(), clear(), query(), cursor() }` | Exposes typed keyed CRUD plus fluent query and cursor access. |
|
|
328
407
|
| `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
|
|
@@ -387,46 +466,108 @@ method below runs inside that scope, and each carries the same contract its
|
|
|
387
466
|
`StorageInterface` and `DriverInterface` tables share one description per
|
|
388
467
|
method.
|
|
389
468
|
|
|
390
|
-
| Method | Returns | Summary
|
|
391
|
-
| ----------- | -------------------------------------- |
|
|
392
|
-
| `read` | `Promise<Row \| undefined>`
|
|
393
|
-
| `write` | `Promise<void>` | Writes one row at a key.
|
|
394
|
-
| `insert` | `Promise<void>` | Inserts one row
|
|
395
|
-
| `delete` | `Promise<boolean>`
|
|
396
|
-
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys.
|
|
397
|
-
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order.
|
|
398
|
-
| `clear` | `Promise<void>` | Empties a table.
|
|
399
|
-
| `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook.
|
|
400
|
-
| `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook.
|
|
401
|
-
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook.
|
|
402
|
-
| `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook.
|
|
403
|
-
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook.
|
|
404
|
-
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook.
|
|
405
|
-
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook.
|
|
469
|
+
| Method | Returns | Summary |
|
|
470
|
+
| ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
471
|
+
| `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
|
|
472
|
+
| `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
|
|
473
|
+
| `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
|
|
474
|
+
| `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
|
|
475
|
+
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
476
|
+
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
477
|
+
| `clear` | `Promise<void>` | Empties a table. |
|
|
478
|
+
| `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
|
|
479
|
+
| `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
|
|
480
|
+
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
|
|
481
|
+
| `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
|
|
482
|
+
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
|
|
483
|
+
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
484
|
+
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
406
485
|
|
|
407
486
|
#### `DriverInterface`
|
|
408
487
|
|
|
409
|
-
The complete backend extends `StorageInterface` with lifecycle
|
|
410
|
-
|
|
488
|
+
The complete backend extends `StorageInterface` with lifecycle and an optional native
|
|
489
|
+
transaction callback. The inherited
|
|
411
490
|
storage/query/migration/metadata methods carry the same contract they carry on
|
|
412
491
|
`StorageInterface`, addressed against the whole backend rather than one
|
|
413
492
|
transaction scope. `open` receives the derived `TableSchema` list: a native
|
|
414
493
|
backend builds real tables and indexes from it, a scan-only backend reads
|
|
415
|
-
`name` alone.
|
|
416
|
-
list
|
|
417
|
-
|
|
418
|
-
`
|
|
419
|
-
|
|
494
|
+
`name` alone. Each keyed member takes one key, or a list that one call applies whole: a
|
|
495
|
+
list `write` or `insert` pairs `keys[i]` with `rows[i]` and applies every row or none, and
|
|
496
|
+
a list `delete` reports, per key, whether the call removed its row: it is the storage contract,
|
|
497
|
+
not a manager verb, and `Table.remove` emits `remove` for each removed key before it folds the
|
|
498
|
+
list into one answer. A driver without
|
|
499
|
+
`plan` answers nothing natively — the core runs the whole read over `scan` — and a driver
|
|
500
|
+
without `transaction` runs a scope on the core's journal (see
|
|
501
|
+
[Transactions](#transactions)).
|
|
502
|
+
|
|
503
|
+
| Method | Returns | Summary |
|
|
504
|
+
| ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
505
|
+
| `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
|
|
506
|
+
| `close` | `Promise<void>` | Releases the backend. |
|
|
507
|
+
| `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
|
|
508
|
+
| `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
|
|
509
|
+
| `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
|
|
510
|
+
| `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
|
|
511
|
+
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
512
|
+
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
513
|
+
| `clear` | `Promise<void>` | Empties a table. |
|
|
514
|
+
| `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
|
|
515
|
+
| `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
|
|
516
|
+
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
|
|
517
|
+
| `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
|
|
518
|
+
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
|
|
519
|
+
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
520
|
+
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
521
|
+
| `transaction` | `Promise<R>` | Opens a native transaction scope — an optional driver hook. The driver owns acquisition, commit or rollback, release, and invalidation of the scoped capability. |
|
|
522
|
+
|
|
523
|
+
#### `StorageJournalInterface`
|
|
524
|
+
|
|
525
|
+
`StorageJournalInterface` extends `StorageInterface`. Each inherited member forwards to the
|
|
526
|
+
storage the journal wraps, and a write, insert, delete, or clear first records the prior rows
|
|
527
|
+
it would change.
|
|
528
|
+
|
|
529
|
+
| Method | Returns | Summary |
|
|
530
|
+
| ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
531
|
+
| `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
|
|
532
|
+
| `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
|
|
533
|
+
| `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
|
|
534
|
+
| `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
|
|
535
|
+
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
536
|
+
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
537
|
+
| `clear` | `Promise<void>` | Empties a table. |
|
|
538
|
+
| `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
|
|
539
|
+
| `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
|
|
540
|
+
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
|
|
541
|
+
| `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
|
|
542
|
+
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
|
|
543
|
+
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
544
|
+
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
545
|
+
| `restore` | `Promise<void>` | Restores every key and table the journal recorded to its prior rows. |
|
|
546
|
+
|
|
547
|
+
#### `StreamPageInterface`
|
|
548
|
+
|
|
549
|
+
The matching-row position of one streaming page; its `count` data member stays in the Surface
|
|
550
|
+
row.
|
|
551
|
+
|
|
552
|
+
| Method | Returns | Summary |
|
|
553
|
+
| ------ | --------- | ------------------------------- |
|
|
554
|
+
| `next` | `boolean` | Advances past one matching row. |
|
|
555
|
+
|
|
556
|
+
#### `SQLiteDriverInterface`
|
|
557
|
+
|
|
558
|
+
`SQLiteDriverInterface` extends `DriverInterface`, and `createSQLiteDriver` returns it. Each
|
|
559
|
+
inherited member carries its `DriverInterface` contract. `pragma` is a root member: the scoped
|
|
560
|
+
capability a transaction passes does not declare it, and a call while a transaction is active
|
|
561
|
+
raises `CONFLICT`.
|
|
420
562
|
|
|
421
563
|
| Method | Returns | Summary |
|
|
422
564
|
| ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
423
565
|
| `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
|
|
424
566
|
| `close` | `Promise<void>` | Releases the backend. |
|
|
425
|
-
| `
|
|
426
|
-
| `
|
|
427
|
-
| `
|
|
428
|
-
| `
|
|
429
|
-
| `delete` | `Promise<boolean>` | Deletes one row by key. |
|
|
567
|
+
| `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
|
|
568
|
+
| `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
|
|
569
|
+
| `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
|
|
570
|
+
| `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
|
|
430
571
|
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
431
572
|
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
432
573
|
| `clear` | `Promise<void>` | Empties a table. |
|
|
@@ -438,6 +579,7 @@ nothing natively — the core runs the whole read over `scan` — and a driver w
|
|
|
438
579
|
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
439
580
|
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
440
581
|
| `transaction` | `Promise<R>` | Opens a native transaction scope — an optional driver hook. The driver owns acquisition, commit or rollback, release, and invalidation of the scoped capability. |
|
|
582
|
+
| `pragma` | `SQLiteValue \| undefined` | Runs `PRAGMA name` with no value and returns the first value the engine answers. |
|
|
441
583
|
|
|
442
584
|
#### `DatabaseInterface`
|
|
443
585
|
|
|
@@ -468,6 +610,11 @@ for work started after the transaction settles.
|
|
|
468
610
|
| ------- | ----------------------------- | ---------------------------------------------- |
|
|
469
611
|
| `table` | `TableInterface<RowOf<T[K]>>` | Returns the typed handle for a declared table. |
|
|
470
612
|
|
|
613
|
+
`table(name, options)` takes `DatabaseTableOptions`: `on` registers initial `TableEventMap` listeners
|
|
614
|
+
on the handle's emitter, and `error` routes their throws instead of the database's `error` option.
|
|
615
|
+
A handle has no lifecycle verb: its emitter ends with the handle, and after the database closes
|
|
616
|
+
no operation runs, so no handle emits.
|
|
617
|
+
|
|
471
618
|
#### `AdmissionInterface`
|
|
472
619
|
|
|
473
620
|
The admission boundary the root database context and a transaction scope both
|
|
@@ -486,8 +633,9 @@ it raises `DRIVER` with `table`, `key`, and the contract's `faults`. `count()` i
|
|
|
486
633
|
`aggregate('count')`, which reads the stored set `records()` reads while ignoring paging,
|
|
487
634
|
so the two agree. `records`,
|
|
488
635
|
`count`, `aggregate`, `scan`, `set`, `add`, `update`, and `remove` each take an
|
|
489
|
-
optional `OperationOptions`: its `signal` reaches every backend commit point
|
|
490
|
-
|
|
636
|
+
optional `OperationOptions`: its `signal` reaches every backend commit point. A list form
|
|
637
|
+
is one driver call that admits every row first and applies every row or none; `update`
|
|
638
|
+
of a list is one list `read` and one list `write`.
|
|
491
639
|
|
|
492
640
|
| Method | Returns | Summary |
|
|
493
641
|
| ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------- |
|
|
@@ -502,7 +650,7 @@ and an aborted batch keeps the items already committed.
|
|
|
502
650
|
| `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
|
|
503
651
|
| `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
|
|
504
652
|
| `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
|
|
505
|
-
| `remove` | `Promise<boolean>`
|
|
653
|
+
| `remove` | `Promise<boolean>` | Deletes one or more rows. |
|
|
506
654
|
| `clear` | `Promise<void>` | Empties the table. |
|
|
507
655
|
| `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
|
|
508
656
|
| `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
|
|
@@ -550,19 +698,20 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
550
698
|
an entry barrel remain internal.
|
|
551
699
|
2. **A table is a contract.** Every write is admitted whole through the
|
|
552
700
|
table's compiled contract — `set` / `add` / `update` run the row through
|
|
553
|
-
Contract's `admitValue`, which
|
|
554
|
-
`
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
701
|
+
Contract's `admitValue`, which enforces types and constraints such as
|
|
702
|
+
`min` / `pattern` and repairs nothing. A row that carries an undeclared
|
|
703
|
+
top-level column, omits a required column, or holds a mistyped value such
|
|
704
|
+
as `'36'` for an integer column throws `VALIDATION`; the table never
|
|
705
|
+
removes a column to admit the rest. A caller that wants a lossless repair
|
|
706
|
+
runs `repairValue(table.contract, row)` before the write. A
|
|
558
707
|
`rawShape` column admits any defined value, so the nested keys of a JSON
|
|
559
708
|
column never refuse. Reads are narrowed back to the table's row type
|
|
560
709
|
through the guard — never an `as` (see `AGENTS.md` § Non-negotiable
|
|
561
710
|
rules). The row type is the shape's `Infer`, so a `tables` map types every
|
|
562
711
|
table from one declaration. A refusal's context carries `table` and
|
|
563
712
|
`faults`, the `AuditFault` list `admitValue` returned, and its message
|
|
564
|
-
names the table and
|
|
565
|
-
function
|
|
713
|
+
names the table and every fault through Contract's `describeFaults`
|
|
714
|
+
function, bounded by `FAULT_TEXT_LIMIT`. A fault's `received` member and the message carry Contract's
|
|
566
715
|
JSON-encoded, length-capped rendering of the received value; the rejected
|
|
567
716
|
row and the parser cause never enter the message, context, serialized
|
|
568
717
|
error, or table events.
|
|
@@ -581,27 +730,28 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
581
730
|
planned driver against the core engine over `scan`. The following table rules where
|
|
582
731
|
each clause runs in this release:
|
|
583
732
|
|
|
584
|
-
| Clause | `SQLiteDriver` | `IndexedDBDriver`
|
|
585
|
-
| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
586
|
-
| Every operator on a flat `text`, `integer`, `real`, or `boolean` column | Native under every flag combination, with the null forms chosen from the column's flags; `starts` is an index range and `any` / `none` bind one `json_each` parameter |
|
|
587
|
-
| A nested path; a `json` or `blob` column |
|
|
588
|
-
| An `or` fold | Native when every condition is; otherwise wholly residual | Residual
|
|
589
|
-
| Order | Native on a flat column that is
|
|
590
|
-
| Page | `LIMIT` and `OFFSET` when the residual holds no condition and no order |
|
|
591
|
-
| `count` | `COUNT(*)` when the residual holds no condition |
|
|
592
|
-
| `sum`, `average`, `minimum`, `maximum` | Native on an `integer` or `real` column that is not both optional and nullable
|
|
593
|
-
| Transaction | `BEGIN` / `COMMIT` / `ROLLBACK`; the scoped capability declares `plan`, `records`, `stream`, and `aggregate`
|
|
733
|
+
| Clause | `SQLiteDriver` | `IndexedDBDriver` | `MemoryDriver`, `JSONDriver` |
|
|
734
|
+
| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
|
|
735
|
+
| Every operator on a flat `text`, `integer`, `real`, or `boolean` column | Native under every flag combination, with the null forms chosen from the column's flags; `starts` is an index range and `any` / `none` bind one `json_each` parameter | One access path when every connector is `and`, ranked by rule: primary-key `equals` or `any`; a compound index matched on two or more columns; a single-column index with `equals` or `any`, or a compound index whose leading column alone an `equals` binds; then a range or `starts` on the primary key or an index. `below` and `to` read an index only on a required column. The other conditions are residual | Residual over `scan` |
|
|
736
|
+
| A nested path; a `json` or `blob` column | A prefilter for `equals`, `not`, `any`, and `none` with scalar operands on a nested path under a `json` head, which the core rechecks; residual otherwise | Residual | Residual over `scan` |
|
|
737
|
+
| An `or` fold | Native when every condition is; otherwise wholly residual | Residual | Residual over `scan` |
|
|
738
|
+
| Order | Native on a flat column; a column that is both optional and nullable sorts behind a rank of absence, `null`, then its values | Native on the primary key, on a point of an index, and on the access path's index when the order is its unbound required columns in one direction; otherwise residual | Residual over `scan` |
|
|
739
|
+
| Page | `LIMIT` and `OFFSET` when the residual holds no condition and no order | `records(range, limit)`, or a cursor with `advance(offset)`, when the residual holds no condition and no order; otherwise residual, stopping the stream at `offset + limit` matches | Residual over `scan` |
|
|
740
|
+
| `count` | `COUNT(*)` when the residual holds no condition | `count(range)`, a sum of counts for `any`, when the residual holds no condition | Residual over `scan` |
|
|
741
|
+
| `sum`, `average`, `minimum`, `maximum` | Native on an `integer` or `real` column that is not both optional and nullable; `sum` is `TOTAL`, `NULL` over no value | `minimum` and `maximum`: the first entry of the column's index on a required `integer` or `real` column, when the residual holds no condition; `sum` and `average`: residual | Residual over `scan` |
|
|
742
|
+
| Transaction | `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`; the scoped capability declares `plan`, `records`, `stream`, and `aggregate` | The core's before-image journal | `JSONDriver`: native; `MemoryDriver`: the core's before-image journal |
|
|
594
743
|
|
|
595
744
|
The rule fixes these semantics on every driver: text order and text ranges are the
|
|
596
745
|
engine's binary order, so SQLite orders by code point where the core orders by UTF-16
|
|
597
746
|
code unit, and the two differ only between a supplementary-plane character and one in
|
|
598
747
|
U+E000 to U+FFFF; `like` folds ASCII letters only, and `_` and `?` match one code point;
|
|
599
748
|
ties resolve by primary key in the direction of the final order term; `sum` and
|
|
600
|
-
`average` on a numeric column are the engine's arithmetic
|
|
749
|
+
`average` on a numeric column are the engine's arithmetic, and SQLite's `sum` is its
|
|
750
|
+
floating-point `TOTAL`, which an integer sum past 2^53 reads as without raising. Every write is admitted
|
|
601
751
|
through the contract, so every stored row conforms; a returned stored row that fails the
|
|
602
752
|
contract raises `DRIVER`, and SQLite raises `DRIVER` for a stored value that does not
|
|
603
|
-
match its column's declaration. `MemoryDriver`
|
|
604
|
-
|
|
753
|
+
match its column's declaration. `MemoryDriver` lacks a native `transaction?`, so the
|
|
754
|
+
core's journal carries its transactions; `JSONDriver` does implement
|
|
605
755
|
`transaction?` — it clones the committed memory/schema/metadata into an
|
|
606
756
|
isolated candidate, passes only that candidate's capability to the callback,
|
|
607
757
|
and publishes it with one atomic file replacement only when the callback
|
|
@@ -614,7 +764,7 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
614
764
|
exactly once, and terminalizes the iterator; the transaction and driver
|
|
615
765
|
remain usable. Memory and IndexedDB need no equivalent root wrapper because
|
|
616
766
|
neither exposes a callback transaction. `Database.transaction` over a `JSONDriver`
|
|
617
|
-
therefore prefers this native path over the
|
|
767
|
+
therefore prefers this native path over the journal. Both reference drivers also
|
|
618
768
|
implement the paired `metadata?` / `stamp?` — `MemoryDriver` in-process only
|
|
619
769
|
(the owned `DriverMetadata` snapshot lives in instance memory), `JSONDriver` persisted:
|
|
620
770
|
the file is `{ metadata?: DriverMetadata, tables }`, with `metadata` present only
|
|
@@ -635,18 +785,18 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
635
785
|
`DatabaseError('DRIVER', 'Stored SQLite table is missing')` before any DDL in its
|
|
636
786
|
open transaction, and IndexedDB throws
|
|
637
787
|
`DatabaseError('DRIVER', 'Stored IndexedDB store is missing')` before its final
|
|
638
|
-
open. Extra
|
|
639
|
-
|
|
788
|
+
open. Extra tables and stores remain allowed, apart from an IndexedDB index the deployed
|
|
789
|
+
schema does not declare, which open drops; SQLite may reconstruct a missing declared index
|
|
790
|
+
because the table and its records still exist, and a writable SQLite open also drops each
|
|
791
|
+
created index of a deployed table that the deployed schema no longer declares. IndexedDB
|
|
640
792
|
captures the bootstrap connection's exact stores and version in the same
|
|
641
|
-
lifetime, then pins the persisted final open to that version
|
|
642
|
-
versionchange makes the stale open reject
|
|
643
|
-
recreating storage. Existing unreadable, malformed, structurally incompatible,
|
|
793
|
+
lifetime, then pins the persisted final open to that version, or to the next one when
|
|
794
|
+
it drops an undeclared index; a concurrent versionchange makes the stale open reject
|
|
795
|
+
instead of silently bumping and recreating storage. Existing unreadable, malformed, structurally incompatible,
|
|
644
796
|
or physically incomplete state throws `DRIVER` without publishing a handle or
|
|
645
797
|
attempting table/store repair; after external repair, the same driver instance
|
|
646
798
|
may retry `open`.
|
|
647
|
-
`
|
|
648
|
-
so the capture is point-in-time consistent across stores even under
|
|
649
|
-
concurrent writers; `restore` was already atomic. `SQLiteDriver` and
|
|
799
|
+
`SQLiteDriver` and
|
|
650
800
|
`IndexedDBDriver` each implement `migrate?` natively and treat `MigrationInput` as one commit unit:
|
|
651
801
|
`SQLiteDriver` applies schema, rows, and optional metadata inside one native
|
|
652
802
|
SQLite transaction (`stepToSQL` projects each step's DDL), while a migration
|
|
@@ -662,9 +812,9 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
662
812
|
nothing is rewritten. Both implement the paired `metadata?` /
|
|
663
813
|
`stamp?` into a reserved store name a user table must avoid:
|
|
664
814
|
`SQLiteDriver` uses a single-row `_metadata` table (`METADATA_TABLE`), and
|
|
665
|
-
`IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`),
|
|
666
|
-
|
|
667
|
-
`transaction?` as a callback-scoped real `BEGIN` / `COMMIT` / `ROLLBACK`;
|
|
815
|
+
`IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`), which no
|
|
816
|
+
table reaches. `SQLiteDriver` implements
|
|
817
|
+
`transaction?` as a callback-scoped real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`;
|
|
668
818
|
the capability performs reads, writes, migration, and metadata work inside
|
|
669
819
|
that one native transaction, then becomes invalid. `IndexedDBDriver`
|
|
670
820
|
deliberately omits `transaction?`: an `IDBTransaction` can auto-commit when
|
|
@@ -674,7 +824,8 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
674
824
|
|
|
675
825
|
4. **Total query helpers; the equality family is structural, not ranked.**
|
|
676
826
|
`compareValues`, `matchesCondition`, and `matchesQuery` never throw — a
|
|
677
|
-
type mismatch is a non-match
|
|
827
|
+
type mismatch is a non-match there, which invariant 15 keeps from any read of a table,
|
|
828
|
+
and the comparator is a total order (it
|
|
678
829
|
never returns `NaN`), mirroring the contracts guards' totality (see
|
|
679
830
|
`.claude/rules/patterns.md` § Validation and contracts). The range
|
|
680
831
|
operators (`above` / `below` / `from` / `to` /
|
|
@@ -704,9 +855,10 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
704
855
|
tables, queries, cursors, and streams also throw `CONFLICT` after settlement.
|
|
705
856
|
When the driver implements `transaction?(scope)`, the driver owns
|
|
706
857
|
acquisition, commit on fulfillment, rollback on rejection, release, and
|
|
707
|
-
invalidation. Otherwise the
|
|
708
|
-
|
|
709
|
-
rejection
|
|
858
|
+
invalidation. Otherwise the core's before-image journal records the prior row of each
|
|
859
|
+
key the scope writes or deletes, on its first touch, and restores those keys on
|
|
860
|
+
rejection; a `clear` journals its table alone, and reads go to the driver, so a native
|
|
861
|
+
read sees the scope's writes. It gives rollback on rejection and no crash atomicity. Either path emits the identical `transaction` / `commit`
|
|
710
862
|
lifecycle; `rollback(error)` is emitted only when rollback completed and the
|
|
711
863
|
original scope/drain error remains the propagated rejection, never when
|
|
712
864
|
cleanup itself replaced that error.
|
|
@@ -728,7 +880,14 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
728
880
|
restores, and the original transaction error still propagates (proven by
|
|
729
881
|
the emit-safety tests). Reads / queries / counts are not emitted (a
|
|
730
882
|
reader does not mutate, and those paths are too hot). The observation
|
|
731
|
-
lives in the core layer; the drivers stay storage primitives.
|
|
883
|
+
lives in the core layer; the drivers stay storage primitives. `close`
|
|
884
|
+
destroys the database emitter last, after its `close` event and even when
|
|
885
|
+
the driver refuses to close, so a listener registered before `close`
|
|
886
|
+
receives nothing after it. `table(name, options)` takes `DatabaseTableOptions`:
|
|
887
|
+
`on` registers initial listeners on that handle's emitter, and `error`
|
|
888
|
+
routes their throws instead of the database's `error` option. A handle has no
|
|
889
|
+
lifecycle verb: its emitter ends with the handle, and after the database closes
|
|
890
|
+
no operation runs, so no handle emits.
|
|
732
891
|
7. **Views share a driver.** A database is a typed view over a set of tables
|
|
733
892
|
on one driver. `import(tables)` returns a new view of only those tables
|
|
734
893
|
over the **same** driver (sharing storage and transactions); `export()`
|
|
@@ -745,13 +904,13 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
745
904
|
`migrate?` / `metadata?` / `stamp?` may be omitted). `MemoryDriver` and
|
|
746
905
|
`JSONDriver` both omit `records?` / `aggregate?`, and both
|
|
747
906
|
implement `stream?` / `migrate?` / `metadata?` / `stamp?`; `MemoryDriver` still
|
|
748
|
-
omits `transaction?` (
|
|
907
|
+
omits `transaction?` (the core's journal carries its scopes) while `JSONDriver`
|
|
749
908
|
implements `transaction?` too (isolated candidate state plus one atomic
|
|
750
909
|
publish on callback fulfillment). `SQLiteDriver` implements every optional hook — `records?` /
|
|
751
910
|
`aggregate?` / `transaction?` / `stream?` / `migrate?` / `metadata?`
|
|
752
911
|
/ `stamp?` — the fully-native backend. `IndexedDBDriver` implements
|
|
753
|
-
`records?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
|
|
754
|
-
omits `transaction?`
|
|
912
|
+
`records?` / `aggregate?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
|
|
913
|
+
omits `transaction?` by IndexedDB's nature, not by
|
|
755
914
|
choice (see `.claude/rules/documentation.md` § Parity). A renamed / added /
|
|
756
915
|
removed method breaks the gate
|
|
757
916
|
until the table is reconciled.
|
|
@@ -777,9 +936,8 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
777
936
|
the temp file before rejection, and reads wait behind that unit. Once an
|
|
778
937
|
commit point that cannot be aborted (`SQLite` call entry, IndexedDB transaction
|
|
779
938
|
completion, JSON `rename` dispatch) has won, the operation awaits and reports its real
|
|
780
|
-
result; a late signal cannot convert success to `ABORTED`.
|
|
781
|
-
|
|
782
|
-
later item.
|
|
939
|
+
result; a late signal cannot convert success to `ABORTED`. A batch is one driver call,
|
|
940
|
+
so an abort ahead of its commit point applies no row of it.
|
|
783
941
|
10. **Key generation is host-neutral and overridable.** When an optional
|
|
784
942
|
primary column is omitted, a table uses global `crypto.randomUUID()`.
|
|
785
943
|
`DatabaseOptions.generator` (a `KeyFunction`) authoritatively replaces
|
|
@@ -850,16 +1008,17 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
850
1008
|
README all call it the same way. It opens the fixed `users` and `posts`
|
|
851
1009
|
schema per phase (calling `factory()` fresh each time so failures stay
|
|
852
1010
|
isolated) and verifies the required surface's invariants (copy-in/copy-out
|
|
853
|
-
isolation, upsert-overwrite, key-ordered `keys`/`scan`,
|
|
854
|
-
|
|
1011
|
+
isolation, upsert-overwrite, key-ordered `keys`/`scan`, the batch invariants (a list
|
|
1012
|
+
read in key order, a list write that applies every row, a list insert with a conflicting
|
|
1013
|
+
final member and a mismatched batch that apply none, a list delete that reports each key
|
|
1014
|
+
once), the journal's round trip of prior rows, a non-`id` primary key, structural round-tripping through `equalsValue`), then
|
|
855
1015
|
presence-gates the optional `migrate?` / `stream?` / `transaction?`
|
|
856
1016
|
hooks when the driver implements them. The battery's `write-read` phase
|
|
857
1017
|
is deepened with nested-field checks (a written row's nested object/array
|
|
858
1018
|
fields must copy-in/copy-out isolated, not only its top-level fields),
|
|
859
|
-
and
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
fails conformance (`MemoryDriver` passes by deep-copying through
|
|
1019
|
+
and the journal phase asserts the same nested isolation for a list read whose rows the
|
|
1020
|
+
journal restores — a driver that shallow-copies anywhere in its write/read/scan
|
|
1021
|
+
boundary fails conformance (`MemoryDriver` passes by deep-copying through
|
|
863
1022
|
`structuredClone` at every one of those boundaries). The first violated
|
|
864
1023
|
invariant throws a `CONFORMANCE` `DatabaseError` naming the failed check.
|
|
865
1024
|
13. **Backend faults surface as `DatabaseError`, never raw.** No native
|
|
@@ -869,16 +1028,14 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
869
1028
|
(`#guard` internally on the SQLite side; `mapIndexedDBError` /
|
|
870
1029
|
`mapMigrationError` on the IndexedDB side), preserving the original
|
|
871
1030
|
error as `context.cause`. `SQLiteDriver`: a constraint violation maps to
|
|
872
|
-
`CONFLICT`, a closed-connection fault to `CLOSED`, a busy
|
|
873
|
-
to `DRIVER` with a `retryable` context flag, anything else to
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
Public `close()` crosses that same boundary
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
`context.code === 'BUSY'`; both retain the actual `SQLiteError` only at
|
|
881
|
-
`context.cause`.
|
|
1031
|
+
`CONFLICT`, a closed-connection fault to `CLOSED`, a busy database (`SQLITE_BUSY`, another
|
|
1032
|
+
connection's lock) to `DRIVER` with a `retryable` context flag, and anything else to
|
|
1033
|
+
`DRIVER`, `SQLITE_LOCKED` included: a lock the same connection holds, such as an open
|
|
1034
|
+
stream under a `migrate` that drops an index, carries no `retryable` flag, and its
|
|
1035
|
+
`context.cause.context.errcode` is 6.
|
|
1036
|
+
Public `close()` crosses that same boundary, and a zero-timeout exclusive lock rejects a
|
|
1037
|
+
write as retryable `DRIVER` with `context.code === 'BUSY'`, retaining the actual
|
|
1038
|
+
`SQLiteError` only at `context.cause`.
|
|
882
1039
|
`IndexedDBDriver`: a constraint violation maps to `CONFLICT`; a
|
|
883
1040
|
closed/not-open/invalid-state fault to `CLOSED`; a quota fault to
|
|
884
1041
|
`DRIVER` with `code: 'QUOTA'`; `migrate`'s versionchange path remaps an
|
|
@@ -893,11 +1050,43 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
893
1050
|
as corrupted metadata. Because both drivers derive their index names from
|
|
894
1051
|
a length-prefixed scheme (`deriveSQLiteIndexName` for SQLite,
|
|
895
1052
|
`deriveIndexedDBIndexName` for IndexedDB) to stay collision-free across
|
|
896
|
-
compound indexes
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
they are never queried and never collide, but a
|
|
900
|
-
them.
|
|
1053
|
+
compound indexes. A writable SQLite open drops every created index of a deployed table
|
|
1054
|
+
whose name its deployed schema does not derive, an old-named index included; an IndexedDB
|
|
1055
|
+
store created under an older naming scheme leaves its old-named indexes orphaned
|
|
1056
|
+
(unreferenced, harmless) on reopen — they are never queried and never collide, but a
|
|
1057
|
+
storage audit may notice them.
|
|
1058
|
+
|
|
1059
|
+
15. **Every read passes the query door.** `records`, `count`, `aggregate`, `scan`, and each
|
|
1060
|
+
`query()` terminal, a filtered `aggregate` included, admit a copy of their read after the
|
|
1061
|
+
driver is ready and before any driver call, and read only that copy, so a change the
|
|
1062
|
+
caller makes afterward never reaches the read. Only an absent read (`undefined`) skips
|
|
1063
|
+
the door; `null` refuses. The shape-derived guard of `queryInputContract` holds the
|
|
1064
|
+
structure: each condition is a union keyed on `operator` that fixes the arity of
|
|
1065
|
+
`values`, `like`, `glob`, `starts`, and `ends` take a string operand, a column is a name
|
|
1066
|
+
or a non-empty list of strings, `connector` and `direction` are their literals, `limit`
|
|
1067
|
+
and `offset` are nonnegative integers, and every object refuses an undeclared key. A pass
|
|
1068
|
+
over the table's columns holds the schema facts: the leading column of a condition, an
|
|
1069
|
+
ordering term, and the aggregate column is declared; a nested path descends only a
|
|
1070
|
+
`json` column; an operand matches its column's storage class (a string for `text`, a
|
|
1071
|
+
number for `integer` and `real`, a boolean for `boolean`, any value on `json`); `null`
|
|
1072
|
+
stands only on a nullable column and `undefined` only on an optional one, each for
|
|
1073
|
+
`equals`, `not`, `any`, and `none`, never under a range operator; `like`, `glob`,
|
|
1074
|
+
`starts`, and `ends` read a `text` or `json` column; the aggregate operation is one of
|
|
1075
|
+
`AGGREGATE_OPERATIONS`; and every string operand is well-formed UTF-16, on a `json`
|
|
1076
|
+
column and under a nested path too. The pass reads no refinement: integer-ness, bounds,
|
|
1077
|
+
patterns, and literal membership stay the contract's. A literal whose members span more
|
|
1078
|
+
than one class is `json` storage, as a union is. A refusal is `VALIDATION` whose context
|
|
1079
|
+
carries `table` and `faults`: the guard's `admitValue` faults, computed only after the
|
|
1080
|
+
guard refuses, then the faults of the column pass, which also runs when the guard refuses
|
|
1081
|
+
and skips each condition and ordering term a guard fault names, so one refusal names every
|
|
1082
|
+
fault once. The message is a header and the contract's `describeFaults` rendering, bounded
|
|
1083
|
+
by `FAULT_TEXT_LIMIT`. When the column pass reports, the header and the context add the
|
|
1084
|
+
`column` its first fault names, and the `operator` when the guard admitted the read, and
|
|
1085
|
+
the header lists the declared columns. An aggregate is admitted as a copy with its read, and
|
|
1086
|
+
the table computes from that copy. A lone surrogate in a written `text` value or in a key
|
|
1087
|
+
is `VALIDATION` with `table` and `column` on every driver, because SQLite stores it as
|
|
1088
|
+
U+FFFD and reads back a changed value; a `json` cell holding one round-trips, because
|
|
1089
|
+
`JSON.stringify` escapes it.
|
|
901
1090
|
|
|
902
1091
|
What ships is the **core in-between** (schema-aware: `open` receives a
|
|
903
1092
|
derived `TableSchema[]`, with `shapeToColumnStorage` mapping each column's shape), its
|
|
@@ -905,7 +1094,7 @@ reference `MemoryDriver`, and the persistent `JSONDriver`, `SQLiteDriver`, and
|
|
|
905
1094
|
`IndexedDBDriver` backends. `JSONDriver` in `src/server` is a decorator over
|
|
906
1095
|
`MemoryDriver` that loads/flushes a single JSON file — every primitive
|
|
907
1096
|
delegates to the inner memory driver, so querying, key-order `scan` / `keys`,
|
|
908
|
-
and
|
|
1097
|
+
and the all-or-nothing batches are inherited unchanged; `JSONDriver.migrate`
|
|
909
1098
|
additionally persists the migrated state, and every flush is atomic — written
|
|
910
1099
|
to a sibling temp file and `rename`d onto the target path, so a crash mid-flush
|
|
911
1100
|
can never truncate or corrupt the previous good file. Outside a `transaction`,
|
|
@@ -920,7 +1109,7 @@ active, and a captured capability used after settlement throw `CONFLICT`.
|
|
|
920
1109
|
fully-native, **trusted-mode** backend on the published `@orkestrel/sqlite`
|
|
921
1110
|
wrapper — real typed `CREATE TABLE` / `CREATE INDEX` DDL, native
|
|
922
1111
|
`records?` / `aggregate?` / `stream?` compiled straight to SQL,
|
|
923
|
-
real `BEGIN` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
|
|
1112
|
+
real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
|
|
924
1113
|
(`stepToSQL`; a root input uses one native transaction, while an input inside
|
|
925
1114
|
an existing callback transaction uses the guarded fixed internal savepoint
|
|
926
1115
|
literal for caught-inner-failure containment while the outer transaction stays
|
|
@@ -929,14 +1118,13 @@ and a reserved
|
|
|
929
1118
|
`_metadata` table (`METADATA_TABLE`) for `metadata?` / `stamp?` versioning — every
|
|
930
1119
|
optional `DriverInterface` hook, none skipped. `IndexedDBDriver` in
|
|
931
1120
|
`src/browser`, on the published `@orkestrel/indexeddb` wrapper, is the
|
|
932
|
-
persistent browser backend — `planIndexedDBQuery` keeps native the one
|
|
933
|
-
|
|
934
|
-
rest of the read residual for the core engine; `migrate?` applies a non-empty plan
|
|
1121
|
+
persistent browser backend — `planIndexedDBQuery` keeps native the one access path
|
|
1122
|
+
`findAccessPlan` ranks first, with the order, page, `count`, `minimum`, and `maximum` that
|
|
1123
|
+
path serves, and leaves the rest of the read residual for the core engine; `migrate?` applies a non-empty plan
|
|
935
1124
|
and its metadata in one versionchange transaction, and `metadata?` / `stamp?`
|
|
936
1125
|
persist into a reserved
|
|
937
1126
|
`__metadata__` store (`METADATA_STORE`) — it omits `transaction?` because arbitrary
|
|
938
|
-
callback awaits outlive an auto-committing `IDBTransaction
|
|
939
|
-
`aggregate?` (no native SUM/AVG/MIN/MAX) by IndexedDB's own nature. The core
|
|
1127
|
+
callback awaits outlive an auto-committing `IDBTransaction`. The core
|
|
940
1128
|
`Database` / `Table` are also **observable** — each owns a typed `emitter`
|
|
941
1129
|
(`DatabaseEventMap` / `TableEventMap`) carrying the transaction +
|
|
942
1130
|
per-row lifecycle (see [Observing](#observing)); a driver stays a storage
|
|
@@ -980,7 +1168,7 @@ posts.primary // 'slug' — the declared override
|
|
|
980
1168
|
Each `indexes` entry is one (possibly compound) index of column names; they
|
|
981
1169
|
flow into each table's derived `TableSchema`. Neither driver here declares a
|
|
982
1170
|
native index, so both ignore them; SQLite and IndexedDB build a native index from each
|
|
983
|
-
supported declaration.
|
|
1171
|
+
supported declaration, and IndexedDB drops at open an index the declaration no longer names.
|
|
984
1172
|
|
|
985
1173
|
### Swapping the driver
|
|
986
1174
|
|
|
@@ -1075,6 +1263,47 @@ await users.count() // every row, unfiltered
|
|
|
1075
1263
|
await users.aggregate('average', 'age') // number | undefined
|
|
1076
1264
|
```
|
|
1077
1265
|
|
|
1266
|
+
### The query door
|
|
1267
|
+
|
|
1268
|
+
A table admits each read before any driver call, so a malformed read raises in place of an
|
|
1269
|
+
empty or a whole-table answer. The refusal names the table, and the key path and expected class
|
|
1270
|
+
of each fault; when the column pass reports, it also names the column and operator of its first
|
|
1271
|
+
fault and lists the declared columns:
|
|
1272
|
+
|
|
1273
|
+
```ts
|
|
1274
|
+
import { createDatabase, createMemoryDriver } from '@orkestrel/database'
|
|
1275
|
+
import { integerShape, optionalShape, stringShape } from '@orkestrel/contract'
|
|
1276
|
+
|
|
1277
|
+
const items = createDatabase({
|
|
1278
|
+
driver: createMemoryDriver(),
|
|
1279
|
+
tables: {
|
|
1280
|
+
items: { id: stringShape(), rank: integerShape(), note: optionalShape(stringShape()) },
|
|
1281
|
+
},
|
|
1282
|
+
}).table('items')
|
|
1283
|
+
await items.set([
|
|
1284
|
+
{ id: 'a', rank: 5 },
|
|
1285
|
+
{ id: 'b', rank: 7, note: 'kept' },
|
|
1286
|
+
])
|
|
1287
|
+
|
|
1288
|
+
await items.count({
|
|
1289
|
+
conditions: [{ column: 'note', operator: 'equals', values: [undefined], connector: 'and' }],
|
|
1290
|
+
}) // 1 — `undefined` stands on an optional column
|
|
1291
|
+
await items
|
|
1292
|
+
.count({ conditions: [{ column: 'rank', operator: 'equals', values: ['5'], connector: 'and' }] })
|
|
1293
|
+
.catch((error: unknown) => error)
|
|
1294
|
+
// DatabaseError VALIDATION, context { table: 'items', column: 'rank', operator: 'equals', faults: [
|
|
1295
|
+
// { reason: 'type', path: ['conditions', '0', 'values', '0'], expected: 'number', received: '"5"' }] }
|
|
1296
|
+
await items
|
|
1297
|
+
.records({ conditions: [{ column: 'rnk', operator: 'absent', values: [], connector: 'and' }] })
|
|
1298
|
+
.catch((error: unknown) => error)
|
|
1299
|
+
// DatabaseError VALIDATION; the message lists the declared columns: id text, rank integer, note text optional
|
|
1300
|
+
await items.get('a\uD800').catch((error: unknown) => error)
|
|
1301
|
+
// DatabaseError VALIDATION, context { table: 'items', column: 'id' } — a lone surrogate in a key
|
|
1302
|
+
```
|
|
1303
|
+
|
|
1304
|
+
`queryInputContract` is the same door for a caller that admits a read before it reaches a
|
|
1305
|
+
table, such as a server that takes a read from a client.
|
|
1306
|
+
|
|
1078
1307
|
### Streaming with early exit
|
|
1079
1308
|
|
|
1080
1309
|
`scan` (on a table) and `stream` (on a query) are lazy — rows are yielded one
|
|
@@ -1165,8 +1394,8 @@ write. Memory and SQLite check immediately before their synchronous mutation;
|
|
|
1165
1394
|
IndexedDB aborts its explicit readwrite transaction while active; JSON aborts
|
|
1166
1395
|
staging, cleans its temp file, and restores the preimage before rejecting. If
|
|
1167
1396
|
the native commit has already been dispatched, the method ignores a late abort
|
|
1168
|
-
and awaits the real success or failure. A batch
|
|
1169
|
-
|
|
1397
|
+
and awaits the real success or failure. A batch is one driver call with one commit point,
|
|
1398
|
+
so an abort applies every row of it or none.
|
|
1170
1399
|
|
|
1171
1400
|
### Batch operations
|
|
1172
1401
|
|
|
@@ -1200,33 +1429,46 @@ await users.get(['u1', 'u2']) // → readonly (Row | undefined)[]
|
|
|
1200
1429
|
await users.resolve(['u1', 'u2']) // → readonly Row[] (NOT_FOUND on any miss)
|
|
1201
1430
|
await users.has(['u1', 'u2']) // → readonly boolean[]
|
|
1202
1431
|
await users.update(['u1', 'u2'], { role: 'member' }) // same changes to each → readonly boolean[]
|
|
1203
|
-
await users.remove(['u1', 'u2']) // →
|
|
1432
|
+
await users.remove(['u1', 'u2']) // → boolean, true only when every distinct listed key held a row and was removed
|
|
1204
1433
|
```
|
|
1205
1434
|
|
|
1206
|
-
A batch
|
|
1207
|
-
|
|
1435
|
+
A batch is one driver call that applies every row or none. The table admits every row through
|
|
1436
|
+
the contract ahead of that call, so a refused row applies none of the batch, and a conflicting
|
|
1437
|
+
`add` member does the same. SQLite runs the batch as one transaction, or as one savepoint
|
|
1438
|
+
inside a scope; IndexedDB runs it in one `database.write` scope; `MemoryDriver` and
|
|
1439
|
+
`JSONDriver` check every row ahead of the first change. `get`, `resolve`, and `has` of a key
|
|
1440
|
+
list are one list `read`, and `update` of a key list is one list `read` and one list
|
|
1441
|
+
`write`.
|
|
1208
1442
|
|
|
1209
1443
|
### Admission through the contract
|
|
1210
1444
|
|
|
1211
|
-
|
|
1445
|
+
Repairs a numeric string through the table's contract before the write, stores the number, and refuses the bare write and an undeclared column:
|
|
1212
1446
|
|
|
1213
1447
|
```ts
|
|
1214
1448
|
import { createDatabase, createMemoryDriver, isDatabaseError } from '@orkestrel/database'
|
|
1215
|
-
import {
|
|
1449
|
+
import type { DatabaseInterface } from '@orkestrel/database'
|
|
1450
|
+
import { integerShape, repairValue, stringShape } from '@orkestrel/contract'
|
|
1216
1451
|
|
|
1217
|
-
|
|
1452
|
+
// A DatabaseInterface hands out untyped rows, as a boundary that holds loose data needs.
|
|
1453
|
+
const db: DatabaseInterface = createDatabase({
|
|
1218
1454
|
driver: createMemoryDriver(),
|
|
1219
1455
|
tables: {
|
|
1220
1456
|
users: { id: stringShape(), name: stringShape(), age: integerShape(), role: stringShape() },
|
|
1221
1457
|
},
|
|
1222
|
-
})
|
|
1458
|
+
})
|
|
1459
|
+
const users = db.table('users')
|
|
1223
1460
|
|
|
1224
|
-
// A numeric string is a lossless repair, so
|
|
1225
|
-
const
|
|
1226
|
-
|
|
1227
|
-
|
|
1461
|
+
// A numeric string is a lossless repair, so repairValue admits it as the number before the write.
|
|
1462
|
+
const loose = { id: 'u2', name: 'Bo', age: '41', role: 'member' }
|
|
1463
|
+
const repaired = repairValue(users.contract, loose)
|
|
1464
|
+
if (!repaired.success) throw new Error('Expected the row to repair')
|
|
1465
|
+
await users.set(repaired.value.value)
|
|
1228
1466
|
;(await users.get('u2'))?.age // 41 (a number)
|
|
1229
1467
|
|
|
1468
|
+
// The bare write refuses the same row with DatabaseError('VALIDATION') and the type fault.
|
|
1469
|
+
const bare = await users.set({ ...loose, id: 'u4' }).catch((error: unknown) => error)
|
|
1470
|
+
if (isDatabaseError(bare)) bare.message // contains 'age: type; expected integer; received "41"'
|
|
1471
|
+
|
|
1230
1472
|
// An undeclared column refuses with DatabaseError('VALIDATION') and the contract's faults.
|
|
1231
1473
|
const imported = { id: 'u3', name: 'Cy', age: 29, role: 'member', nickname: 'Cy' }
|
|
1232
1474
|
const refused = await users.set(imported).catch((error: unknown) => error)
|
|
@@ -1365,7 +1607,8 @@ await users
|
|
|
1365
1607
|
|
|
1366
1608
|
The condition operators map to familiar SQL operators. The core engine evaluates each one
|
|
1367
1609
|
over a residual; SQLite answers each natively on a flat declared column, and IndexedDB
|
|
1368
|
-
answers one
|
|
1610
|
+
answers the conditions of one access path with a key range or a key list, under these same
|
|
1611
|
+
semantics:
|
|
1369
1612
|
|
|
1370
1613
|
| Operator | SQL |
|
|
1371
1614
|
| --------- | ------------- |
|
|
@@ -1544,6 +1787,35 @@ error. `rollback(error)` reports only a completed rollback whose original
|
|
|
1544
1787
|
scope/drain error is still being propagated — a cleanup failure is never
|
|
1545
1788
|
reported as a successful rollback.
|
|
1546
1789
|
|
|
1790
|
+
On a driver without `transaction?` (`MemoryDriver`, `IndexedDBDriver`, a custom backend), the
|
|
1791
|
+
core runs the scope through its before-image journal, `StorageJournal`: each write, insert,
|
|
1792
|
+
or delete reads the prior rows of its untouched keys in one list `read` ahead of the write,
|
|
1793
|
+
and a `clear` reads its table's keys and rows ahead of emptying it. On rejection the journal
|
|
1794
|
+
writes back each cleared table and each recorded row and deletes each recorded key that held
|
|
1795
|
+
no row, so the cost of a scope follows the keys it touched rather than the store's size.
|
|
1796
|
+
Reads go to the driver, so a native read inside the scope sees the scope's writes. The
|
|
1797
|
+
journal gives rollback on rejection and no crash atomicity:
|
|
1798
|
+
|
|
1799
|
+
```ts
|
|
1800
|
+
import { createMemoryDriver, StorageJournal } from '@orkestrel/database'
|
|
1801
|
+
|
|
1802
|
+
const driver = createMemoryDriver()
|
|
1803
|
+
await driver.open([
|
|
1804
|
+
{
|
|
1805
|
+
name: 'users',
|
|
1806
|
+
primary: 'id',
|
|
1807
|
+
columns: [{ name: 'id', storage: 'text', optional: false, nullable: false }],
|
|
1808
|
+
indexes: [],
|
|
1809
|
+
},
|
|
1810
|
+
])
|
|
1811
|
+
await driver.write('users', 'u1', { id: 'u1', name: 'Ada' })
|
|
1812
|
+
const journal = new StorageJournal(driver)
|
|
1813
|
+
await journal.write('users', 'u1', { id: 'u1', name: 'Grace' })
|
|
1814
|
+
await journal.insert('users', 'u2', { id: 'u2', name: 'Alan' })
|
|
1815
|
+
await journal.restore()
|
|
1816
|
+
await driver.read('users', ['u1', 'u2']) // [{ id: 'u1', name: 'Ada' }, undefined]
|
|
1817
|
+
```
|
|
1818
|
+
|
|
1547
1819
|
Root promise operations enter the shared admission ledger synchronously, before
|
|
1548
1820
|
their first `await`. `transaction()` closes root admission before it drains that
|
|
1549
1821
|
ledger, so work accepted immediately before the transaction is included and work
|
|
@@ -1572,7 +1844,7 @@ await boundary.track(async () => 42) // 42
|
|
|
1572
1844
|
### Native transactions
|
|
1573
1845
|
|
|
1574
1846
|
`transaction` uses a driver's optional native `transaction?(scope)` hook
|
|
1575
|
-
instead of the
|
|
1847
|
+
instead of the core's journal. The driver passes a `StorageInterface`
|
|
1576
1848
|
capability to the callback, commits when it fulfills, rolls back when it
|
|
1577
1849
|
rejects, and invalidates the capability after settlement. The database-level
|
|
1578
1850
|
`transaction` / `commit` / `rollback` events fire the same either way:
|
|
@@ -1816,10 +2088,10 @@ schemaToStore(table)
|
|
|
1816
2088
|
|
|
1817
2089
|
The helper delegates exact JSON ownership to Contract 0.0.9's
|
|
1818
2090
|
`cloneJSONRecord`, then validates the owned output as `DriverMetadata`. A malformed
|
|
1819
|
-
shape, cycle, function, accessor, or
|
|
2091
|
+
shape, cycle, function, accessor, or throwing/revoked proxy throws
|
|
1820
2092
|
`DatabaseError('VALIDATION')` with `context.path === 'metadata'`; clone/traversal
|
|
1821
2093
|
failures are retained only as `context.cause`, so no raw Contract or caller
|
|
1822
|
-
error crosses the Database surface.
|
|
2094
|
+
error crosses the Database surface. Untrusted values are never stringified or
|
|
1823
2095
|
embedded in the diagnostic.
|
|
1824
2096
|
|
|
1825
2097
|
`JSONDriver` applies that ownership rule at every file-backed seam: valid parsed
|
|
@@ -1834,7 +2106,7 @@ structured-clone behavior and are not forced through the JSON metadata cloner.
|
|
|
1834
2106
|
|
|
1835
2107
|
`SQLiteDriver` applies the same boundary at persisted-row ingress, every
|
|
1836
2108
|
root/scoped `stamp` and `migrate` ingress, and every `metadata()` copy-out.
|
|
1837
|
-
Root lifecycle and scoped token gates run before
|
|
2109
|
+
Root lifecycle and scoped token gates run before untrusted metadata traversal;
|
|
1838
2110
|
valid migration metadata is cloned before its first DDL statement. Malformed
|
|
1839
2111
|
stored metadata fails closed with `DRIVER`, while valid copy-outs are distinct
|
|
1840
2112
|
and deeply frozen. General SQLite rows continue through
|
|
@@ -1925,8 +2197,9 @@ const db = createDatabase({
|
|
|
1925
2197
|
on: { commit: () => console.log('transaction committed') },
|
|
1926
2198
|
})
|
|
1927
2199
|
|
|
1928
|
-
const users = db.table('users'
|
|
1929
|
-
|
|
2200
|
+
const users = db.table('users', {
|
|
2201
|
+
on: { write: (key) => console.log('invalidate users', key) },
|
|
2202
|
+
}) // hold the handle (the documented practice) and observe it
|
|
1930
2203
|
users.emitter.on('remove', (key) => console.log('invalidate users', key))
|
|
1931
2204
|
db.emitter.on('rollback', (error) => console.warn('transaction rolled back', error))
|
|
1932
2205
|
```
|
|
@@ -1941,7 +2214,7 @@ The event vocabulary:
|
|
|
1941
2214
|
`open` fires once when the handle's driver connects (an explicit `open()`, or
|
|
1942
2215
|
the lazy first-use connect); `close`
|
|
1943
2216
|
when the driver is released; `transaction` when a scope begins after its
|
|
1944
|
-
native boundary or
|
|
2217
|
+
native boundary is acquired or its journal is created; `commit` only after a scope
|
|
1945
2218
|
succeeds; `rollback` only after a throwing scope's tables are all restored;
|
|
1946
2219
|
`migrate` after a migration commits. A `Table` fires `write` after any
|
|
1947
2220
|
row put (set / add / update — re-read by key if you need the new value),
|
|
@@ -1949,7 +2222,12 @@ row put (set / add / update — re-read by key if you need the new value),
|
|
|
1949
2222
|
and `clear` after the table is emptied. Reads / queries / counts are **not**
|
|
1950
2223
|
emitted — a reader does not mutate, and those paths are too hot. Each
|
|
1951
2224
|
`db.table(name)` returns a fresh handle with its own emitter, so subscribe
|
|
1952
|
-
on the handle you hold and operate on that same handle
|
|
2225
|
+
on the handle you hold and operate on that same handle, or pass initial
|
|
2226
|
+
listeners through the handle's `on` option. `close` destroys the database
|
|
2227
|
+
emitter after its `close` event, so a database listener receives nothing after
|
|
2228
|
+
`close`. A table handle has no lifecycle verb: its emitter ends with the handle, and
|
|
2229
|
+
after `close` every table operation refuses with `CLOSED`, so a table listener
|
|
2230
|
+
receives nothing after it either.
|
|
1953
2231
|
|
|
1954
2232
|
**Listener isolation.** A listener throw never escapes
|
|
1955
2233
|
into the engine: the emitter isolates it and routes it to
|
|
@@ -1966,8 +2244,8 @@ propagates, the tables still roll back), and a throwing `write` observer
|
|
|
1966
2244
|
leaves the written row intact — proven by the per-entity emit-safety tests.
|
|
1967
2245
|
(A `Table` reached through the `Database` receives the same `error` handler
|
|
1968
2246
|
the `DatabaseOptions.error` option supplies, so a `Table` listener throw
|
|
1969
|
-
routes there
|
|
1970
|
-
silently.)
|
|
2247
|
+
routes there unless the handle's own `DatabaseTableOptions.error` option supplies one;
|
|
2248
|
+
with no `error` handler configured, the throw is swallowed silently.)
|
|
1971
2249
|
|
|
1972
2250
|
### Importing and exporting schemas
|
|
1973
2251
|
|
|
@@ -2083,9 +2361,10 @@ await driver.write('users', 'u1', { id: 'u1', name: 'Ada Lovelace' }) // upsert
|
|
|
2083
2361
|
await driver.read('users', 'u1') // { id: 'u1', name: 'Ada' } | undefined
|
|
2084
2362
|
for await (const row of driver.scan('users')) row // every row, key order
|
|
2085
2363
|
await driver.keys('users') // readonly Key[]
|
|
2086
|
-
|
|
2087
|
-
await driver.
|
|
2088
|
-
await
|
|
2364
|
+
await driver.write('users', ['u2', 'u3'], [{ id: 'u2' }, { id: 'u3' }]) // every row or none
|
|
2365
|
+
await driver.read('users', ['u1', 'missing']) // [{ id: 'u1', name: 'Ada Lovelace' }, undefined]
|
|
2366
|
+
await driver.delete('users', ['u2', 'u2']) // [true, false]
|
|
2367
|
+
await driver.delete('users', 'u1') // true
|
|
2089
2368
|
await driver.clear('users')
|
|
2090
2369
|
await driver.close()
|
|
2091
2370
|
```
|
|
@@ -2140,6 +2419,36 @@ shapeToColumnStorage(integerShape()) // 'integer' — the type `open` hands a dr
|
|
|
2140
2419
|
equalsValue({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }) // true — structural, not reference, equality
|
|
2141
2420
|
```
|
|
2142
2421
|
|
|
2422
|
+
### Recording driver calls
|
|
2423
|
+
|
|
2424
|
+
`StorageRecorder` wraps a real driver and counts the keys each call addresses and the rows it
|
|
2425
|
+
returns or yields; `tallyCalls` totals one member. Its `driver` declares exactly the members
|
|
2426
|
+
its source declares, so a read plans as it would on the source:
|
|
2427
|
+
|
|
2428
|
+
```ts
|
|
2429
|
+
import { integerShape, stringShape } from '@orkestrel/contract'
|
|
2430
|
+
import {
|
|
2431
|
+
createDatabase,
|
|
2432
|
+
createMemoryDriver,
|
|
2433
|
+
StorageRecorder,
|
|
2434
|
+
tallyCalls,
|
|
2435
|
+
} from '@orkestrel/database'
|
|
2436
|
+
|
|
2437
|
+
const recorder = new StorageRecorder(createMemoryDriver())
|
|
2438
|
+
const users = createDatabase({
|
|
2439
|
+
driver: recorder.driver,
|
|
2440
|
+
tables: { users: { id: stringShape(), age: integerShape() } },
|
|
2441
|
+
}).table('users')
|
|
2442
|
+
await users.set([
|
|
2443
|
+
{ id: 'u1', age: 36 },
|
|
2444
|
+
{ id: 'u2', age: 7 },
|
|
2445
|
+
])
|
|
2446
|
+
|
|
2447
|
+
const { value, calls } = await recorder.measure(() => users.count())
|
|
2448
|
+
value // 2
|
|
2449
|
+
tallyCalls(calls, 'scan') // { calls: 1, keys: 0, rows: 2 } — the Memory driver answers over scan
|
|
2450
|
+
```
|
|
2451
|
+
|
|
2143
2452
|
### Persistence with the JSON driver
|
|
2144
2453
|
|
|
2145
2454
|
Opens a database over the JSON driver and writes one row, persisted to the backing file:
|
|
@@ -2192,12 +2501,12 @@ restored before that error leaves the exclusive queue, so the next operation
|
|
|
2192
2501
|
can proceed after the temporary obstruction is removed. A successful staging
|
|
2193
2502
|
write requests native `flush: true` before the same-directory atomic rename.
|
|
2194
2503
|
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2504
|
+
Each root write, insert, or delete, a list included, records its prior rows in a
|
|
2505
|
+
`StorageJournal` over the driver's memory, applies the change, and flushes the whole store
|
|
2506
|
+
once; a failed flush restores the journaled rows before the error leaves the queue, so memory
|
|
2507
|
+
and the file hold the same rows. An empty list changes no row and leaves the file in place.
|
|
2508
|
+
`clear` flushes the table as empty ahead of emptying memory, so a failed flush leaves memory
|
|
2509
|
+
holding every row it held.
|
|
2201
2510
|
|
|
2202
2511
|
### Compiling input to SQL
|
|
2203
2512
|
|
|
@@ -2240,7 +2549,7 @@ compileQuerySQL(
|
|
|
2240
2549
|
quoteIdentifier('order') // '"order"'
|
|
2241
2550
|
deriveSQLiteIndexName('users', ['age']) // 'idx_5_users_3_age'
|
|
2242
2551
|
compileColumnSQL('integer') // 'INTEGER'
|
|
2243
|
-
compileFieldSQL(['profile', 'score']) //
|
|
2552
|
+
compileFieldSQL(['profile', 'score']) // `json_extract(CASE WHEN typeof("profile") = 'text' THEN "profile" END, '$."score"')`
|
|
2244
2553
|
compileAggregateSQL('average', 'age') // 'AVG("age")'
|
|
2245
2554
|
planSQLiteQuery({ aggregate: { operation: 'minimum', column: 'age' } }, schema).residual // {}
|
|
2246
2555
|
matchesSQLiteAffinity('INTEGER', 'integer') // true
|
|
@@ -2258,11 +2567,24 @@ A driver's `plan` splits each read into the part its engine answers and the resi
|
|
|
2258
2567
|
core runs, under the native-first rule the `DriverInterface` doc block states. A read is
|
|
2259
2568
|
wholly native when `residual` equals `{}`. `planSQLiteQuery` is the SQLite driver's plan,
|
|
2260
2569
|
and `compileQuerySQL` compiles its native side; `planIndexedDBQuery` is the IndexedDB
|
|
2261
|
-
driver's plan, which keeps one
|
|
2570
|
+
driver's plan, which keeps one ranked access path native with the order, page, and count it
|
|
2571
|
+
serves. A driver without `plan`, such as
|
|
2262
2572
|
`MemoryDriver` and `JSONDriver`, answers the whole read as residual over `scan`. `Table` runs
|
|
2263
2573
|
every read through `readPlannedRows`, `readPlannedAggregate`, and `streamPlannedRows`, the one
|
|
2264
2574
|
read procedure `scanDriver`'s differential checks.
|
|
2265
2575
|
|
|
2576
|
+
Two SQLite forms keep a read native where a flag or a path would otherwise send it to the
|
|
2577
|
+
core. An order on a column that is both optional and nullable compiles a rank ahead of the
|
|
2578
|
+
column term, in the term's direction: absence ranks 0, the column's `null` sentinel ranks 1,
|
|
2579
|
+
and a value ranks 2, so the engine returns the core's total order, and the page stays native
|
|
2580
|
+
beside it. When every connector is `and`, `matchesSQLitePrefilter` admits `equals`, `not`,
|
|
2581
|
+
`any`, and `none` with scalar operands on a nested path under a `json` head, and the plan puts
|
|
2582
|
+
the condition on both sides: `compileNestedSQL` tests the JSON type at the path beside its
|
|
2583
|
+
value, so the engine keeps a superset of the rows and the core rechecks each one. A key that
|
|
2584
|
+
can name an array member, a canonical index such as `0` or `length`, keeps the condition
|
|
2585
|
+
residual alone, because a JSON path label names an object member only. A prefilter holds the
|
|
2586
|
+
page on the residual side, so the core still stops at `offset + limit` matches.
|
|
2587
|
+
|
|
2266
2588
|
```ts
|
|
2267
2589
|
import type { Condition, TableSchema } from '@orkestrel/database'
|
|
2268
2590
|
import {
|
|
@@ -2337,15 +2659,18 @@ await db
|
|
|
2337
2659
|
// Real transactions and atomic migration ship with it:
|
|
2338
2660
|
await db.transaction(async (transaction) => {
|
|
2339
2661
|
await transaction.table('users').update('u1', { age: 37 })
|
|
2340
|
-
}) // real BEGIN/COMMIT/ROLLBACK, not the
|
|
2662
|
+
}) // real BEGIN IMMEDIATE/COMMIT/ROLLBACK, not the core's journal
|
|
2341
2663
|
|
|
2342
|
-
// createSQLiteDriver accepts a SQLiteDriverOptions bag:
|
|
2343
|
-
createSQLiteDriver({
|
|
2344
|
-
path: 'data/
|
|
2345
|
-
timeout: 5000,
|
|
2664
|
+
// createSQLiteDriver accepts a SQLiteDriverOptions bag and returns a SQLiteDriverInterface:
|
|
2665
|
+
const driver = createSQLiteDriver({
|
|
2666
|
+
path: 'data/reports.sqlite',
|
|
2346
2667
|
references: true,
|
|
2347
|
-
pragmas: {
|
|
2668
|
+
pragmas: { synchronous: 'FULL' }, // applied after the WAL default, in order
|
|
2348
2669
|
})
|
|
2670
|
+
const reports = createDatabase({ driver, tables: { reports: { id: stringShape() } } })
|
|
2671
|
+
await reports.table('reports').set({ id: 'r1' })
|
|
2672
|
+
driver.pragma('journal_mode') // 'wal'
|
|
2673
|
+
driver.pragma('synchronous') // 2
|
|
2349
2674
|
```
|
|
2350
2675
|
|
|
2351
2676
|
`SQLiteDriver` is the fully-native backend — it implements every optional
|
|
@@ -2364,17 +2689,72 @@ metadata. The same call inside a callback transaction uses a SQLite savepoint:
|
|
|
2364
2689
|
the wrapper deliberately provides raw `execute`, not a savepoint manager, so the
|
|
2365
2690
|
driver owns one guarded fixed internal SQL literal. If caller code catches its
|
|
2366
2691
|
failure, the failed inner migration is rolled back to that savepoint while the
|
|
2367
|
-
surrounding transaction remains active and may continue safely.
|
|
2368
|
-
|
|
2369
|
-
|
|
2692
|
+
surrounding transaction remains active and may continue safely. A list write or insert
|
|
2693
|
+
uses one prepared statement per row, as one transaction outside a scope and inside the same
|
|
2694
|
+
savepoint form within one, so a conflicting row applies none of the batch; a list read and a
|
|
2695
|
+
list delete are each one statement with the keys bound as one JSON parameter. Public
|
|
2696
|
+
`close()` contains its complete native body inside `#guard`; no raw SQLite fault crosses the driver boundary. Candidate
|
|
2370
2697
|
schema state becomes live only after the native commit. Point `write` / `insert` /
|
|
2371
2698
|
`delete` check `OperationOptions.signal`
|
|
2372
2699
|
immediately before the synchronous SQLite call; that call entry is the commit
|
|
2373
2700
|
point, so there is no post-check that could relabel a completed commit.
|
|
2374
2701
|
|
|
2702
|
+
A writable file opens under `journal_mode = WAL`, issued ahead of the `pragmas` entries, unless
|
|
2703
|
+
`pragmas` names `journal_mode`; a `':memory:'` database and a `readonly`
|
|
2704
|
+
open keep their journal. The driver issues no other pragma: `synchronous` keeps the engine
|
|
2705
|
+
build's default, which is `FULL` on the SQLite that Node 22.23.5 bundles, and the busy timeout
|
|
2706
|
+
stays 0 unless the application sets `timeout`. A refused journal mode raises nothing, so an
|
|
2707
|
+
application that requires WAL reads `journal_mode` back through the `pragma` method.
|
|
2708
|
+
|
|
2709
|
+
Every driver transaction opens with `BEGIN IMMEDIATE`: a scope, a list write's commit, a root
|
|
2710
|
+
`migrate`, and the open's schema transaction. A contended writer is refused at its start,
|
|
2711
|
+
ahead of any work, and a set busy timeout applies there. One driver per file is the supported
|
|
2712
|
+
shape. Two connections on one thread never resolve by waiting, because the holder cannot
|
|
2713
|
+
advance while the waiter blocks the thread: with no `timeout`, the waiter's scope is refused at
|
|
2714
|
+
once as `DRIVER` with `context.retryable`, a read on it returns, and its scope runs after the
|
|
2715
|
+
holder settles, so share one driver instead. Set `timeout` only when another process or a
|
|
2716
|
+
worker thread opens the file; the wait blocks the event loop for up to its length, and the
|
|
2717
|
+
waiting scope runs after the holder commits. A copy of the main file alone misses the WAL.
|
|
2718
|
+
The application decides whether to retry a refusal.
|
|
2719
|
+
|
|
2720
|
+
The `pragma` method of the `SQLiteDriverInterface` that `createSQLiteDriver` returns runs
|
|
2721
|
+
`PRAGMA name` with no value and returns the first value the engine answers, or `undefined`
|
|
2722
|
+
when it answers no row. A name the engine treats as an action runs that action. A name that
|
|
2723
|
+
fails `isPragmaName` from `@orkestrel/sqlite` raises `VALIDATION` ahead of any SQL, and a call
|
|
2724
|
+
while a transaction is active raises `CONFLICT`. The `pragmas` option is the one place a
|
|
2725
|
+
setting is written: each name passes `isPragmaName` and is one of `PRAGMA_NAMES`, and each
|
|
2726
|
+
value passes `isPragmaValue`, a 32-bit signed integer or a keyword of ASCII letters and
|
|
2727
|
+
underscores, at construction.
|
|
2728
|
+
|
|
2729
|
+
A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction, so an index the
|
|
2730
|
+
open created is analyzed too, and the `close` method runs nothing. Statistics are exact at a
|
|
2731
|
+
writable open of a table that holds none or whose row count changed tenfold since its
|
|
2732
|
+
statistics, and the prior statistics stand in between. The analysis reads every row of such a
|
|
2733
|
+
table, so its cost grows with the table. A busy refusal of it leaves the open in place, because
|
|
2734
|
+
it changes cost only and the next writable open analyzes again; any other refusal fails the
|
|
2735
|
+
open as `DRIVER`, so a file whose index is corrupt never opens. The busy path is unproven by
|
|
2736
|
+
test: the schema transaction takes the same write lock on the same thread immediately before the
|
|
2737
|
+
analysis, so nothing can stage the refusal between them without a seam, and a seam there
|
|
2738
|
+
would reopen it. The `pragma` method with
|
|
2739
|
+
`optimize` runs the engine's default mask, whose bounded statistics a following open keeps
|
|
2740
|
+
until the row count changes tenfold.
|
|
2741
|
+
|
|
2742
|
+
Inside the open transaction, after validation, a writable open drops every index created on
|
|
2743
|
+
a deployed table (`origin` `c` in `pragma_index_list`) whose name the deployed schema does not
|
|
2744
|
+
derive, so the file's created indexes equal the deployed schema's; an index is derived data,
|
|
2745
|
+
so a drop loses no row. A `readonly` open drops nothing, and an undeclared unique index still
|
|
2746
|
+
raises `DRIVER`.
|
|
2747
|
+
|
|
2748
|
+
Each open connection is a `SQLiteConnection`, which keeps up to `STATEMENT_LIMIT` prepared
|
|
2749
|
+
statements keyed by SQL text and evicts the least recently used. Point and list reads, list
|
|
2750
|
+
deletes, writes, pages, counts, and aggregates reuse them; a stream prepares its own statement,
|
|
2751
|
+
because a statement with an open iterator cannot run again. The `close` method and the next
|
|
2752
|
+
`open` drop the cache with the connection. A cached point read skips the statement's compile,
|
|
2753
|
+
which `tests/src/server/drivers/SQLiteDriver.bench.ts` reads beside the wrapper alone.
|
|
2754
|
+
|
|
2375
2755
|
### Persistence with the IndexedDB driver
|
|
2376
2756
|
|
|
2377
|
-
Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query
|
|
2757
|
+
Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query the driver answers with a key range:
|
|
2378
2758
|
|
|
2379
2759
|
```ts
|
|
2380
2760
|
import { createDatabase } from '@orkestrel/database'
|
|
@@ -2392,7 +2772,7 @@ if (typeof indexedDB !== 'undefined') {
|
|
|
2392
2772
|
.table('users')
|
|
2393
2773
|
.query()
|
|
2394
2774
|
.condition({ column: 'id', operator: 'equals', values: ['u1'], connector: 'and' })
|
|
2395
|
-
.collect() //
|
|
2775
|
+
.collect() // answered by a key range on the primary key
|
|
2396
2776
|
}
|
|
2397
2777
|
```
|
|
2398
2778
|
|
|
@@ -2404,50 +2784,80 @@ publishing schema/identity/connection state or changing the record. The
|
|
|
2404
2784
|
bootstrap closes in every outcome, so external repair or version activity is
|
|
2405
2785
|
not blocked and the same driver may retry. It then connects the deployed
|
|
2406
2786
|
`DriverMetadata.schema` plus `__metadata__`; it does not create the target declaration
|
|
2407
|
-
before reconciliation.
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2787
|
+
before reconciliation.
|
|
2788
|
+
|
|
2789
|
+
`open()` drops every index of a deployed table that the deployed schema does not declare: the
|
|
2790
|
+
stored schema of a versioned database, and the declared schema of an unversioned one. It
|
|
2791
|
+
drops them on its own connection at the next version, then makes its final open pinned for
|
|
2792
|
+
a versioned database and unpinned for an unversioned one, and a dropped index loses no row.
|
|
2793
|
+
When another connection bumps the version between the driver's read of it and that
|
|
2794
|
+
upgrade, `open()` rejects with `DRIVER` whose `context.retryable` is `true`; call
|
|
2795
|
+
`open()` again. Two builds that declare different indexes on one unversioned database name
|
|
2796
|
+
each drop the other's index at their `open()`, and the other's next open creates it again,
|
|
2797
|
+
so give each build its own database name.
|
|
2798
|
+
|
|
2799
|
+
The plan keeps native the one access path `findAccessPlan` ranks first, with the order, the
|
|
2800
|
+
page, `count`, `minimum`, and `maximum` that path serves (`planIndexedDBQuery`), and the
|
|
2801
|
+
core engine runs the rest — see [Plans and residual work](#plans-and-residual-work) and
|
|
2802
|
+
[IndexedDB planning](#indexeddb-planning). A stream and `scan` read at most
|
|
2803
|
+
`STREAM_BATCH_SIZE` rows per transaction and resume after the final key of each batch,
|
|
2804
|
+
because a transaction cannot stay open across your awaits. A native page reads no row past
|
|
2805
|
+
`offset + limit`; a page with residual conditions stops after the batch that holds its last
|
|
2806
|
+
match. A stream walking the primary key or an index
|
|
2807
|
+
holds one batch; a listed stream, an `any` or an index range read out of its index order,
|
|
2808
|
+
holds its sorted primary keys plus one batch. A direct stream applies a residual condition
|
|
2809
|
+
and page to each batch as it arrives, and only a residual order holds every match. The
|
|
2810
|
+
stream reads each batch at its own moment, so a row another write moves past the stream's
|
|
2811
|
+
position can appear twice or not at all. A stored value that is no record raises `DRIVER` with `context.code` `'RECORD'`
|
|
2812
|
+
from a read, `MIGRATION` inside `migrate()`, and the payload-safe metadata refusal from
|
|
2813
|
+
`open()` and `metadata()`; none of them carries the stored value.
|
|
2814
|
+
`IndexedDBDriver` implements `plan?` / `records?` / `aggregate?` / `stream?` / `migrate?` /
|
|
2815
|
+
`metadata?` / `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
|
|
2412
2816
|
`open()` throws `DatabaseError('VALIDATION')` if a declared table is
|
|
2413
2817
|
literally named `__metadata__`), but omits `transaction?` (the underlying
|
|
2414
2818
|
`IDBTransaction` auto-commits the moment control yields to a non-IDB
|
|
2415
|
-
`await`)
|
|
2416
|
-
IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
|
|
2819
|
+
`await`) by IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
|
|
2417
2820
|
row transformations, and the metadata write in the same versionchange
|
|
2418
2821
|
transaction; a metadata-only input uses one ordinary `__metadata__` write
|
|
2419
|
-
transaction. A failed upgrade reconnects the old deployed schema
|
|
2822
|
+
transaction. A failed upgrade reconnects the old deployed schema, pinned at the stored version
|
|
2823
|
+
when metadata is stored, so `migrate()` raises `MIGRATION` and leaves the driver usable. Each point
|
|
2420
2824
|
`write` / `insert` / `delete` still uses one explicit
|
|
2421
2825
|
wrapper `database.write(table, scope)` transaction: the signal aborts it only
|
|
2422
2826
|
while active, a signal-driven rollback maps to `DatabaseError('ABORTED')`, and
|
|
2423
2827
|
native transaction completion is the commit boundary a late abort cannot
|
|
2424
2828
|
rewrite.
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
`
|
|
2429
|
-
|
|
2430
|
-
`
|
|
2431
|
-
|
|
2432
|
-
`
|
|
2433
|
-
|
|
2434
|
-
Failed query-builder validation does not mutate builder state. `count` and
|
|
2435
|
-
`aggregate` validate paging even though valid paging remains intentionally
|
|
2436
|
-
ignored by their unpaged semantics.
|
|
2829
|
+
A table checks paging inside the query door: `limit` and `offset`, when present, must be
|
|
2830
|
+
nonnegative integers, and zero is legal. Every table and query path refuses with one evidence
|
|
2831
|
+
shape, `VALIDATION` with `table` and `faults`, a fault at `['limit']` or `['offset']`.
|
|
2832
|
+
`Query.limit` and `Query.offset` refuse synchronously through the same door and leave the
|
|
2833
|
+
builder unchanged; `Table.records`, `count`, and `aggregate` return a rejected promise; and
|
|
2834
|
+
`Table.scan` raises at its first step. `count` and `aggregate` check paging even though their
|
|
2835
|
+
unpaged semantics ignore it. A driver's own hooks (`records`, `stream`, `aggregate`, and the
|
|
2836
|
+
SQL compilers) keep `validatePage`, whose `VALIDATION` context names the `field` and its
|
|
2837
|
+
`value`, rendering `NaN` and infinity as strings.
|
|
2437
2838
|
|
|
2438
2839
|
### IndexedDB planning
|
|
2439
2840
|
|
|
2440
|
-
The pure planner behind `IndexedDBDriver`'s `plan`
|
|
2441
|
-
|
|
2841
|
+
The pure planner behind `IndexedDBDriver`'s `plan` shows which access path a read takes
|
|
2842
|
+
before the read touches a browser database. When every connector is `and`, it ranks the
|
|
2843
|
+
paths the conditions admit by a fixed rule, because IndexedDB has no statistics and reads
|
|
2844
|
+
one index per read: primary-key `equals` or `any` first, then a compound index matched on
|
|
2845
|
+
two or more columns, then a single-column index with `equals` or `any` beside a compound index
|
|
2846
|
+
whose leading column alone an `equals` binds, then a range or `starts` on the primary key or
|
|
2847
|
+
an index. An index holds no entry for a row whose field is
|
|
2848
|
+
absent or `null`, so `below`, `to`, an order, `minimum`, and `maximum` read an index only
|
|
2849
|
+
for a column declared required. `any` reads one `get(keys)` on the primary key, or one
|
|
2850
|
+
`only` range per value on an index sorted into primary-key order, and its page reads the
|
|
2851
|
+
listed keys first and only the page's rows. When the access path and the order's path
|
|
2852
|
+
differ, the access path wins and the order sorts as residual:
|
|
2442
2853
|
|
|
2443
2854
|
```ts
|
|
2444
2855
|
import type { Condition, TableSchema } from '@orkestrel/database'
|
|
2445
2856
|
import { isKey } from '@orkestrel/database'
|
|
2446
2857
|
import {
|
|
2447
2858
|
conditionToRange,
|
|
2448
|
-
deriveAccessPlan,
|
|
2449
2859
|
deriveIndexedDBIndexName,
|
|
2450
|
-
|
|
2860
|
+
findAccessPlan,
|
|
2451
2861
|
planIndexedDBQuery,
|
|
2452
2862
|
} from '@orkestrel/database/browser'
|
|
2453
2863
|
|
|
@@ -2457,8 +2867,9 @@ const schema: TableSchema = {
|
|
|
2457
2867
|
columns: [
|
|
2458
2868
|
{ name: 'id', storage: 'text', optional: false, nullable: false },
|
|
2459
2869
|
{ name: 'age', storage: 'integer', optional: false, nullable: false },
|
|
2870
|
+
{ name: 'city', storage: 'text', optional: true, nullable: false },
|
|
2460
2871
|
],
|
|
2461
|
-
indexes: [['age']],
|
|
2872
|
+
indexes: [['age'], ['city']],
|
|
2462
2873
|
}
|
|
2463
2874
|
|
|
2464
2875
|
isKey('u1') // true — a string is a usable IndexedDB key
|
|
@@ -2473,15 +2884,21 @@ const equalsAge: Condition = {
|
|
|
2473
2884
|
}
|
|
2474
2885
|
conditionToRange(equalsAge) // an IDBKeyRange.only(30) — an exact comparison operator
|
|
2475
2886
|
|
|
2476
|
-
// No condition narrows, so the plan reads the whole store
|
|
2477
|
-
planIndexedDBQuery({}, schema, ['age']) // { native: {}, residual: {} }
|
|
2887
|
+
// No condition narrows, so the plan reads the whole store; the page is native:
|
|
2888
|
+
planIndexedDBQuery({ limit: 10 }, schema, ['age', 'city']) // { native: { limit: 10 }, residual: {} }
|
|
2478
2889
|
|
|
2479
|
-
// A
|
|
2890
|
+
// A range over the required `age` index is the access path, and it serves an order on age:
|
|
2480
2891
|
const fromAge: Condition = { column: 'age', operator: 'from', values: [18], connector: 'and' }
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2892
|
+
const byAge = [{ column: 'age', direction: 'descending' as const }]
|
|
2893
|
+
planIndexedDBQuery({ conditions: [fromAge], order: byAge, limit: 10 }, schema, ['age', 'city'])
|
|
2894
|
+
// { native: { conditions: [fromAge], order: byAge, limit: 10 }, residual: {} }
|
|
2895
|
+
|
|
2896
|
+
// `below` on the optional `city` column would miss rows without a city, so it stays residual:
|
|
2897
|
+
const belowCity: Condition = { column: 'city', operator: 'below', values: ['m'], connector: 'and' }
|
|
2898
|
+
planIndexedDBQuery({ conditions: [belowCity] }, schema, ['age', 'city'])
|
|
2899
|
+
// { native: {}, residual: { conditions: [belowCity] } }
|
|
2900
|
+
findAccessPlan({ conditions: [fromAge] }, schema, ['age', 'city'])
|
|
2901
|
+
// { conditions: [fromAge], columns: ['age'], prefix: 0, index: 'age', range: an IDBKeyRange bounding age >= 18 }
|
|
2485
2902
|
```
|
|
2486
2903
|
|
|
2487
2904
|
### IndexedDB error mapping
|
|
@@ -2497,15 +2914,15 @@ import { mapIndexedDBError, mapMigrationError } from '@orkestrel/database/browse
|
|
|
2497
2914
|
declare const fault: IndexedDBError // a caught backend fault
|
|
2498
2915
|
|
|
2499
2916
|
mapIndexedDBError(fault) // → DatabaseError('CONFLICT' | 'CLOSED' | 'DRIVER', ...)
|
|
2500
|
-
mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATION'
|
|
2917
|
+
mapMigrationError(fault) // → the same, but an UPGRADE or a RECORD fault becomes 'MIGRATION'
|
|
2501
2918
|
```
|
|
2502
2919
|
|
|
2503
2920
|
### Practices
|
|
2504
2921
|
|
|
2505
2922
|
- **Declare tables in `createDatabase({ tables })` and hold the handles** —
|
|
2506
2923
|
`const users = db.table('users')`; reuse them rather than re-resolving.
|
|
2507
|
-
- **Writes admit whole, reads narrow.** At an unknown-input boundary,
|
|
2508
|
-
loose data (`'41'`) through `
|
|
2924
|
+
- **Writes admit whole, reads narrow.** At an unknown-input boundary, repair
|
|
2925
|
+
loose data (`'41'`) through `repairValue(table.contract, input)` and write
|
|
2509
2926
|
its value; a refusal carries the faults to report. Trust `get` / `records`
|
|
2510
2927
|
to return the row type.
|
|
2511
2928
|
- **Use `resolve` when absence is an error**, `get` when it is expected —
|
|
@@ -2527,7 +2944,39 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
|
|
|
2527
2944
|
- **Use `MemoryDriver` for tests and ephemeral data** — no I/O, and
|
|
2528
2945
|
`JSONDriver` swaps in unchanged when writes need to survive a restart.
|
|
2529
2946
|
|
|
2530
|
-
## Migrating from 0.0.
|
|
2947
|
+
## Migrating from 0.0.24
|
|
2948
|
+
|
|
2949
|
+
The coverage wave changes these exports and behaviors; each consumer changes in the release
|
|
2950
|
+
that adopts it. A name in this section that the package no longer exports is written plain.
|
|
2951
|
+
|
|
2952
|
+
| 0.0.24 | This release |
|
|
2953
|
+
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2954
|
+
| DriverInterface.snapshot, on `MemoryDriver`, `JSONDriver`, `SQLiteDriver`, and `IndexedDBDriver` | Removed; a scope on a driver without `transaction?` runs through `StorageJournal`, and a custom driver drops the member |
|
|
2955
|
+
| A custom `StorageInterface` with single-key `read`, `write`, `insert`, and `delete` | Each member adds its list overload: `read(table, keys)`, `write(table, keys, rows, options?)`, `insert(table, keys, rows, options?)`, and `delete(table, keys, options?)`, each one call that applies every row or none |
|
|
2956
|
+
| A `Table` batch (`set`, `add`, `update`, `remove` of a list) that kept the rows ahead of a failure | The batch applies no row; a caller that relied on the earlier rows writes them as their own batch |
|
|
2957
|
+
| An abort between the items of a batch | The signal is checked at entry and at the driver's commit point; an abort ahead of the commit applies no row |
|
|
2958
|
+
| `Table.remove(keys)` answering one boolean per key | One boolean, true only when every distinct listed key held a row and was removed, a repeated key counting as one; `has(keys)` keeps one answer per key |
|
|
2959
|
+
| A read naming an undeclared column in a condition, an ordering term, or the aggregate, an unknown operator, connector, or direction, a wrong arity, an empty or non-string column path, or an operand of another storage class, answered with 0 or every row | `VALIDATION` with `table` and every fault, raised before any driver call; a caller corrects the read |
|
|
2960
|
+
| A fractional or negative `limit` or `offset` refused without `table` | The door refuses it with `VALIDATION` and `table`, and `scan` raises at its first step instead of at the call |
|
|
2961
|
+
| A non-string operand of `like`, `glob`, `starts`, or `ends`, or a `null` read, matching no row | `VALIDATION` |
|
|
2962
|
+
| An unknown aggregate operation answering a maximum, or a missing column raising a raw `TypeError` | `VALIDATION` naming `aggregate.operation` or `aggregate.column` |
|
|
2963
|
+
| `null` on a column that is not nullable, `undefined` on one that is not optional, or either under a range operator, matching no row | `VALIDATION`; read absence with `absent` or `present` |
|
|
2964
|
+
| A lone surrogate in a `text` value, a key, or a text operand, stored by SQLite as U+FFFD | `VALIDATION` with `table` and `column` on every driver |
|
|
2965
|
+
| A `literalShape` column whose members span more than one class, stored as `text` | `json` storage, as a union is |
|
|
2966
|
+
| findAccessCondition(input, schema, indexes) and deriveAccessPlan(condition, schema) | `findAccessPlan(input, schema, indexes)`, which returns the ranked `AccessPlan`: its `conditions`, `columns`, `prefix`, and `index`, `range`, or `keys` |
|
|
2967
|
+
| `AccessPlan` as `{ index?, range? }` | `{ conditions, columns, prefix, index?, range?, keys? }`; `{}` as a whole-store read is `{ conditions: [], columns: [primary], prefix: 0 }` |
|
|
2968
|
+
| `IndexedDBDriver` answering one condition natively and reading every candidate row for an order, a page, or a count | It ranks one access path, serves the order, page, `count`, `minimum`, and `maximum` that path serves, declares `aggregate?`, and streams in batches of `STREAM_BATCH_SIZE` |
|
|
2969
|
+
| An undeclared index surviving `IndexedDBDriver.open()` | `open()` drops it on a connection at the next version; a concurrent bump raises `DRIVER` with `context.retryable` |
|
|
2970
|
+
| A stored IndexedDB value that is no record | A read raises `DRIVER` with `context.code` `'RECORD'`; `migrate()` raises `MIGRATION`; the metadata record raises the metadata-invalid refusal |
|
|
2971
|
+
| A transaction on `MemoryDriver` or `IndexedDBDriver` that copied the whole store | The journal reads and restores only the keys the scope touched, and a `clear` journals its table alone |
|
|
2972
|
+
| `createSQLiteDriver` returning `DriverInterface` | It returns `SQLiteDriverInterface`, which adds the `pragma` method; `SQLiteDriver` implements it |
|
|
2973
|
+
| A SQLite scope, list write, and `migrate` opening with a deferred `BEGIN` | Each opens with `BEGIN IMMEDIATE`; a contended scope is refused at its start, before its callback runs |
|
|
2974
|
+
| A writable SQLite file keeping the engine's journal mode | It opens under `journal_mode = WAL` unless `pragmas` names `journal_mode`; a `':memory:'` database and a `readonly` open keep theirs |
|
|
2975
|
+
| A SQLite open that analyzed nothing | A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction; the `close` method runs nothing |
|
|
2976
|
+
| An index created on a deployed SQLite table and no longer declared, kept at open | A writable open drops it; a `readonly` open drops nothing |
|
|
2977
|
+
| A `pragmas` value that is any finite number | A value is a 32-bit signed integer or a bare keyword, through `isPragmaValue` |
|
|
2978
|
+
| An integer `sum` past 2^53 on SQLite raising `DRIVER` | `sum` compiles to `TOTAL`, the engine's float sum, with `undefined` over no value |
|
|
2979
|
+
| An order on a SQLite column that is both optional and nullable, and the equality family on a nested path, read by the core | The order is native behind a rank term, and the equality family with scalar operands under a `json` head is a prefilter the core rechecks |
|
|
2531
2980
|
|
|
2532
2981
|
The paging wave changes these exports and behaviors; under the no-shim law, each consumer
|
|
2533
2982
|
changes in the release that adopts it. A name in this section that the package no longer
|
|
@@ -2539,7 +2988,7 @@ exports is written plain, without code formatting.
|
|
|
2539
2988
|
| `compileQuerySQL(input, schema)` | Same name and signature; pass it `planSQLiteQuery(input, schema).native`. Its SQL changes: `starts` compiles to an index range, `any` and `none` bind one `json_each` parameter, every condition beside an `any` on the primary key is pinned behind unary `+`, and the primary-key tie term carries the final order term's direction |
|
|
2540
2989
|
| matchesConditionExactly | `matchesSQLiteCondition(condition, schema)` |
|
|
2541
2990
|
| matchesOrderExactly, matchesAggregateExactly, EXACT_COLUMN_STORAGE, EXACT_RANGE_COLUMN_STORAGE | Removed; `planSQLiteQuery` answers each question |
|
|
2542
|
-
| selectPlan(input, schema, indexes) | `
|
|
2991
|
+
| selectPlan(input, schema, indexes) | `findAccessPlan(input, schema, indexes)` for the access path, and `planIndexedDBQuery(input, schema, indexes)` for the split |
|
|
2543
2992
|
| QueryPlan | `AccessPlan` |
|
|
2544
2993
|
| `MemoryDriver.stream`, `JSONDriver.stream` | Removed; call `Table.scan`, or `streamPlannedRows` over the driver |
|
|
2545
2994
|
| `matchesWildcardSegment(value: string, segment: string, …)` | `matchesWildcardSegment(value: readonly string[], segment: readonly string[], …)`, over code points |
|
|
@@ -2548,7 +2997,7 @@ exports is written plain, without code formatting.
|
|
|
2548
2997
|
| A read that skipped a nonconforming stored row | `get`, `records`, and `scan` raise `DRIVER` with `table`, `key`, and `faults` |
|
|
2549
2998
|
| `count` skipping a nonconforming stored row | `count` is `aggregate('count')`: it counts every stored row its conditions match, a nonconforming row included, and raises nothing, because it returns no row |
|
|
2550
2999
|
| A driver with `records`, `stream`, or `aggregate` and no `plan` | The core never calls those hooks and reads the driver over `scan`; a custom driver adds `plan` to keep its pushdown |
|
|
2551
|
-
| Any `pragmas` entry on `createSQLiteDriver` | Each name must be one of `PRAGMA_NAMES`, matched exactly, and each value
|
|
3000
|
+
| Any `pragmas` entry on `createSQLiteDriver` | Each name must pass `isPragmaName` and be one of `PRAGMA_NAMES`, matched exactly, and each value must pass `isPragmaValue`; anything else throws `VALIDATION` at construction |
|
|
2552
3001
|
| `compileConditionSQL` and `compileQuerySQL` leaving `equals` / `not` with `undefined`, and lists holding `null` or `undefined`, to the core | Each compiles natively: `undefined` to `IS NULL` / `IS NOT NULL` on a column that stores absence, and a list to `IN (…)` joined with the null and absence tests its flags define, the `none` complement included |
|
|
2553
3002
|
|
|
2554
3003
|
The paging wave added names that its review then renamed or folded before release:
|
|
@@ -2563,31 +3012,42 @@ to `Scalar`.
|
|
|
2563
3012
|
## Tests
|
|
2564
3013
|
|
|
2565
3014
|
- [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ compiler-resolved public-entry bijection across `src/core`, `src/server`, and `src/browser`, including fail-closed temporary-project coverage for barrel resolution and unsupported exports, each interface ↔ implementing-class method bijection, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Create a database` fence against the `@example` block of that title (pinned so the titled pair cannot be retired silently), and the README pitch against this guide's tagline. It also compiles every TypeScript fence against the published entry specifiers and runs the flagship fences, asserting the values their comments claim.
|
|
2566
|
-
- [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — `cloneDriverMetadata` ownership: normalized deeply frozen distinct output, caller-mutation isolation, and `VALIDATION` translation for malformed, cyclic, functional, accessor, and
|
|
3015
|
+
- [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — `cloneDriverMetadata` ownership: normalized deeply frozen distinct output, caller-mutation isolation, and `VALIDATION` translation for malformed, cyclic, functional, accessor, and unexpected/revoked-proxy inputs without leaking raw Contract or caller errors; `normalizeDriverSchema`'s sorted, deeply frozen canonical snapshot and its `VALIDATION` refusal.
|
|
3016
|
+
- [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — `planMigration`'s step order and its `MIGRATION` throw on a shared column's storage/nullability drift, and `projectMigrationSchema`'s sequential projection.
|
|
2567
3017
|
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — total boundary guards for keys, columns, tables, driver schemas, migrations, inputs, and metadata.
|
|
2568
|
-
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the query engine: `validatePage`'s strict page matrix, deterministic field order, exact non-finite diagnostics, and legal zero; `findColumn`'s flat-column lookup and its `undefined` miss; `resolvePrimary`'s declared-or-default key and `requireColumns`'s typed map lookup with its `NOT_FOUND` throw; `compareValues` total order, every `matchesCondition` operator (the equality family — `equals` / `not` / `any` / `none` — through `equalsValue`, including `NaN`-equals-`NaN`; the range family through `compareValues`), `matchesQuery` folding, `filterRows`, `sortRows`, `applyQuery`, `computeAggregate`, `extractKey`, `shapeToColumnStorage`'s shape → portable-type mapping (scalars, `json` for object/array/union/raw, optional/nullable unwrap, literal-by-values), total `isDriverMetadata` rejection of malformed and
|
|
2569
|
-
- [`tests/src/core/drivers/MemoryDriver.test.ts`](../tests/src/core/drivers/MemoryDriver.test.ts) — the driver primitive: `open(schema)` readies tables, read/write/atomic-insert/delete/keys/scan/clear
|
|
3018
|
+
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the query engine: `validatePage`'s strict page matrix, deterministic field order, exact non-finite diagnostics, and legal zero; `findColumn`'s flat-column lookup and its `undefined` miss; `resolvePrimary`'s declared-or-default key and `requireColumns`'s typed map lookup with its `NOT_FOUND` throw; `compareValues` total order, every `matchesCondition` operator (the equality family — `equals` / `not` / `any` / `none` — through `equalsValue`, including `NaN`-equals-`NaN`; the range family through `compareValues`), `matchesQuery` folding, `filterRows`, `sortRows`, `applyQuery`, `computeAggregate`, `extractKey`, `shapeToColumnStorage`'s shape → portable-type mapping (scalars, `json` for object/array/union/raw, optional/nullable unwrap, literal-by-values), total `isDriverMetadata` rejection of malformed and unexpected getter/proxy input, `equalsValue`'s structural equality, and the `scanDriver` / `conformDriver` / `auditDriver` battery against `MemoryDriver` and a deliberately-broken driver (each check fails with a `CONFORMANCE` `DatabaseError`), including the deepened `write-read` nested-field checks, the journal phase (a shallow-copying driver fails it), and the batch phase (a per-row list insert fails it); `buildBatch`'s pairing and refusals and `computeRemoved`'s first-occurrence rule.
|
|
3019
|
+
- [`tests/src/core/drivers/MemoryDriver.test.ts`](../tests/src/core/drivers/MemoryDriver.test.ts) — the driver primitive: `open(schema)` readies tables, read/write/atomic-insert/delete/keys/scan/clear, list reads in key order, list writes and inserts that apply every row or none, list deletes that report each key once, duplicate-insert `CONFLICT`, non-JSON row isolation through native `structuredClone`, metadata stamp/migrate/copy-out ownership through `cloneDriverMetadata`, strict stream paging, and pre-aborted point mutations rejecting `ABORTED` without changing rows.
|
|
2570
3020
|
- [`tests/src/core/Database.test.ts`](../tests/src/core/Database.test.ts) — declared tables, lazy connect, typed CRUD, custom keys, indexes, import/export, and callback transactions: whole accepted-operation drain, synchronous-throw and asynchronous-rejection reason identity, caught-operation rejection still rolling back, callback-over-drain error precedence, root/import/lifecycle/nesting barriers, stale scoped table/query/cursor/stream invalidation, and truthful successful-rollback-only events. It also covers explicit migration and versioned open: deployed-schema-first reconciliation, fresh stamp, same-version no-op, atomic upgrade input, higher-version rejection, paired-hook enforcement (metadata-only and stamp-only are inert), and migrate-event behavior.
|
|
2571
3021
|
- [`tests/src/core/ScopedIterator.test.ts`](../tests/src/core/ScopedIterator.test.ts) — direct internal continuation-lifetime coverage: tracked `next` / `return` / `throw`, the readiness thunk running before every advance and its failure preempting the source, synchronous source throws, missing methods, concurrent accepted continuations, idle iterators, late conflicts, and exactly-once rejected cleanup.
|
|
2572
3022
|
- [`tests/src/core/DriverIterator.test.ts`](../tests/src/core/DriverIterator.test.ts) — direct root-driver continuation coverage: pre/post-read guards, produced-row discard, terminalization, return races, missing methods, throw delegation, and exactly-once cleanup.
|
|
2573
|
-
- [`tests/src/core/Table.test.ts`](../tests/src/core/Table.test.ts) — `Table`'s keyed CRUD + batch overloads, payload-safe bounded contract diagnostics, strict paging at every read boundary, whole-row admission with its
|
|
3023
|
+
- [`tests/src/core/Table.test.ts`](../tests/src/core/Table.test.ts) — `Table`'s keyed CRUD + batch overloads, payload-safe bounded contract diagnostics, strict paging at every read boundary, whole-row admission with its refusals of a mistyped value (a numeric string included), an undeclared column, a missing column, and two faults at once, each fault named in the message, and the raw-column nested-key admission, `add` dispatch through atomic `insert` (including concurrent duplicate claims), one driver call per batch read through a `StorageRecorder`, batches that apply every row or none, a list `remove` that answers true only when every distinct listed key held a row and was removed, a repeated key counting as one (a transaction view included), empty lists that answer and touch no row, and the emitter's post-commit and no-aborted-event behavior. The query door: every refusal class through `records`, `count`, `aggregate`, `scan`, and each `query()` terminal with no driver call, the reads admitted at each class's edge, and a lone surrogate refused in a written `text` value and a key.
|
|
2574
3024
|
- [`tests/src/core/Query.test.ts`](../tests/src/core/Query.test.ts) — `Query`'s where / and / or dispatch, ordering, synchronous strict page builders with no failed mutation, legal zero, `filter`, and aggregates.
|
|
3025
|
+
- [`tests/src/core/contracts.test.ts`](../tests/src/core/contracts.test.ts) — `queryInputContract`: each operator's arity on both sides, the operator candidates of an unknown operator, the column forms, and the closed object.
|
|
3026
|
+
- [`tests/src/core/StorageRecorder.test.ts`](../tests/src/core/StorageRecorder.test.ts) — the recorder over real drivers: rows returned and yielded per member, scoped calls inside a native transaction, the members it declares, a rejected call and an unpulled stream each counted as invoked, and a stream abandoned early or failing part way.
|
|
3027
|
+
- [`tests/src/core/RecordedStorage.test.ts`](../tests/src/core/RecordedStorage.test.ts) — each call reported as it is invoked with its keys and rows, a rejected call and an unpulled scan counted, each keyed call forwarded in its received form, and a scan that throws part way.
|
|
3028
|
+
- [`tests/src/core/Table.bench.ts`](../tests/src/core/Table.bench.ts) — the point read on a held table and through `database.table(name)`, a scope with one read, and the door on a ten-condition count, beside a published build that `DATABASE_BASELINE` names; `npm run test:bench` runs it and no gate does.
|
|
3029
|
+
- [`tests/src/core/StorageJournal.test.ts`](../tests/src/core/StorageJournal.test.ts) — the before-image journal over a real `MemoryDriver`: restore of updated, inserted, and deleted keys, one list read per call and one restore call per kind, no call when nothing was recorded, and the adverse orderings (unawaited writes to one key, a write on each side of a `clear`, a table cleared alone, a failed prior read that records nothing so a later write records its prior row, a delayed prior read that a later write to the same key waits on, a mismatched batch).
|
|
3030
|
+
- [`tests/src/core/ScopedStorage.test.ts`](../tests/src/core/ScopedStorage.test.ts) — the scoped-storage lifetime boundary: forwarding of each member's single and list forms, refusal of every member once the guard throws, and a scan advance refused after the scope settles.
|
|
2575
3031
|
- [`tests/src/core/Cursor.test.ts`](../tests/src/core/Cursor.test.ts) — cursor behavior over a key snapshot: `value` / `index` / `done`, serialized overlapping `next` / `update` / `remove`, rejection recovery, synchronous runner admission, terminal close before queued work and during dispatched reads/mutations, plus transaction-ledger regressions for deleted-key skipping, unawaited normalized updates, validation rollback, and retained closed/active conflicts.
|
|
2576
3032
|
- [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — `createDatabase` / `createMemoryDriver` each return a working instance of their interface (a round-trip end to end).
|
|
2577
3033
|
- [`tests/src/core/TransactionScope.test.ts`](../tests/src/core/TransactionScope.test.ts) — direct transaction-lifetime coverage: `accepting` and the `check` refusal, synchronous admission through `track`, a synchronous operation throw captured as a rejection, unawaited work contained by `drain`, the drain loop re-reading work another tracked operation admitted, first-failure identity preserved across repeated drains, and `stream`'s per-continuation boundary leaving an idle iterator unpinned.
|
|
2578
3034
|
- [`tests/src/core/DatabaseContext.test.ts`](../tests/src/core/DatabaseContext.test.ts) — direct shared-context coverage: `register`'s identical-schema merge, its `VALIDATION` conflict, and its `CONFLICT` / `CLOSED` refusals; idle → open → closed transitions emitted once with one shared readiness promise; root admission, its transaction-time `CONFLICT`, and close-time drain; transaction commit / rollback events and value or error propagation, nested-transaction refusal, entry-only signal checking, and a fresh `TransactionScope` per attempt; explicit migration's missing-hook and post-open refusals; and versioned reconciliation's fresh stamp, newer-store rejection, differing-schema rejection, and same-version no-op.
|
|
2579
3035
|
- [`tests/src/core/DatabaseTransaction.test.ts`](../tests/src/core/DatabaseTransaction.test.ts) — direct transaction-view coverage: the typed table `table()` builds over the scoped driver, its writes landing straight on that driver, the scope `CONFLICT` after settlement, the `NOT_FOUND` refusal for an undeclared table, a per-table primary override, a scoped table refusing work started after settlement, and the configured generator minting a key for a keyless write.
|
|
2580
3036
|
- [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) — `createJSONDriver` / `createSQLiteDriver` each return a working `DriverInterface` instance (a round-trip end to end), drive the core `createDatabase` stack, and persist across a reopen; `createSQLiteDriver` requires a path and opens an in-memory database only with `path: ':memory:'`.
|
|
2581
|
-
- [`tests/src/server/drivers/JSONDriver.test.ts`](../tests/src/server/drivers/JSONDriver.test.ts) — `JSONDriver` persistence plus atomic insert and the exclusive point-mutation queue: queued abort/no late start, active staging restoration, cleanup-success error precedence, deterministic real-filesystem persistence-plus-cleanup dual failure with exact evidence and queue recovery, read isolation, concurrent-writer ordering, fail-closed real-filesystem coverage for non-absence reads, invalid syntax/documents/table sets/containers/rows/metadata, byte preservation, no partial publication, application-invalid row retention, payload-safe rejection, strict stream paging, and same-instance external-repair retry; synchronous root/scoped stamp and migration ownership, deeply frozen distinct copy-out, deployed-schema-first open, isolated callback/root-migration candidates whose rows/schema/metadata publish only after file replacement succeeds, transaction-time root scan/stream continuation conflicts with terminal cleanup, and post-native-rollback rejection replacement.
|
|
2582
|
-
- [`tests/src/server/drivers/SQLiteDriver.test.ts`](../tests/src/server/drivers/SQLiteDriver.test.ts) — `SQLiteDriver`'s native surface: deployed-metadata-first open and reconciliation; fail-closed malformed metadata, physical schema disagreement, and persisted-table loss before DDL, including deterministic first-loss evidence, physical non-recreation, external repair, and same-driver retry; root/scoped stamp/migration ownership and distinct deeply frozen copy-out; atomic insert/duplicate `CONFLICT`; point-mutation abort boundaries; strict direct records/aggregate/stream paging; native planned query and aggregate paths, the paging readings, the operator matrix, and `EXPLAIN QUERY PLAN` of the native plan;
|
|
3037
|
+
- [`tests/src/server/drivers/JSONDriver.test.ts`](../tests/src/server/drivers/JSONDriver.test.ts) — `JSONDriver` persistence plus atomic insert and the exclusive point-mutation queue: an empty list that leaves the file in place, a failed clear flush that leaves every row in memory, queued abort/no late start, active staging restoration, cleanup-success error precedence, deterministic real-filesystem persistence-plus-cleanup dual failure with exact evidence and queue recovery, read isolation, concurrent-writer ordering, fail-closed real-filesystem coverage for non-absence reads, invalid syntax/documents/table sets/containers/rows/metadata, byte preservation, no partial publication, application-invalid row retention, payload-safe rejection, strict stream paging, and same-instance external-repair retry; synchronous root/scoped stamp and migration ownership, deeply frozen distinct copy-out, deployed-schema-first open, isolated callback/root-migration candidates whose rows/schema/metadata publish only after file replacement succeeds, transaction-time root scan/stream continuation conflicts with terminal cleanup, and post-native-rollback rejection replacement.
|
|
3038
|
+
- [`tests/src/server/drivers/SQLiteDriver.test.ts`](../tests/src/server/drivers/SQLiteDriver.test.ts) — `SQLiteDriver`'s native surface: deployed-metadata-first open and reconciliation; fail-closed malformed metadata, physical schema disagreement, and persisted-table loss before DDL, including deterministic first-loss evidence, physical non-recreation, external repair, and same-driver retry; root/scoped stamp/migration ownership and distinct deeply frozen copy-out; atomic insert/duplicate `CONFLICT`; point-mutation abort boundaries; strict direct records/aggregate/stream paging; native planned query and aggregate paths, the paging readings, the operator matrix, and `EXPLAIN QUERY PLAN` of the native plan; list reads and deletes as one statement, a conflicting batch that applies no row outside a scope and rolls back to its savepoint inside one, and one commit per batch read through the file change counter under a rollback journal; atomic `MigrationInput` schema/rows/metadata at the root; fixed-literal savepoint containment for a caught migration failure while its callback transaction remains active; candidate-schema publication only after commit; callback transaction barriers/invalidation including root continuation cleanup; payload-safe rejection; post-native-rollback rejection replacement; backend-fault mapping, `SQLITE_LOCKED` without `retryable` included; the rows-read tripwire `plantTripwire` plants beyond each page; `BEGIN IMMEDIATE` across two drivers on one thread and against a worker-thread holder under a `timeout`; the WAL default; statistics at a writable open; `pragma` and its name door; the index reconcile at open; native orders on a column with both flags; the nested-path prefilters per operator and scalar class; an integer `sum` as `TOTAL`; and engine parity.
|
|
3039
|
+
- [`tests/src/server/SQLiteConnection.test.ts`](../tests/src/server/SQLiteConnection.test.ts) — the per-connection statement cache: one cached statement per text, least-recently-used eviction past `STATEMENT_LIMIT` with a text used since kept.
|
|
3040
|
+
- [`tests/src/server/drivers/SQLiteDriver.bench.ts`](../tests/src/server/drivers/SQLiteDriver.bench.ts) — run by `npm run test:bench`, outside every gate: the point read, a 100-key list, an `any` of 100 keys beside a tenant, a page, a count, and a 100-row batch through `Table` beside the wrapper alone, on 80646 narrow and mixed rows.
|
|
2583
3041
|
- [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) — the SQLite bridge: `quoteIdentifier`, codecs, row extraction, `deriveSQLiteIndexName` exact bytes, the planner `planSQLiteQuery` and its `matchesSQLiteCondition` / `computeSuccessor` predicates, `validatePragmas`, strict decode, and `matchesSQLiteAffinity`.
|
|
2584
3042
|
- [`tests/src/server/compilers.test.ts`](../tests/src/server/compilers.test.ts) — the coherent SQL-emitter cluster: column/field/aggregate compilation, table/index/migration DDL, and the strict-page `QueryInput` → SQL pipeline with exact statements and parameters.
|
|
2585
|
-
- [`tests/src/server/inferers.test.ts`](../tests/src/server/inferers.test.ts) — `inferValueStorage`'s nested-operand storage inference: the `ColumnStorage` a `json_extract` operand must encode as, over booleans, integral and fractional numbers, bigints, objects and arrays, strings, `null`, and `undefined
|
|
2586
|
-
- [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `SQLiteDriver` (native and residual reads) produce identical rows/counts/aggregates, and the text-order exemption names the ids SQLite returns under its binary order.
|
|
2587
|
-
- [`tests/src/browser/drivers/IndexedDBDriver.test.ts`](../tests/src/browser/drivers/IndexedDBDriver.test.ts) — `IndexedDBDriver` against real IndexedDB: metadata-only bootstrap and deployed-schema-first reopen, one-transaction `has`/`get` absence discrimination, fail-closed malformed-metadata preservation (including stored `undefined`) and persisted-store loss with deterministic first-loss evidence, physical non-recreation, extra-store retention, external repair, and same-driver retry; bootstrap-lifetime store/version capture and a competing versionchange proving the persisted final open is pinned and retryable; payload-safe errors and table rejection, closed failed state, reserved-store validation, atomic `add` insertion and duplicate `CONFLICT`, active/pre-dispatch/late abort boundaries, strict direct records/stream paging, the plan, the rows read per conformance read
|
|
2588
|
-
- [`tests/src/browser/
|
|
3043
|
+
- [`tests/src/server/inferers.test.ts`](../tests/src/server/inferers.test.ts) — `inferValueStorage`'s nested-operand storage inference: the `ColumnStorage` a `json_extract` operand must encode as, over booleans, integral and fractional numbers, bigints, objects and arrays, strings, `null`, and `undefined`; and `inferSentinelType`'s class per storage, read against a declared table and through the `encodeValue` and `decodeValue` sentinel round trip.
|
|
3044
|
+
- [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `SQLiteDriver` (native and residual reads) produce identical rows/counts/aggregates, and the text-order exemption names the ids SQLite returns under its binary order. Each wrong-class read in its refused-parity table raises the same `VALIDATION` refusal on both engines.
|
|
3045
|
+
- [`tests/src/browser/drivers/IndexedDBDriver.test.ts`](../tests/src/browser/drivers/IndexedDBDriver.test.ts) — `IndexedDBDriver` against real IndexedDB: metadata-only bootstrap and deployed-schema-first reopen, one-transaction `has`/`get` absence discrimination, fail-closed malformed-metadata preservation (including stored `undefined`) and persisted-store loss with deterministic first-loss evidence, physical non-recreation, extra-store retention, external repair, and same-driver retry; bootstrap-lifetime store/version capture and a competing versionchange proving the persisted final open is pinned and retryable; payload-safe errors and table rejection, closed failed state, reserved-store validation, atomic `add` insertion and duplicate `CONFLICT`, active/pre-dispatch/late abort boundaries, strict direct records/stream paging, the plan, the rows read per conformance read, list reads, inserts, and deletes in one transaction each, a journal scope whose native reads see its writes, schema/rows/metadata in one versionchange migration, metadata-only migration input, failed-upgrade reconnection to the old schema, metadata persistence, backend-fault mapping, confirmation that callback `transaction` is absent, a tripwire beyond each plan class's bound that the read never reaches, the differential of every plan class against the core engine, native counts and index extremes that return no row, streams that read one batch at a time, no index entry for a row missing its field, the index reconcile at open with its retryable concurrent bump, and `DRIVER` for a stored non-record.
|
|
3046
|
+
- [`tests/src/browser/drivers/IndexedDBDriver.bench.ts`](../tests/src/browser/drivers/IndexedDBDriver.bench.ts) — a bench no gate collects: the key-list, `any`, ordered page, `equals` page, `any` count, `equals` count, and batch cells over one client-shaped store, each beside the wrapper alone; run it with `vitest bench --config vite.config.ts --project src:browser --mode benchmark`.
|
|
3047
|
+
- [`tests/src/browser/IndexedDBBatchIterator.test.ts`](../tests/src/browser/IndexedDBBatchIterator.test.ts) — `IndexedDBBatchIterator` over a real store: each batch resumes from the position the previous batch reports, a short batch ends the stream, and an empty batch ends it too.
|
|
3048
|
+
- [`tests/src/browser/helpers.test.ts`](../tests/src/browser/helpers.test.ts) — the planner: `conditionToRange` over every comparison operator and `starts`, `findAccessPlan` ranking and its required-column rule, `deriveConditionPlan`, `deriveCompoundPlan`, `buildCompoundRange`, `rankAccessPlan`, `deriveOrderPlan`, `matchesAccessOrder`, `narrowRange`, `planIndexedDBQuery`, backend-error mapping with `RECORD`, and exact `deriveIndexedDBIndexName` bytes.
|
|
2589
3049
|
- [`tests/src/browser/factories.test.ts`](../tests/src/browser/factories.test.ts) — `createIndexedDBDriver` returns a working `DriverInterface` instance (a round-trip end to end).
|
|
2590
|
-
- [`tests/src/browser/integration.test.ts`](../tests/src/browser/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `IndexedDBDriver` produce identical rows/counts, including pushdown edge cases (`below`/`to` on a secondary-indexed column, a reversed `between`).
|
|
3050
|
+
- [`tests/src/browser/integration.test.ts`](../tests/src/browser/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `IndexedDBDriver` produce identical rows/counts, including pushdown edge cases (`below`/`to` on a secondary-indexed column, a reversed `between`). Each wrong-class read in its refused-parity table raises the same `VALIDATION` refusal on both engines.
|
|
2591
3051
|
|
|
2592
3052
|
## See also
|
|
2593
3053
|
|