@orkestrel/scaffold 0.0.134 → 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 +777 -83
- package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
- package/dist/bin/main.js +254 -36
- package/dist/bin/main.js.map +1 -1
- package/dist/host/AGENTS.md +2 -2
- package/dist/host/agents/orchestration.md +2 -2
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
- package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
- package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
- package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
- package/dist/host/claude/agents/orkestrel.md +17 -17
- package/dist/host/claude/agents/reviewer.md +1 -1
- package/dist/host/claude/rules/architecture.md +1 -1
- package/dist/host/claude/rules/documentation.md +1 -1
- package/dist/host/claude/rules/patterns.md +4 -2
- package/dist/host/claude/rules/workspace.md +73 -67
- package/dist/host/configs/helpers.ts +109 -73
- package/dist/host/dotfiles/oxlintrc.json +1 -57
- package/dist/host/guides/agent.md +989 -395
- package/dist/host/guides/contract.md +198 -163
- package/dist/host/guides/database.md +978 -503
- package/dist/host/guides/indexeddb.md +80 -66
- package/dist/host/guides/middleware.md +5 -5
- package/dist/host/guides/ollama.md +41 -42
- package/dist/host/guides/relation.md +56 -32
- package/dist/host/guides/scaffold.md +185 -107
- package/dist/host/guides/sqlite.md +44 -23
- package/dist/host/guides/study.md +12 -12
- package/dist/host/guides/test.md +163 -47
- package/dist/host/guides/toolbox.md +127 -81
- package/dist/host/guides/workspace.md +21 -14
- package/dist/host/manifest.json +30 -30
- 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 +237 -115
- package/dist/src/core/index.cjs +591 -218
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +248 -29
- package/dist/src/core/index.d.ts +248 -29
- package/dist/src/core/index.js +581 -216
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +18 -8
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +4 -3
- package/dist/src/server/index.d.ts +4 -3
- package/dist/src/server/index.js +19 -9
- package/dist/src/server/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,20 +1,19 @@
|
|
|
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,
|
|
9
9
|
JSON-Schema introspection, and seed data all flow from that one
|
|
10
10
|
declaration — no separate schema, no annotations, no `as`.
|
|
11
11
|
|
|
12
|
-
The design stance is
|
|
13
|
-
|
|
14
|
-
`scan`, key listing, and
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
native hooks the engine falls back from; it never re-derives query semantics.
|
|
12
|
+
The design stance is native first, under the rule Contract invariant 3 places. A backend
|
|
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
|
+
core's engine runs only the residual. A backend without `plan` inherits the whole WHERE /
|
|
16
|
+
order / page / aggregate surface from that engine over `scan`.
|
|
18
17
|
So this is deliberately not an ORM and not a query abstraction layer: there is
|
|
19
18
|
no entity graph, no migration runner, and no raw-SQL escape hatch — only the
|
|
20
19
|
smallest cross-environment core that earns its keep.
|
|
@@ -22,12 +21,11 @@ smallest cross-environment core that earns its keep.
|
|
|
22
21
|
Source: [`src/core`](../src/core), published through `@orkestrel/database`. The
|
|
23
22
|
persistent drivers ship alongside it: a trusted-mode SQLite driver in
|
|
24
23
|
[`src/server`](../src/server) (surfaced through `@orkestrel/database/server`)
|
|
25
|
-
with native querying, paging, aggregation, transactions, and atomic migration,
|
|
26
|
-
and
|
|
27
|
-
(surfaced through `@orkestrel/database/browser`)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
`JSONDriver`.
|
|
24
|
+
with native querying, paging, counting, aggregation, transactions, and atomic migration,
|
|
25
|
+
and an IndexedDB driver in [`src/browser`](../src/browser)
|
|
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
|
+
file-persisted `JSONDriver`, whose reads the core answers over `scan`.
|
|
31
29
|
|
|
32
30
|
## Surface
|
|
33
31
|
|
|
@@ -73,41 +71,49 @@ produces the JSON Schema, and seeds fixtures.
|
|
|
73
71
|
|
|
74
72
|
### Factories
|
|
75
73
|
|
|
76
|
-
| Name | Kind | Signature | Summary
|
|
77
|
-
| ----------------------- | -------- | --------------------------------------------------------------------------------- |
|
|
78
|
-
| `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema.
|
|
79
|
-
| `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`.
|
|
80
|
-
| `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path.
|
|
81
|
-
| `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) =>
|
|
82
|
-
| `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. |
|
|
83
81
|
|
|
84
82
|
### Classes
|
|
85
83
|
|
|
86
|
-
| Name
|
|
87
|
-
|
|
|
88
|
-
| `Database`
|
|
89
|
-
| `DriverIterator`
|
|
90
|
-
| `
|
|
91
|
-
| `
|
|
92
|
-
| `
|
|
93
|
-
| `
|
|
94
|
-
| `
|
|
95
|
-
| `
|
|
96
|
-
| `
|
|
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. |
|
|
97
99
|
|
|
98
100
|
### Server
|
|
99
101
|
|
|
100
|
-
| Name
|
|
101
|
-
|
|
|
102
|
-
| `METADATA_TABLE`
|
|
103
|
-
| `
|
|
104
|
-
| `
|
|
105
|
-
| `
|
|
106
|
-
| `
|
|
107
|
-
| `
|
|
108
|
-
| `
|
|
109
|
-
| `
|
|
110
|
-
| `
|
|
102
|
+
| Name | Kind | Signature | Summary |
|
|
103
|
+
| ------------------------ | -------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
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. |
|
|
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. |
|
|
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`. |
|
|
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`. |
|
|
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. |
|
|
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. |
|
|
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. |
|
|
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. |
|
|
114
|
+
| `matchesDeclaredStorage` | function | `(value: unknown, storage: ColumnStorage) => boolean` | Reports whether an operand has the storage class a declared column stores, so a bound operand compares as the stored values do. |
|
|
115
|
+
| `extractValues` | function | `(row: SQLiteRow, names: readonly string[], table: string) => readonly SQLiteValue[]` | Extracts a stored row's values in a declared positional order. |
|
|
116
|
+
| `deriveSQLiteIndexName` | function | `(table: string, columns: readonly string[]) => string` | Builds a collision-free SQL index name for a table + column-group index — shared by the compiler module's `schemaToIndexes` and `stepToSQL`, so a plan-built index name always matches one `open` would have created. |
|
|
111
117
|
|
|
112
118
|
### SQL compilation
|
|
113
119
|
|
|
@@ -115,47 +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
|
|
119
|
-
|
|
|
120
|
-
| `inferValueStorage`
|
|
121
|
-
| `
|
|
122
|
-
| `
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
125
|
-
| `
|
|
126
|
-
| `
|
|
127
|
-
| `
|
|
128
|
-
| `
|
|
129
|
-
| `
|
|
130
|
-
| `
|
|
131
|
-
| `
|
|
132
|
-
| `
|
|
133
|
-
| `
|
|
134
|
-
| `
|
|
135
|
-
| `
|
|
136
|
-
| `
|
|
137
|
-
| `
|
|
138
|
-
| `
|
|
139
|
-
| `
|
|
140
|
-
| `
|
|
141
|
-
| `
|
|
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. |
|
|
142
155
|
|
|
143
156
|
### Browser
|
|
144
157
|
|
|
145
|
-
Pure functions behind the IndexedDB driver's
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
| Name | Kind | Signature
|
|
150
|
-
| -------------------------- | -------- |
|
|
151
|
-
| `
|
|
152
|
-
| `
|
|
153
|
-
| `
|
|
154
|
-
| `
|
|
155
|
-
| `
|
|
156
|
-
| `
|
|
157
|
-
| `
|
|
158
|
-
| `
|
|
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. |
|
|
159
185
|
|
|
160
186
|
### Errors
|
|
161
187
|
|
|
@@ -178,29 +204,75 @@ whose every entry passes Contract's `isAuditFault` function.
|
|
|
178
204
|
The portable semantics every backend shares — pure, total functions the
|
|
179
205
|
driver never re-implements.
|
|
180
206
|
|
|
181
|
-
| Name | Kind | Signature
|
|
182
|
-
| ---------------------- | -------- |
|
|
183
|
-
| `compareValues` | function | `(left: unknown, right: unknown) => number`
|
|
184
|
-
| `matchesCondition` | function | `(row: Row, condition: Condition) => boolean`
|
|
185
|
-
| `matchesQuery` | function | `(row: Row, conditions: readonly Condition[]) => boolean`
|
|
186
|
-
| `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]`
|
|
187
|
-
| `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]`
|
|
188
|
-
| `validatePage` | function | `(input?: QueryInput) => void`
|
|
189
|
-
| `
|
|
190
|
-
| `
|
|
191
|
-
| `
|
|
192
|
-
| `
|
|
193
|
-
| `
|
|
194
|
-
| `
|
|
195
|
-
| `
|
|
196
|
-
| `
|
|
197
|
-
| `
|
|
198
|
-
| `
|
|
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. |
|
|
199
235
|
|
|
200
236
|
For `minimum` and `maximum`, `computeAggregate` compares each numeric value
|
|
201
237
|
with a scalar `Math.min` or `Math.max` call. The helper never passes a
|
|
202
238
|
row-sized argument list.
|
|
203
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
|
+
|
|
204
276
|
### Abort
|
|
205
277
|
|
|
206
278
|
| Name | Kind | Signature | Summary |
|
|
@@ -222,90 +294,118 @@ transform. Versioning drivers persist reconciliation metadata through the paired
|
|
|
222
294
|
|
|
223
295
|
### Conformance
|
|
224
296
|
|
|
225
|
-
| Name
|
|
226
|
-
|
|
|
227
|
-
| `conformDriver`
|
|
228
|
-
| `scanDriver`
|
|
229
|
-
| `
|
|
297
|
+
| Name | Kind | Signature | Summary |
|
|
298
|
+
| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
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. |
|
|
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. |
|
|
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. |
|
|
303
|
+
| `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
|
|
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. |
|
|
305
|
+
| `readPlannedAggregate` | function | `(storage: StorageInterface, table: string, input: QueryInput, aggregate: Aggregate, step?: () => Promise<void>) => Promise<number \| undefined>` | Computes an aggregate read through a storage's plan — the read procedure `Table.count` and `Table.aggregate` run and the conformance differential checks. |
|
|
306
|
+
| `scanPlans` | function | `(storage: StorageInterface, check: string) => AsyncIterable<ConformanceFinding>` | Compares a storage's planned answer to every conformance read against the core engine's answer over its `scan`, and checks each plan's invariants. |
|
|
230
307
|
|
|
231
308
|
### Helpers & guards
|
|
232
309
|
|
|
233
310
|
Pure helpers behind the query engine's pattern matching.
|
|
234
311
|
|
|
235
|
-
| Name | Kind | Signature
|
|
236
|
-
| ------------------------ | -------- |
|
|
237
|
-
| `cloneDriverMetadata` | function | `(value: unknown) => DriverMetadata`
|
|
238
|
-
| `matchesWildcardPattern` | function | `(value: string, pattern: string, any: string, single: string, fold: boolean) => boolean`
|
|
239
|
-
| `matchesWildcardSegment` | function | `(value: string, segment: string, at: number, single: string) => boolean`
|
|
240
|
-
| `matchesLikePattern` | function | `(value: string, pattern: string) => boolean`
|
|
241
|
-
| `matchesGlobPattern` | function | `(value: string, pattern: string) => boolean`
|
|
242
|
-
| `
|
|
243
|
-
| `
|
|
244
|
-
| `
|
|
245
|
-
| `
|
|
246
|
-
| `
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
249
|
-
| `
|
|
250
|
-
| `
|
|
251
|
-
| `
|
|
252
|
-
| `
|
|
312
|
+
| Name | Kind | Signature | Summary |
|
|
313
|
+
| ------------------------ | -------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
314
|
+
| `cloneDriverMetadata` | function | `(value: unknown) => DriverMetadata` | Clones unknown driver metadata into a distinct deeply frozen snapshot. |
|
|
315
|
+
| `matchesWildcardPattern` | function | `(value: string, pattern: string, any: string, single: string, fold: boolean) => boolean` | Matches a value against a wildcard pattern in linear time — the shared, ReDoS-safe engine behind `matchesLikePattern` and `matchesGlobPattern`. |
|
|
316
|
+
| `matchesWildcardSegment` | function | `(value: readonly string[], segment: readonly string[], at: number, single: string) => boolean` | Checks whether a fixed-length wildcard segment matches a value at an offset. |
|
|
317
|
+
| `matchesLikePattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a SQL `LIKE` pattern, folding ASCII case. |
|
|
318
|
+
| `matchesGlobPattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a `GLOB` pattern, preserving case. |
|
|
319
|
+
| `foldASCII` | function | `(text: string) => string` | Folds the ASCII letters of a text to lower case, leaving every other character unchanged. |
|
|
320
|
+
| `isDriverMetadata` | function | `(value: unknown) => value is DriverMetadata` | Checks whether a value is persisted driver metadata. |
|
|
321
|
+
| `isDriverSchema` | function | `(value: unknown) => value is readonly TableSchema[]` | Checks whether a value is a complete portable driver schema. |
|
|
322
|
+
| `isColumnSchema` | function | `(value: unknown) => value is ColumnSchema` | Checks whether a value is a portable column schema. |
|
|
323
|
+
| `isTableSchema` | function | `(value: unknown) => value is TableSchema` | Checks whether a value is a portable table schema. |
|
|
324
|
+
| `isMigrationStep` | function | `(value: unknown) => value is MigrationStep` | Checks whether a value is one ordered migration step. |
|
|
325
|
+
| `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
|
|
326
|
+
| `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
|
|
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`. |
|
|
330
|
+
| `isScalar` | function | `(value: unknown) => value is Scalar` | Checks whether a value is a scalar: not an object and not a function. |
|
|
331
|
+
| `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
|
|
332
|
+
| `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
|
|
333
|
+
| `captureFailure` | function | `(operation: () => Promise<unknown>) => Promise<unknown>` | Captures the exact rejection or synchronous throw from a driver conformance operation. |
|
|
253
334
|
|
|
254
335
|
### Constants
|
|
255
336
|
|
|
256
|
-
| Name | Kind | Signature
|
|
257
|
-
| -------------------------- | ----- |
|
|
258
|
-
| `DEFAULT_PRIMARY` | const | `"id"`
|
|
259
|
-
| `
|
|
260
|
-
| `
|
|
261
|
-
| `
|
|
262
|
-
| `
|
|
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. |
|
|
263
349
|
|
|
264
350
|
### Types
|
|
265
351
|
|
|
266
|
-
| Name | Kind | Signature | Summary
|
|
267
|
-
| -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
268
|
-
| `Key` | type | `string \| number` | Represents a primary key — the value identifying a row within its table.
|
|
269
|
-
| `KeyFunction` | type | `() => Key` | Represents a key-generating function.
|
|
270
|
-
| `Row` | type | `Record<string, unknown>` | Represents a table row — a plain record of column values keyed by column name.
|
|
271
|
-
| `
|
|
272
|
-
| `
|
|
273
|
-
| `
|
|
274
|
-
| `
|
|
275
|
-
| `
|
|
276
|
-
| `
|
|
277
|
-
| `
|
|
278
|
-
| `
|
|
279
|
-
| `
|
|
280
|
-
| `
|
|
281
|
-
| `
|
|
282
|
-
| `
|
|
283
|
-
| `
|
|
284
|
-
| `
|
|
285
|
-
| `
|
|
286
|
-
| `
|
|
287
|
-
| `
|
|
288
|
-
| `
|
|
289
|
-
| `
|
|
290
|
-
| `
|
|
291
|
-
| `
|
|
292
|
-
| `
|
|
293
|
-
| `
|
|
294
|
-
| `
|
|
295
|
-
| `
|
|
296
|
-
| `
|
|
297
|
-
| `
|
|
298
|
-
| `
|
|
299
|
-
| `
|
|
300
|
-
| `
|
|
301
|
-
| `
|
|
302
|
-
| `
|
|
303
|
-
| `
|
|
304
|
-
| `
|
|
305
|
-
| `
|
|
306
|
-
| `
|
|
307
|
-
| `
|
|
308
|
-
| `
|
|
352
|
+
| Name | Kind | Signature | Summary |
|
|
353
|
+
| -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
354
|
+
| `Key` | type | `string \| number` | Represents a primary key — the value identifying a row within its table. |
|
|
355
|
+
| `KeyFunction` | type | `() => Key` | Represents a key-generating function. |
|
|
356
|
+
| `Row` | type | `Record<string, unknown>` | Represents a table row — a plain record of column values keyed by column name. |
|
|
357
|
+
| `Scalar` | type | `null \| undefined \| boolean \| number \| bigint \| string \| symbol` | Represents a value that is not an object and not a function: `null` or a primitive. |
|
|
358
|
+
| `ConditionOperator` | type | `'equals' \| 'not' \| 'above' \| 'below' \| 'from' \| 'to' \| 'between' \| 'like' \| 'glob' \| 'starts' \| 'ends' \| 'any' \| 'none' \| 'absent' \| 'present'` | Represents a WHERE operator — the comparison a single `Condition` applies. |
|
|
359
|
+
| `ConditionConnector` | type | `'and' \| 'or'` | Names how a `Condition` joins to the running result of the conditions before it. |
|
|
360
|
+
| `Condition` | interface | `{ column, operator, values, connector }` | Represents one compiled WHERE condition. |
|
|
361
|
+
| `OrderDirection` | type | `'ascending' \| 'descending'` | Names a sort direction. |
|
|
362
|
+
| `Order` | interface | `{ column, direction }` | Represents one ordering term — a column (`FieldPath`, flat or nested) and its direction. |
|
|
363
|
+
| `QueryInput` | interface | `{ conditions?, order?, limit?, offset? }` | Represents a serializable read specification — everything a backend needs to compile one read, free of JS callbacks so any backend can honor it. |
|
|
364
|
+
| `Aggregate` | interface | `{ operation, column }` | Represents one aggregate a read reduces its rows to. |
|
|
365
|
+
| `ReadInput` | interface | `{ aggregate? }` | Represents a read as a driver plans it: a query, and the aggregate over its rows when the read computes one. |
|
|
366
|
+
| `ReadPlan` | interface | `{ native, residual }` | Represents the split of one read between the engine and the core. |
|
|
367
|
+
| `AggregateOperation` | type | `'count' \| 'sum' \| 'average' \| 'minimum' \| 'maximum'` | Names an aggregate computed over a numeric column. |
|
|
368
|
+
| `OperationOptions` | interface | `{ signal? }` | Options for an abortable operation. |
|
|
369
|
+
| `DatabaseStatus` | type | `'idle' \| 'open' \| 'closed'` | Names the lifecycle state of a `DatabaseInterface`. |
|
|
370
|
+
| `AdmissionInterface` | interface | `{ accepting, track() }` | Represents the admission boundary a scoped operation enters before it runs. |
|
|
371
|
+
| `DatabaseErrorCode` | type | `'CLOSED' \| 'NOT_FOUND' \| 'CONFLICT' \| 'VALIDATION' \| 'ABORTED' \| 'MIGRATION' \| 'CONFORMANCE' \| 'DRIVER'` | Names a machine-readable `DatabaseError` code. |
|
|
372
|
+
| `ConformanceFinding` | interface | `{ check, message, context }` | Represents one violated invariant from the driver-conformance battery. |
|
|
373
|
+
| `DatabaseEventMap` | type | `{ readonly open: readonly []; readonly close: readonly []; readonly transaction: readonly []; readonly commit: readonly []; readonly rollback: readonly [error: unknown]; readonly migrate: readonly [migration: Migration]; }` | Describes the push observation surface of a `DatabaseInterface` — the connection + transaction lifecycle a fire-and-forget observer (logging, metrics, tracing, cache invalidation) subscribes to. |
|
|
374
|
+
| `TableEventMap` | type | `{ readonly write: readonly [key: Key]; readonly remove: readonly [key: Key]; readonly clear: readonly []; }` | Describes the push observation surface of a `TableInterface` — the per-row mutation moments a fire-and-forget observer (cache invalidation, sync, an audit log) subscribes to, alongside the database-level `DatabaseEventMap`. |
|
|
375
|
+
| `ColumnMap` | type | `Readonly<Record<string, ContractShape>>` | Represents one table's columns — a map of column name to its value `ContractShape`. |
|
|
376
|
+
| `TableMap` | type | `Readonly<Record<string, ColumnMap>>` | Represents a database's table schema — a map of table name to its `ColumnMap`. |
|
|
377
|
+
| `RowOf` | type | `Infer<{ readonly category: 'object'; readonly properties: C; }>` | Represents the row type a table's `ColumnMap` describe — `Infer` of the `objectShape` the database wraps them in. |
|
|
378
|
+
| `PrimaryMap` | type | `Readonly<Record<string, string>>` | Holds per-table primary-key column overrides — `{ [table]: column }`. |
|
|
379
|
+
| `IndexMap` | type | `Readonly<Record<string, ReadonlyArray<readonly string[]>>>` | Holds per-table secondary indexes — `{ [table]: groups }`, each group one (possibly compound) index of column names. |
|
|
380
|
+
| `ColumnStorage` | type | `'text' \| 'integer' \| 'real' \| 'boolean' \| 'json' \| 'blob'` | Names a portable storage type for a column — the backend maps it to its native type (SQLite affinity, an IndexedDB value). Derived from a column's `ContractShape` by `shapeToColumnStorage`; `json` covers object/array/union/raw values a backend stores as JSON text and can `json_extract` for nested-field queries. |
|
|
381
|
+
| `ColumnSchema` | interface | `{ name, storage, optional, nullable }` | Represents one column of a `TableSchema` — its name, portable `ColumnStorage`, and whether it independently accepts absence (`optional`) and explicit `null` (`nullable`). |
|
|
382
|
+
| `TableSchema` | interface | `{ name, primary, columns, indexes }` | Represents a backend-agnostic description of one table — what `open` hands each driver so a native backend can create real tables and indexes. |
|
|
383
|
+
| `MigrationStep` | type | `{ readonly operation: 'table.add'; readonly table: TableSchema; } \| { readonly operation: 'table.remove'; readonly table: string; } \| { readonly operation: 'column.add'; readonly table: string; readonly column: ColumnSchema; } \| { readonly operation: 'column.remove'; readonly table: string; readonly column: string; } \| { readonly operation: 'index.add'; readonly table: string; readonly index: readonly string[]; } \| { readonly operation: 'index.remove'; readonly table: string; readonly index: readonly string[]; }` | Represents one step of a `Migration` plan — a single schema change applied to one table. |
|
|
384
|
+
| `Migration` | interface | `{ from, to, steps }` | Represents a schema migration plan — an ordered set of `MigrationStep`s moving a database from one schema version to another. |
|
|
385
|
+
| `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
|
|
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. |
|
|
387
|
+
| `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
|
|
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. |
|
|
395
|
+
| `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
|
|
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. |
|
|
397
|
+
| `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
|
|
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. |
|
|
402
|
+
| `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
|
|
403
|
+
| `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
|
|
404
|
+
| `DatabaseTableOptions` | interface | `{ on?, error? }` | Options for one table handle that `table` returns. |
|
|
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. |
|
|
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. |
|
|
407
|
+
| `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
|
|
408
|
+
| `CursorInterface` | interface | `{ value, index, done, next(), update(), remove(), close() }` | Walks a table's rows forward for bulk in-place mutation. |
|
|
309
409
|
|
|
310
410
|
### Operation state
|
|
311
411
|
|
|
@@ -366,56 +466,121 @@ method below runs inside that scope, and each carries the same contract its
|
|
|
366
466
|
`StorageInterface` and `DriverInterface` tables share one description per
|
|
367
467
|
method.
|
|
368
468
|
|
|
369
|
-
| Method | Returns | Summary
|
|
370
|
-
| ----------- | -------------------------------------- |
|
|
371
|
-
| `read` | `Promise<Row \| undefined>`
|
|
372
|
-
| `write` | `Promise<void>` | Writes one row at a key.
|
|
373
|
-
| `insert` | `Promise<void>` | Inserts one row
|
|
374
|
-
| `delete` | `Promise<boolean>`
|
|
375
|
-
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys.
|
|
376
|
-
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order.
|
|
377
|
-
| `clear` | `Promise<void>` | Empties a table.
|
|
378
|
-
| `
|
|
379
|
-
| `
|
|
380
|
-
| `
|
|
381
|
-
| `
|
|
382
|
-
| `
|
|
383
|
-
| `
|
|
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. |
|
|
384
485
|
|
|
385
486
|
#### `DriverInterface`
|
|
386
487
|
|
|
387
|
-
The complete backend extends `StorageInterface` with lifecycle
|
|
388
|
-
|
|
488
|
+
The complete backend extends `StorageInterface` with lifecycle and an optional native
|
|
489
|
+
transaction callback. The inherited
|
|
389
490
|
storage/query/migration/metadata methods carry the same contract they carry on
|
|
390
491
|
`StorageInterface`, addressed against the whole backend rather than one
|
|
391
492
|
transaction scope. `open` receives the derived `TableSchema` list: a native
|
|
392
493
|
backend builds real tables and indexes from it, a scan-only backend reads
|
|
393
|
-
`name` alone.
|
|
394
|
-
list
|
|
395
|
-
|
|
396
|
-
`
|
|
397
|
-
|
|
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)).
|
|
398
502
|
|
|
399
503
|
| Method | Returns | Summary |
|
|
400
504
|
| ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
401
505
|
| `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
|
|
402
506
|
| `close` | `Promise<void>` | Releases the backend. |
|
|
403
|
-
| `
|
|
404
|
-
| `
|
|
405
|
-
| `
|
|
406
|
-
| `
|
|
407
|
-
| `delete` | `Promise<boolean>` | Deletes one row by key. |
|
|
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. |
|
|
408
511
|
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
409
512
|
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
410
513
|
| `clear` | `Promise<void>` | Empties a table. |
|
|
411
|
-
| `
|
|
412
|
-
| `
|
|
413
|
-
| `
|
|
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. |
|
|
414
518
|
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
|
|
415
519
|
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
416
520
|
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
417
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. |
|
|
418
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`.
|
|
562
|
+
|
|
563
|
+
| Method | Returns | Summary |
|
|
564
|
+
| ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
565
|
+
| `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
|
|
566
|
+
| `close` | `Promise<void>` | Releases the backend. |
|
|
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. |
|
|
571
|
+
| `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
|
|
572
|
+
| `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
|
|
573
|
+
| `clear` | `Promise<void>` | Empties a table. |
|
|
574
|
+
| `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
|
|
575
|
+
| `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
|
|
576
|
+
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
|
|
577
|
+
| `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
|
|
578
|
+
| `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
|
|
579
|
+
| `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
|
|
580
|
+
| `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
|
|
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. |
|
|
583
|
+
|
|
419
584
|
#### `DatabaseInterface`
|
|
420
585
|
|
|
421
586
|
`DatabaseInterface` extends `DatabaseStorageInterface` and inherits its `table` method.
|
|
@@ -445,6 +610,11 @@ for work started after the transaction settles.
|
|
|
445
610
|
| ------- | ----------------------------- | ---------------------------------------------- |
|
|
446
611
|
| `table` | `TableInterface<RowOf<T[K]>>` | Returns the typed handle for a declared table. |
|
|
447
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
|
+
|
|
448
618
|
#### `AdmissionInterface`
|
|
449
619
|
|
|
450
620
|
The admission boundary the root database context and a transaction scope both
|
|
@@ -457,34 +627,33 @@ expose; its `accepting` data member stays in the Surface row above.
|
|
|
457
627
|
#### `TableInterface`
|
|
458
628
|
|
|
459
629
|
The keyed methods batch by overload (one in → one out; array in → array
|
|
460
|
-
out) — a single verb, never `getMany` / `setAll`. `records()
|
|
461
|
-
narrow every row through the table's contract guard,
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
count. `aggregate()` remains a stored-row operation; its `count` aggregate may
|
|
466
|
-
therefore include a row that `TableInterface.count()` excludes. `records`,
|
|
630
|
+
out) — a single verb, never `getMany` / `setAll`. `get()`, `records()`, and `scan()`
|
|
631
|
+
narrow every returned row through the table's contract guard, and a stored row that fails
|
|
632
|
+
it raises `DRIVER` with `table`, `key`, and the contract's `faults`. `count()` is
|
|
633
|
+
`aggregate('count')`, which reads the stored set `records()` reads while ignoring paging,
|
|
634
|
+
so the two agree. `records`,
|
|
467
635
|
`count`, `aggregate`, `scan`, `set`, `add`, `update`, and `remove` each take an
|
|
468
|
-
optional `OperationOptions`: its `signal` reaches every backend commit point
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
|
473
|
-
|
|
|
474
|
-
| `
|
|
475
|
-
| `
|
|
476
|
-
| `
|
|
477
|
-
| `
|
|
478
|
-
| `
|
|
479
|
-
| `
|
|
480
|
-
| `
|
|
481
|
-
| `
|
|
482
|
-
| `
|
|
483
|
-
| `
|
|
484
|
-
| `
|
|
485
|
-
| `
|
|
486
|
-
| `
|
|
487
|
-
| `
|
|
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`.
|
|
639
|
+
|
|
640
|
+
| Method | Returns | Summary |
|
|
641
|
+
| ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------- |
|
|
642
|
+
| `get` | `Promise<T \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
|
|
643
|
+
| `resolve` | `Promise<T>` (or array) | Reads one row by key, or one row per key for a list, throwing `NOT_FOUND` on a miss. |
|
|
644
|
+
| `has` | `Promise<boolean>` (or array) | Reports whether one key exists, or one result per key for a list. |
|
|
645
|
+
| `keys` | `Promise<readonly Key[]>` | Lists every primary key in order. |
|
|
646
|
+
| `records` | `Promise<readonly T[]>` | Reads the rows matching an optional `QueryInput`. |
|
|
647
|
+
| `count` | `Promise<number>` | Counts the stored rows matching `input`'s conditions. |
|
|
648
|
+
| `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over `column` across the stored rows matching `input`'s conditions. |
|
|
649
|
+
| `scan` | `AsyncIterable<T>` | Iterates the table's rows lazily with filtering. |
|
|
650
|
+
| `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
|
|
651
|
+
| `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
|
|
652
|
+
| `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
|
|
653
|
+
| `remove` | `Promise<boolean>` | Deletes one or more rows. |
|
|
654
|
+
| `clear` | `Promise<void>` | Empties the table. |
|
|
655
|
+
| `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
|
|
656
|
+
| `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
|
|
488
657
|
|
|
489
658
|
#### `QueryInterface`
|
|
490
659
|
|
|
@@ -529,45 +698,60 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
529
698
|
an entry barrel remain internal.
|
|
530
699
|
2. **A table is a contract.** Every write is admitted whole through the
|
|
531
700
|
table's compiled contract — `set` / `add` / `update` run the row through
|
|
532
|
-
Contract's `admitValue`, which
|
|
533
|
-
`
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
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
|
|
537
707
|
`rawShape` column admits any defined value, so the nested keys of a JSON
|
|
538
708
|
column never refuse. Reads are narrowed back to the table's row type
|
|
539
709
|
through the guard — never an `as` (see `AGENTS.md` § Non-negotiable
|
|
540
710
|
rules). The row type is the shape's `Infer`, so a `tables` map types every
|
|
541
711
|
table from one declaration. A refusal's context carries `table` and
|
|
542
712
|
`faults`, the `AuditFault` list `admitValue` returned, and its message
|
|
543
|
-
names the table and
|
|
544
|
-
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
|
|
545
715
|
JSON-encoded, length-capped rendering of the received value; the rejected
|
|
546
716
|
row and the parser cause never enter the message, context, serialized
|
|
547
717
|
error, or table events.
|
|
548
|
-
3. **
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
`indexes`) so a native
|
|
554
|
-
scan-only backend reads only `name`.
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
`
|
|
570
|
-
|
|
718
|
+
3. **Native first.** A driver answers every part of a read or a write with its engine's
|
|
719
|
+
native operation wherever the engine has one, and the core runs its own engine only over
|
|
720
|
+
the residual a driver's plan returns. The rule's home is the `DriverInterface` doc block,
|
|
721
|
+
which also states the plan invariants; this guide states it nowhere else. `open` hands the
|
|
722
|
+
driver a derived `TableSchema[]` (each table's `columns`, their portable `ColumnStorage`
|
|
723
|
+
through `shapeToColumnStorage`, the `primary` key, and declared `indexes`) so a native
|
|
724
|
+
backend can build real tables and indexes; a scan-only backend reads only `name`. A
|
|
725
|
+
driver declares its native coverage per read through `plan`, which returns a `ReadPlan`;
|
|
726
|
+
`Table` calls `records`, `stream`, and `aggregate` with `plan.native` only, and runs the
|
|
727
|
+
residual through `applyQuery`, `matchesQuery`, `sortRows`, and `computeAggregate`. A read
|
|
728
|
+
is wholly native when `residual` equals `{}`. `scanDriver` checks every plan's invariants,
|
|
729
|
+
the transaction capability's mirror of the native members, and a differential of each
|
|
730
|
+
planned driver against the core engine over `scan`. The following table rules where
|
|
731
|
+
each clause runs in this release:
|
|
732
|
+
|
|
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 |
|
|
743
|
+
|
|
744
|
+
The rule fixes these semantics on every driver: text order and text ranges are the
|
|
745
|
+
engine's binary order, so SQLite orders by code point where the core orders by UTF-16
|
|
746
|
+
code unit, and the two differ only between a supplementary-plane character and one in
|
|
747
|
+
U+E000 to U+FFFF; `like` folds ASCII letters only, and `_` and `?` match one code point;
|
|
748
|
+
ties resolve by primary key in the direction of the final order term; `sum` and
|
|
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
|
|
751
|
+
through the contract, so every stored row conforms; a returned stored row that fails the
|
|
752
|
+
contract raises `DRIVER`, and SQLite raises `DRIVER` for a stored value that does not
|
|
753
|
+
match its column's declaration. `MemoryDriver` lacks a native `transaction?`, so the
|
|
754
|
+
core's journal carries its transactions; `JSONDriver` does implement
|
|
571
755
|
`transaction?` — it clones the committed memory/schema/metadata into an
|
|
572
756
|
isolated candidate, passes only that candidate's capability to the callback,
|
|
573
757
|
and publishes it with one atomic file replacement only when the callback
|
|
@@ -580,7 +764,7 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
580
764
|
exactly once, and terminalizes the iterator; the transaction and driver
|
|
581
765
|
remain usable. Memory and IndexedDB need no equivalent root wrapper because
|
|
582
766
|
neither exposes a callback transaction. `Database.transaction` over a `JSONDriver`
|
|
583
|
-
therefore prefers this native path over the
|
|
767
|
+
therefore prefers this native path over the journal. Both reference drivers also
|
|
584
768
|
implement the paired `metadata?` / `stamp?` — `MemoryDriver` in-process only
|
|
585
769
|
(the owned `DriverMetadata` snapshot lives in instance memory), `JSONDriver` persisted:
|
|
586
770
|
the file is `{ metadata?: DriverMetadata, tables }`, with `metadata` present only
|
|
@@ -601,63 +785,18 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
601
785
|
`DatabaseError('DRIVER', 'Stored SQLite table is missing')` before any DDL in its
|
|
602
786
|
open transaction, and IndexedDB throws
|
|
603
787
|
`DatabaseError('DRIVER', 'Stored IndexedDB store is missing')` before its final
|
|
604
|
-
open. Extra
|
|
605
|
-
|
|
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
|
|
606
792
|
captures the bootstrap connection's exact stores and version in the same
|
|
607
|
-
lifetime, then pins the persisted final open to that version
|
|
608
|
-
versionchange makes the stale open reject
|
|
609
|
-
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,
|
|
610
796
|
or physically incomplete state throws `DRIVER` without publishing a handle or
|
|
611
797
|
attempting table/store repair; after external repair, the same driver instance
|
|
612
798
|
may retry `open`.
|
|
613
|
-
`SQLiteDriver` and
|
|
614
|
-
picture from opposite ends, each earning trust its own way (see
|
|
615
|
-
`.claude/rules/architecture.md` § System constraints).
|
|
616
|
-
`SQLiteDriver` is **prove-exactness-or-refine**: real `CREATE TABLE` /
|
|
617
|
-
`CREATE INDEX` DDL backs every table, but `records?` /
|
|
618
|
-
`aggregate?` / `stream?` compile a `QueryInput` straight to SQL
|
|
619
|
-
(`compileQuerySQL`, `compileAggregateSQL`) and run it natively only when
|
|
620
|
-
`matchesQueryExactly` (built from `matchesConditionExactly` / `matchesOrderExactly`) first
|
|
621
|
-
proves the SQL and the engine's semantics are identical for every
|
|
622
|
-
condition and order term — otherwise the driver falls back to a full
|
|
623
|
-
`scan` refined through the same core engine every scan-only driver uses
|
|
624
|
-
(`applyQuery` / `filterRows` / `computeAggregate` / `matchesQuery`).
|
|
625
|
-
Refine, not native SQL, is the path for: `like` / `glob` patterns (SQL
|
|
626
|
-
`LIKE`/`GLOB` semantics can diverge from the engine's `matchesWildcardPattern`),
|
|
627
|
-
every scalar condition over a column that is optional or nullable,
|
|
628
|
-
`absent` / `present` only when the column is optional and nullable, a `null`
|
|
629
|
-
or `undefined` scalar operand, an empty `any` / `none` operand list,
|
|
630
|
-
mismatched operand types, `json` / `blob` columns, and any nested
|
|
631
|
-
`FieldPath` — and a
|
|
632
|
-
range operator (`above` / `below` / `from` / `to` / `between`) or an
|
|
633
|
-
`ORDER BY` term over a `text` column: SQLite's default BINARY collation
|
|
634
|
-
orders `TEXT` by Unicode code point while the core engine's `compareValues`
|
|
635
|
-
orders JS strings by UTF-16 code unit, and the two diverge on
|
|
636
|
-
supplementary-plane characters (code points ≥ U+10000, for example many emoji) —
|
|
637
|
-
so text ranges and text ordering always refine through the engine, even
|
|
638
|
-
though text equality (`equals`/`not`/`any`/`none`) and `starts`/`ends` stay
|
|
639
|
-
native on a required non-null text column. `starts` / `ends` compile
|
|
640
|
-
case-sensitively (a `substr` comparison plus a
|
|
641
|
-
`typeof text === 'string'` guard; an empty operand falls back to a
|
|
642
|
-
`typeof` check) when they do qualify as exact. `IndexedDBDriver` is **narrow-then-refine**:
|
|
643
|
-
`records?` / `stream?` first ask `selectPlan` for a key-range pushdown over
|
|
644
|
-
the primary key or a single-column secondary index — a candidate superset,
|
|
645
|
-
never lossy — then hands that superset to the same core engine
|
|
646
|
-
(`applyQuery` / `matchesQuery`) every scan-only driver uses, which
|
|
647
|
-
refines it to the exact result; a plan that cannot prove itself range-exact
|
|
648
|
-
(a nested path, a non-orderable column type, an `or`-joined condition, a
|
|
649
|
-
non-comparison operator) falls back to a full scan. `below` / `to` push
|
|
650
|
-
down only onto the primary store, never a secondary index — a secondary
|
|
651
|
-
index has no entry for a row whose indexed column is absent or `null`,
|
|
652
|
-
while the engine's total order (`compareValues`) lets those rows match a
|
|
653
|
-
`below` / `to` bound; `equals` / `above` / `from` / `between` remain
|
|
654
|
-
index-eligible on either. `conditionToRange` returns `undefined` for a `between`
|
|
655
|
-
whose bounds are reversed (`compareValues(first, second) > 0`), so
|
|
656
|
-
`selectPlan` falls back to a full scan instead of handing a raw
|
|
657
|
-
backwards `IDBKeyRange` to the store (which would throw a `DataError`).
|
|
658
|
-
`IndexedDBDriver.snapshot()` captures every store in one read transaction,
|
|
659
|
-
so the capture is point-in-time consistent across stores even under
|
|
660
|
-
concurrent writers; `restore` was already atomic. `SQLiteDriver` and
|
|
799
|
+
`SQLiteDriver` and
|
|
661
800
|
`IndexedDBDriver` each implement `migrate?` natively and treat `MigrationInput` as one commit unit:
|
|
662
801
|
`SQLiteDriver` applies schema, rows, and optional metadata inside one native
|
|
663
802
|
SQLite transaction (`stepToSQL` projects each step's DDL), while a migration
|
|
@@ -673,20 +812,20 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
673
812
|
nothing is rewritten. Both implement the paired `metadata?` /
|
|
674
813
|
`stamp?` into a reserved store name a user table must avoid:
|
|
675
814
|
`SQLiteDriver` uses a single-row `_metadata` table (`METADATA_TABLE`), and
|
|
676
|
-
`IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`),
|
|
677
|
-
|
|
678
|
-
`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`;
|
|
679
818
|
the capability performs reads, writes, migration, and metadata work inside
|
|
680
819
|
that one native transaction, then becomes invalid. `IndexedDBDriver`
|
|
681
820
|
deliberately omits `transaction?`: an `IDBTransaction` can auto-commit when
|
|
682
821
|
control yields to a non-IDB `await`, so arbitrary callback awaits cannot
|
|
683
|
-
truthfully remain inside one native transaction. It also omits `aggregate
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
inherits the entire query surface unchanged.
|
|
822
|
+
truthfully remain inside one native transaction. It also omits `aggregate?`, so every
|
|
823
|
+
aggregate it plans stays residual.
|
|
824
|
+
|
|
687
825
|
4. **Total query helpers; the equality family is structural, not ranked.**
|
|
688
826
|
`compareValues`, `matchesCondition`, and `matchesQuery` never throw — a
|
|
689
|
-
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
|
|
690
829
|
never returns `NaN`), mirroring the contracts guards' totality (see
|
|
691
830
|
`.claude/rules/patterns.md` § Validation and contracts). The range
|
|
692
831
|
operators (`above` / `below` / `from` / `to` /
|
|
@@ -716,9 +855,10 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
716
855
|
tables, queries, cursors, and streams also throw `CONFLICT` after settlement.
|
|
717
856
|
When the driver implements `transaction?(scope)`, the driver owns
|
|
718
857
|
acquisition, commit on fulfillment, rollback on rejection, release, and
|
|
719
|
-
invalidation. Otherwise the
|
|
720
|
-
|
|
721
|
-
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`
|
|
722
862
|
lifecycle; `rollback(error)` is emitted only when rollback completed and the
|
|
723
863
|
original scope/drain error remains the propagated rejection, never when
|
|
724
864
|
cleanup itself replaced that error.
|
|
@@ -740,7 +880,14 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
740
880
|
restores, and the original transaction error still propagates (proven by
|
|
741
881
|
the emit-safety tests). Reads / queries / counts are not emitted (a
|
|
742
882
|
reader does not mutate, and those paths are too hot). The observation
|
|
743
|
-
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.
|
|
744
891
|
7. **Views share a driver.** A database is a typed view over a set of tables
|
|
745
892
|
on one driver. `import(tables)` returns a new view of only those tables
|
|
746
893
|
over the **same** driver (sharing storage and transactions); `export()`
|
|
@@ -757,13 +904,13 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
757
904
|
`migrate?` / `metadata?` / `stamp?` may be omitted). `MemoryDriver` and
|
|
758
905
|
`JSONDriver` both omit `records?` / `aggregate?`, and both
|
|
759
906
|
implement `stream?` / `migrate?` / `metadata?` / `stamp?`; `MemoryDriver` still
|
|
760
|
-
omits `transaction?` (
|
|
907
|
+
omits `transaction?` (the core's journal carries its scopes) while `JSONDriver`
|
|
761
908
|
implements `transaction?` too (isolated candidate state plus one atomic
|
|
762
909
|
publish on callback fulfillment). `SQLiteDriver` implements every optional hook — `records?` /
|
|
763
910
|
`aggregate?` / `transaction?` / `stream?` / `migrate?` / `metadata?`
|
|
764
911
|
/ `stamp?` — the fully-native backend. `IndexedDBDriver` implements
|
|
765
|
-
`records?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
|
|
766
|
-
omits `transaction?`
|
|
912
|
+
`records?` / `aggregate?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
|
|
913
|
+
omits `transaction?` by IndexedDB's nature, not by
|
|
767
914
|
choice (see `.claude/rules/documentation.md` § Parity). A renamed / added /
|
|
768
915
|
removed method breaks the gate
|
|
769
916
|
until the table is reconciled.
|
|
@@ -789,9 +936,8 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
789
936
|
the temp file before rejection, and reads wait behind that unit. Once an
|
|
790
937
|
commit point that cannot be aborted (`SQLite` call entry, IndexedDB transaction
|
|
791
938
|
completion, JSON `rename` dispatch) has won, the operation awaits and reports its real
|
|
792
|
-
result; a late signal cannot convert success to `ABORTED`.
|
|
793
|
-
|
|
794
|
-
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.
|
|
795
941
|
10. **Key generation is host-neutral and overridable.** When an optional
|
|
796
942
|
primary column is omitted, a table uses global `crypto.randomUUID()`.
|
|
797
943
|
`DatabaseOptions.generator` (a `KeyFunction`) authoritatively replaces
|
|
@@ -862,16 +1008,17 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
862
1008
|
README all call it the same way. It opens the fixed `users` and `posts`
|
|
863
1009
|
schema per phase (calling `factory()` fresh each time so failures stay
|
|
864
1010
|
isolated) and verifies the required surface's invariants (copy-in/copy-out
|
|
865
|
-
isolation, upsert-overwrite, key-ordered `keys`/`scan`,
|
|
866
|
-
|
|
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
|
|
867
1015
|
presence-gates the optional `migrate?` / `stream?` / `transaction?`
|
|
868
1016
|
hooks when the driver implements them. The battery's `write-read` phase
|
|
869
1017
|
is deepened with nested-field checks (a written row's nested object/array
|
|
870
1018
|
fields must copy-in/copy-out isolated, not only its top-level fields),
|
|
871
|
-
and
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
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
|
|
875
1022
|
`structuredClone` at every one of those boundaries). The first violated
|
|
876
1023
|
invariant throws a `CONFORMANCE` `DatabaseError` naming the failed check.
|
|
877
1024
|
13. **Backend faults surface as `DatabaseError`, never raw.** No native
|
|
@@ -881,16 +1028,14 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
881
1028
|
(`#guard` internally on the SQLite side; `mapIndexedDBError` /
|
|
882
1029
|
`mapMigrationError` on the IndexedDB side), preserving the original
|
|
883
1030
|
error as `context.cause`. `SQLiteDriver`: a constraint violation maps to
|
|
884
|
-
`CONFLICT`, a closed-connection fault to `CLOSED`, a busy
|
|
885
|
-
to `DRIVER` with a `retryable` context flag, anything else to
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
Public `close()` crosses that same boundary
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
`context.code === 'BUSY'`; both retain the actual `SQLiteError` only at
|
|
893
|
-
`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`.
|
|
894
1039
|
`IndexedDBDriver`: a constraint violation maps to `CONFLICT`; a
|
|
895
1040
|
closed/not-open/invalid-state fault to `CLOSED`; a quota fault to
|
|
896
1041
|
`DRIVER` with `code: 'QUOTA'`; `migrate`'s versionchange path remaps an
|
|
@@ -905,11 +1050,43 @@ These invariants hold across the core database source tree ↔ this guide:
|
|
|
905
1050
|
as corrupted metadata. Because both drivers derive their index names from
|
|
906
1051
|
a length-prefixed scheme (`deriveSQLiteIndexName` for SQLite,
|
|
907
1052
|
`deriveIndexedDBIndexName` for IndexedDB) to stay collision-free across
|
|
908
|
-
compound indexes
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
they are never queried and never collide, but a
|
|
912
|
-
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.
|
|
913
1090
|
|
|
914
1091
|
What ships is the **core in-between** (schema-aware: `open` receives a
|
|
915
1092
|
derived `TableSchema[]`, with `shapeToColumnStorage` mapping each column's shape), its
|
|
@@ -917,7 +1094,7 @@ reference `MemoryDriver`, and the persistent `JSONDriver`, `SQLiteDriver`, and
|
|
|
917
1094
|
`IndexedDBDriver` backends. `JSONDriver` in `src/server` is a decorator over
|
|
918
1095
|
`MemoryDriver` that loads/flushes a single JSON file — every primitive
|
|
919
1096
|
delegates to the inner memory driver, so querying, key-order `scan` / `keys`,
|
|
920
|
-
and
|
|
1097
|
+
and the all-or-nothing batches are inherited unchanged; `JSONDriver.migrate`
|
|
921
1098
|
additionally persists the migrated state, and every flush is atomic — written
|
|
922
1099
|
to a sibling temp file and `rename`d onto the target path, so a crash mid-flush
|
|
923
1100
|
can never truncate or corrupt the previous good file. Outside a `transaction`,
|
|
@@ -932,7 +1109,7 @@ active, and a captured capability used after settlement throw `CONFLICT`.
|
|
|
932
1109
|
fully-native, **trusted-mode** backend on the published `@orkestrel/sqlite`
|
|
933
1110
|
wrapper — real typed `CREATE TABLE` / `CREATE INDEX` DDL, native
|
|
934
1111
|
`records?` / `aggregate?` / `stream?` compiled straight to SQL,
|
|
935
|
-
real `BEGIN` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
|
|
1112
|
+
real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
|
|
936
1113
|
(`stepToSQL`; a root input uses one native transaction, while an input inside
|
|
937
1114
|
an existing callback transaction uses the guarded fixed internal savepoint
|
|
938
1115
|
literal for caught-inner-failure containment while the outer transaction stays
|
|
@@ -941,15 +1118,13 @@ and a reserved
|
|
|
941
1118
|
`_metadata` table (`METADATA_TABLE`) for `metadata?` / `stamp?` versioning — every
|
|
942
1119
|
optional `DriverInterface` hook, none skipped. `IndexedDBDriver` in
|
|
943
1120
|
`src/browser`, on the published `@orkestrel/indexeddb` wrapper, is the
|
|
944
|
-
|
|
945
|
-
`
|
|
946
|
-
|
|
947
|
-
engine then refines to the exact result; `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
|
|
948
1124
|
and its metadata in one versionchange transaction, and `metadata?` / `stamp?`
|
|
949
1125
|
persist into a reserved
|
|
950
1126
|
`__metadata__` store (`METADATA_STORE`) — it omits `transaction?` because arbitrary
|
|
951
|
-
callback awaits outlive an auto-committing `IDBTransaction
|
|
952
|
-
`aggregate?` (no native SUM/AVG/MIN/MAX) by IndexedDB's own nature. The core
|
|
1127
|
+
callback awaits outlive an auto-committing `IDBTransaction`. The core
|
|
953
1128
|
`Database` / `Table` are also **observable** — each owns a typed `emitter`
|
|
954
1129
|
(`DatabaseEventMap` / `TableEventMap`) carrying the transaction +
|
|
955
1130
|
per-row lifecycle (see [Observing](#observing)); a driver stays a storage
|
|
@@ -992,9 +1167,8 @@ posts.primary // 'slug' — the declared override
|
|
|
992
1167
|
|
|
993
1168
|
Each `indexes` entry is one (possibly compound) index of column names; they
|
|
994
1169
|
flow into each table's derived `TableSchema`. Neither driver here declares a
|
|
995
|
-
native index, so both ignore them; SQLite and IndexedDB
|
|
996
|
-
|
|
997
|
-
required.
|
|
1170
|
+
native index, so both ignore them; SQLite and IndexedDB build a native index from each
|
|
1171
|
+
supported declaration, and IndexedDB drops at open an index the declaration no longer names.
|
|
998
1172
|
|
|
999
1173
|
### Swapping the driver
|
|
1000
1174
|
|
|
@@ -1089,6 +1263,47 @@ await users.count() // every row, unfiltered
|
|
|
1089
1263
|
await users.aggregate('average', 'age') // number | undefined
|
|
1090
1264
|
```
|
|
1091
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
|
+
|
|
1092
1307
|
### Streaming with early exit
|
|
1093
1308
|
|
|
1094
1309
|
`scan` (on a table) and `stream` (on a query) are lazy — rows are yielded one
|
|
@@ -1179,8 +1394,8 @@ write. Memory and SQLite check immediately before their synchronous mutation;
|
|
|
1179
1394
|
IndexedDB aborts its explicit readwrite transaction while active; JSON aborts
|
|
1180
1395
|
staging, cleans its temp file, and restores the preimage before rejecting. If
|
|
1181
1396
|
the native commit has already been dispatched, the method ignores a late abort
|
|
1182
|
-
and awaits the real success or failure. A batch
|
|
1183
|
-
|
|
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.
|
|
1184
1399
|
|
|
1185
1400
|
### Batch operations
|
|
1186
1401
|
|
|
@@ -1214,33 +1429,46 @@ await users.get(['u1', 'u2']) // → readonly (Row | undefined)[]
|
|
|
1214
1429
|
await users.resolve(['u1', 'u2']) // → readonly Row[] (NOT_FOUND on any miss)
|
|
1215
1430
|
await users.has(['u1', 'u2']) // → readonly boolean[]
|
|
1216
1431
|
await users.update(['u1', 'u2'], { role: 'member' }) // same changes to each → readonly boolean[]
|
|
1217
|
-
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
|
|
1218
1433
|
```
|
|
1219
1434
|
|
|
1220
|
-
A batch
|
|
1221
|
-
|
|
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`.
|
|
1222
1442
|
|
|
1223
1443
|
### Admission through the contract
|
|
1224
1444
|
|
|
1225
|
-
|
|
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:
|
|
1226
1446
|
|
|
1227
1447
|
```ts
|
|
1228
1448
|
import { createDatabase, createMemoryDriver, isDatabaseError } from '@orkestrel/database'
|
|
1229
|
-
import {
|
|
1449
|
+
import type { DatabaseInterface } from '@orkestrel/database'
|
|
1450
|
+
import { integerShape, repairValue, stringShape } from '@orkestrel/contract'
|
|
1230
1451
|
|
|
1231
|
-
|
|
1452
|
+
// A DatabaseInterface hands out untyped rows, as a boundary that holds loose data needs.
|
|
1453
|
+
const db: DatabaseInterface = createDatabase({
|
|
1232
1454
|
driver: createMemoryDriver(),
|
|
1233
1455
|
tables: {
|
|
1234
1456
|
users: { id: stringShape(), name: stringShape(), age: integerShape(), role: stringShape() },
|
|
1235
1457
|
},
|
|
1236
|
-
})
|
|
1458
|
+
})
|
|
1459
|
+
const users = db.table('users')
|
|
1237
1460
|
|
|
1238
|
-
// A numeric string is a lossless repair, so
|
|
1239
|
-
const
|
|
1240
|
-
|
|
1241
|
-
|
|
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)
|
|
1242
1466
|
;(await users.get('u2'))?.age // 41 (a number)
|
|
1243
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
|
+
|
|
1244
1472
|
// An undeclared column refuses with DatabaseError('VALIDATION') and the contract's faults.
|
|
1245
1473
|
const imported = { id: 'u3', name: 'Cy', age: 29, role: 'member', nickname: 'Cy' }
|
|
1246
1474
|
const refused = await users.set(imported).catch((error: unknown) => error)
|
|
@@ -1377,9 +1605,10 @@ await users
|
|
|
1377
1605
|
.collect()
|
|
1378
1606
|
```
|
|
1379
1607
|
|
|
1380
|
-
The condition operators map to familiar SQL operators. The engine
|
|
1381
|
-
|
|
1382
|
-
|
|
1608
|
+
The condition operators map to familiar SQL operators. The core engine evaluates each one
|
|
1609
|
+
over a residual; SQLite answers each natively on a flat declared column, and IndexedDB
|
|
1610
|
+
answers the conditions of one access path with a key range or a key list, under these same
|
|
1611
|
+
semantics:
|
|
1383
1612
|
|
|
1384
1613
|
| Operator | SQL |
|
|
1385
1614
|
| --------- | ------------- |
|
|
@@ -1558,6 +1787,35 @@ error. `rollback(error)` reports only a completed rollback whose original
|
|
|
1558
1787
|
scope/drain error is still being propagated — a cleanup failure is never
|
|
1559
1788
|
reported as a successful rollback.
|
|
1560
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
|
+
|
|
1561
1819
|
Root promise operations enter the shared admission ledger synchronously, before
|
|
1562
1820
|
their first `await`. `transaction()` closes root admission before it drains that
|
|
1563
1821
|
ledger, so work accepted immediately before the transaction is included and work
|
|
@@ -1586,7 +1844,7 @@ await boundary.track(async () => 42) // 42
|
|
|
1586
1844
|
### Native transactions
|
|
1587
1845
|
|
|
1588
1846
|
`transaction` uses a driver's optional native `transaction?(scope)` hook
|
|
1589
|
-
instead of the
|
|
1847
|
+
instead of the core's journal. The driver passes a `StorageInterface`
|
|
1590
1848
|
capability to the callback, commits when it fulfills, rolls back when it
|
|
1591
1849
|
rejects, and invalidates the capability after settlement. The database-level
|
|
1592
1850
|
`transaction` / `commit` / `rollback` events fire the same either way:
|
|
@@ -1830,10 +2088,10 @@ schemaToStore(table)
|
|
|
1830
2088
|
|
|
1831
2089
|
The helper delegates exact JSON ownership to Contract 0.0.9's
|
|
1832
2090
|
`cloneJSONRecord`, then validates the owned output as `DriverMetadata`. A malformed
|
|
1833
|
-
shape, cycle, function, accessor, or
|
|
2091
|
+
shape, cycle, function, accessor, or throwing/revoked proxy throws
|
|
1834
2092
|
`DatabaseError('VALIDATION')` with `context.path === 'metadata'`; clone/traversal
|
|
1835
2093
|
failures are retained only as `context.cause`, so no raw Contract or caller
|
|
1836
|
-
error crosses the Database surface.
|
|
2094
|
+
error crosses the Database surface. Untrusted values are never stringified or
|
|
1837
2095
|
embedded in the diagnostic.
|
|
1838
2096
|
|
|
1839
2097
|
`JSONDriver` applies that ownership rule at every file-backed seam: valid parsed
|
|
@@ -1848,7 +2106,7 @@ structured-clone behavior and are not forced through the JSON metadata cloner.
|
|
|
1848
2106
|
|
|
1849
2107
|
`SQLiteDriver` applies the same boundary at persisted-row ingress, every
|
|
1850
2108
|
root/scoped `stamp` and `migrate` ingress, and every `metadata()` copy-out.
|
|
1851
|
-
Root lifecycle and scoped token gates run before
|
|
2109
|
+
Root lifecycle and scoped token gates run before untrusted metadata traversal;
|
|
1852
2110
|
valid migration metadata is cloned before its first DDL statement. Malformed
|
|
1853
2111
|
stored metadata fails closed with `DRIVER`, while valid copy-outs are distinct
|
|
1854
2112
|
and deeply frozen. General SQLite rows continue through
|
|
@@ -1939,8 +2197,9 @@ const db = createDatabase({
|
|
|
1939
2197
|
on: { commit: () => console.log('transaction committed') },
|
|
1940
2198
|
})
|
|
1941
2199
|
|
|
1942
|
-
const users = db.table('users'
|
|
1943
|
-
|
|
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
|
|
1944
2203
|
users.emitter.on('remove', (key) => console.log('invalidate users', key))
|
|
1945
2204
|
db.emitter.on('rollback', (error) => console.warn('transaction rolled back', error))
|
|
1946
2205
|
```
|
|
@@ -1955,7 +2214,7 @@ The event vocabulary:
|
|
|
1955
2214
|
`open` fires once when the handle's driver connects (an explicit `open()`, or
|
|
1956
2215
|
the lazy first-use connect); `close`
|
|
1957
2216
|
when the driver is released; `transaction` when a scope begins after its
|
|
1958
|
-
native boundary or
|
|
2217
|
+
native boundary is acquired or its journal is created; `commit` only after a scope
|
|
1959
2218
|
succeeds; `rollback` only after a throwing scope's tables are all restored;
|
|
1960
2219
|
`migrate` after a migration commits. A `Table` fires `write` after any
|
|
1961
2220
|
row put (set / add / update — re-read by key if you need the new value),
|
|
@@ -1963,7 +2222,12 @@ row put (set / add / update — re-read by key if you need the new value),
|
|
|
1963
2222
|
and `clear` after the table is emptied. Reads / queries / counts are **not**
|
|
1964
2223
|
emitted — a reader does not mutate, and those paths are too hot. Each
|
|
1965
2224
|
`db.table(name)` returns a fresh handle with its own emitter, so subscribe
|
|
1966
|
-
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.
|
|
1967
2231
|
|
|
1968
2232
|
**Listener isolation.** A listener throw never escapes
|
|
1969
2233
|
into the engine: the emitter isolates it and routes it to
|
|
@@ -1980,8 +2244,8 @@ propagates, the tables still roll back), and a throwing `write` observer
|
|
|
1980
2244
|
leaves the written row intact — proven by the per-entity emit-safety tests.
|
|
1981
2245
|
(A `Table` reached through the `Database` receives the same `error` handler
|
|
1982
2246
|
the `DatabaseOptions.error` option supplies, so a `Table` listener throw
|
|
1983
|
-
routes there
|
|
1984
|
-
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.)
|
|
1985
2249
|
|
|
1986
2250
|
### Importing and exporting schemas
|
|
1987
2251
|
|
|
@@ -2097,17 +2361,18 @@ await driver.write('users', 'u1', { id: 'u1', name: 'Ada Lovelace' }) // upsert
|
|
|
2097
2361
|
await driver.read('users', 'u1') // { id: 'u1', name: 'Ada' } | undefined
|
|
2098
2362
|
for await (const row of driver.scan('users')) row // every row, key order
|
|
2099
2363
|
await driver.keys('users') // readonly Key[]
|
|
2100
|
-
|
|
2101
|
-
await driver.
|
|
2102
|
-
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
|
|
2103
2368
|
await driver.clear('users')
|
|
2104
2369
|
await driver.close()
|
|
2105
2370
|
```
|
|
2106
2371
|
|
|
2107
2372
|
### Query engine helpers
|
|
2108
2373
|
|
|
2109
|
-
The pure functions
|
|
2110
|
-
|
|
2374
|
+
The pure functions of the core's engine, which runs the residual of a driver's plan
|
|
2375
|
+
behind `TableInterface` and `QueryInterface`:
|
|
2111
2376
|
|
|
2112
2377
|
```ts
|
|
2113
2378
|
import type { Condition } from '@orkestrel/database'
|
|
@@ -2131,7 +2396,7 @@ import {
|
|
|
2131
2396
|
|
|
2132
2397
|
compareValues(1, 2) // -1 — a total order over mixed types
|
|
2133
2398
|
matchesWildcardPattern('hello', 'h%o', '%', '_', true) // true — the shared LIKE/GLOB engine
|
|
2134
|
-
matchesLikePattern('
|
|
2399
|
+
matchesLikePattern('Hello', 'h%o') // true — ASCII letters fold
|
|
2135
2400
|
matchesGlobPattern('hello', 'h*o') // true — case-sensitive
|
|
2136
2401
|
|
|
2137
2402
|
const condition: Condition = {
|
|
@@ -2154,6 +2419,36 @@ shapeToColumnStorage(integerShape()) // 'integer' — the type `open` hands a dr
|
|
|
2154
2419
|
equalsValue({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }) // true — structural, not reference, equality
|
|
2155
2420
|
```
|
|
2156
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
|
+
|
|
2157
2452
|
### Persistence with the JSON driver
|
|
2158
2453
|
|
|
2159
2454
|
Opens a database over the JSON driver and writes one row, persisted to the backing file:
|
|
@@ -2206,19 +2501,19 @@ restored before that error leaves the exclusive queue, so the next operation
|
|
|
2206
2501
|
can proceed after the temporary obstruction is removed. A successful staging
|
|
2207
2502
|
write requests native `flush: true` before the same-directory atomic rename.
|
|
2208
2503
|
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
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.
|
|
2215
2510
|
|
|
2216
2511
|
### Compiling input to SQL
|
|
2217
2512
|
|
|
2218
2513
|
The server's pure `compilers.ts` turns a core `QueryInput` (the same one
|
|
2219
2514
|
`applyQuery` folds) into the `WHERE` / `ORDER BY` / `LIMIT` tail of a
|
|
2220
|
-
`SELECT`, with `?`-bound parameters in clause order — the
|
|
2221
|
-
driver's `records` hook runs
|
|
2515
|
+
`SELECT`, with `?`-bound parameters in clause order — the native side of a plan that a
|
|
2516
|
+
SQLite driver's `records` hook runs:
|
|
2222
2517
|
|
|
2223
2518
|
```ts
|
|
2224
2519
|
import {
|
|
@@ -2227,8 +2522,8 @@ import {
|
|
|
2227
2522
|
compileFieldSQL,
|
|
2228
2523
|
compileQuerySQL,
|
|
2229
2524
|
deriveSQLiteIndexName,
|
|
2230
|
-
matchesAggregateExactly,
|
|
2231
2525
|
matchesSQLiteAffinity,
|
|
2526
|
+
planSQLiteQuery,
|
|
2232
2527
|
quoteIdentifier,
|
|
2233
2528
|
schemaToIndexes,
|
|
2234
2529
|
schemaToTable,
|
|
@@ -2249,14 +2544,14 @@ const schema: TableSchema = {
|
|
|
2249
2544
|
compileQuerySQL(
|
|
2250
2545
|
{ conditions: [{ column: 'age', operator: 'from', values: [18], connector: 'and' }] },
|
|
2251
2546
|
schema,
|
|
2252
|
-
) // { sql: 'WHERE "age" >= ? ORDER BY "id"', parameters: [18] }
|
|
2547
|
+
) // { sql: 'WHERE "age" >= ? ORDER BY "id" ASC', parameters: [18] }
|
|
2253
2548
|
|
|
2254
2549
|
quoteIdentifier('order') // '"order"'
|
|
2255
2550
|
deriveSQLiteIndexName('users', ['age']) // 'idx_5_users_3_age'
|
|
2256
2551
|
compileColumnSQL('integer') // 'INTEGER'
|
|
2257
|
-
compileFieldSQL(['profile', 'score']) //
|
|
2552
|
+
compileFieldSQL(['profile', 'score']) // `json_extract(CASE WHEN typeof("profile") = 'text' THEN "profile" END, '$."score"')`
|
|
2258
2553
|
compileAggregateSQL('average', 'age') // 'AVG("age")'
|
|
2259
|
-
|
|
2554
|
+
planSQLiteQuery({ aggregate: { operation: 'minimum', column: 'age' } }, schema).residual // {}
|
|
2260
2555
|
matchesSQLiteAffinity('INTEGER', 'integer') // true
|
|
2261
2556
|
schemaToTable(schema) // CREATE TABLE IF NOT EXISTS …
|
|
2262
2557
|
schemaToIndexes(schema) // []
|
|
@@ -2266,31 +2561,36 @@ stepToSQL({ operation: 'index.add', table: 'users', index: ['age'] })
|
|
|
2266
2561
|
// db.prepare(`SELECT * FROM "users" ${sql}`).all(...parameters)
|
|
2267
2562
|
```
|
|
2268
2563
|
|
|
2269
|
-
###
|
|
2270
|
-
|
|
2271
|
-
A
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
core
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2564
|
+
### Plans and residual work
|
|
2565
|
+
|
|
2566
|
+
A driver's `plan` splits each read into the part its engine answers and the residual the
|
|
2567
|
+
core runs, under the native-first rule the `DriverInterface` doc block states. A read is
|
|
2568
|
+
wholly native when `residual` equals `{}`. `planSQLiteQuery` is the SQLite driver's plan,
|
|
2569
|
+
and `compileQuerySQL` compiles its native side; `planIndexedDBQuery` is the IndexedDB
|
|
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
|
|
2572
|
+
`MemoryDriver` and `JSONDriver`, answers the whole read as residual over `scan`. `Table` runs
|
|
2573
|
+
every read through `readPlannedRows`, `readPlannedAggregate`, and `streamPlannedRows`, the one
|
|
2574
|
+
read procedure `scanDriver`'s differential checks.
|
|
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.
|
|
2287
2587
|
|
|
2288
2588
|
```ts
|
|
2289
2589
|
import type { Condition, TableSchema } from '@orkestrel/database'
|
|
2290
2590
|
import {
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2591
|
+
compileQuerySQL,
|
|
2592
|
+
matchesSQLiteCondition,
|
|
2593
|
+
planSQLiteQuery,
|
|
2294
2594
|
} from '@orkestrel/database/server'
|
|
2295
2595
|
|
|
2296
2596
|
const schema: TableSchema = {
|
|
@@ -2303,28 +2603,29 @@ const schema: TableSchema = {
|
|
|
2303
2603
|
indexes: [],
|
|
2304
2604
|
}
|
|
2305
2605
|
|
|
2306
|
-
const
|
|
2606
|
+
const native: Condition = {
|
|
2307
2607
|
column: 'age',
|
|
2308
2608
|
operator: 'above',
|
|
2309
2609
|
values: [18],
|
|
2310
2610
|
connector: 'and',
|
|
2311
2611
|
}
|
|
2312
|
-
|
|
2612
|
+
matchesSQLiteCondition(native, schema) // true — a comparison over a typed column
|
|
2313
2613
|
|
|
2314
|
-
const
|
|
2614
|
+
const residual: Condition = {
|
|
2315
2615
|
column: 'age',
|
|
2316
2616
|
operator: 'above',
|
|
2317
2617
|
values: [null],
|
|
2318
2618
|
connector: 'and',
|
|
2319
2619
|
}
|
|
2320
|
-
|
|
2620
|
+
matchesSQLiteCondition(residual, schema) // false — a null range operand stays residual
|
|
2321
2621
|
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
matchesQueryExactly(
|
|
2325
|
-
{ conditions: [exact], order: [{ column: 'age', direction: 'ascending' }] },
|
|
2622
|
+
const plan = planSQLiteQuery(
|
|
2623
|
+
{ conditions: [native], order: [{ column: 'age', direction: 'ascending' }], limit: 10 },
|
|
2326
2624
|
schema,
|
|
2327
|
-
) //
|
|
2625
|
+
) // { native: { conditions: [ … ], order: [ … ], limit: 10 }, residual: {} }
|
|
2626
|
+
|
|
2627
|
+
compileQuerySQL(plan.native, schema)
|
|
2628
|
+
// { sql: 'WHERE "age" > ? ORDER BY "age" ASC, "id" ASC LIMIT ?', parameters: [18, 10] }
|
|
2328
2629
|
```
|
|
2329
2630
|
|
|
2330
2631
|
### Persistence with the SQLite driver
|
|
@@ -2358,15 +2659,18 @@ await db
|
|
|
2358
2659
|
// Real transactions and atomic migration ship with it:
|
|
2359
2660
|
await db.transaction(async (transaction) => {
|
|
2360
2661
|
await transaction.table('users').update('u1', { age: 37 })
|
|
2361
|
-
}) // real BEGIN/COMMIT/ROLLBACK, not the
|
|
2662
|
+
}) // real BEGIN IMMEDIATE/COMMIT/ROLLBACK, not the core's journal
|
|
2362
2663
|
|
|
2363
|
-
// createSQLiteDriver accepts a SQLiteDriverOptions bag:
|
|
2364
|
-
createSQLiteDriver({
|
|
2365
|
-
path: 'data/
|
|
2366
|
-
timeout: 5000,
|
|
2664
|
+
// createSQLiteDriver accepts a SQLiteDriverOptions bag and returns a SQLiteDriverInterface:
|
|
2665
|
+
const driver = createSQLiteDriver({
|
|
2666
|
+
path: 'data/reports.sqlite',
|
|
2367
2667
|
references: true,
|
|
2368
|
-
pragmas: {
|
|
2668
|
+
pragmas: { synchronous: 'FULL' }, // applied after the WAL default, in order
|
|
2369
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
|
|
2370
2674
|
```
|
|
2371
2675
|
|
|
2372
2676
|
`SQLiteDriver` is the fully-native backend — it implements every optional
|
|
@@ -2385,17 +2689,72 @@ metadata. The same call inside a callback transaction uses a SQLite savepoint:
|
|
|
2385
2689
|
the wrapper deliberately provides raw `execute`, not a savepoint manager, so the
|
|
2386
2690
|
driver owns one guarded fixed internal SQL literal. If caller code catches its
|
|
2387
2691
|
failure, the failed inner migration is rolled back to that savepoint while the
|
|
2388
|
-
surrounding transaction remains active and may continue safely.
|
|
2389
|
-
|
|
2390
|
-
|
|
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
|
|
2391
2697
|
schema state becomes live only after the native commit. Point `write` / `insert` /
|
|
2392
2698
|
`delete` check `OperationOptions.signal`
|
|
2393
2699
|
immediately before the synchronous SQLite call; that call entry is the commit
|
|
2394
2700
|
point, so there is no post-check that could relabel a completed commit.
|
|
2395
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
|
+
|
|
2396
2755
|
### Persistence with the IndexedDB driver
|
|
2397
2756
|
|
|
2398
|
-
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:
|
|
2399
2758
|
|
|
2400
2759
|
```ts
|
|
2401
2760
|
import { createDatabase } from '@orkestrel/database'
|
|
@@ -2413,7 +2772,7 @@ if (typeof indexedDB !== 'undefined') {
|
|
|
2413
2772
|
.table('users')
|
|
2414
2773
|
.query()
|
|
2415
2774
|
.condition({ column: 'id', operator: 'equals', values: ['u1'], connector: 'and' })
|
|
2416
|
-
.collect() //
|
|
2775
|
+
.collect() // answered by a key range on the primary key
|
|
2417
2776
|
}
|
|
2418
2777
|
```
|
|
2419
2778
|
|
|
@@ -2425,48 +2784,82 @@ publishing schema/identity/connection state or changing the record. The
|
|
|
2425
2784
|
bootstrap closes in every outcome, so external repair or version activity is
|
|
2426
2785
|
not blocked and the same driver may retry. It then connects the deployed
|
|
2427
2786
|
`DriverMetadata.schema` plus `__metadata__`; it does not create the target declaration
|
|
2428
|
-
before reconciliation.
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
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` —
|
|
2434
2816
|
`open()` throws `DatabaseError('VALIDATION')` if a declared table is
|
|
2435
2817
|
literally named `__metadata__`), but omits `transaction?` (the underlying
|
|
2436
2818
|
`IDBTransaction` auto-commits the moment control yields to a non-IDB
|
|
2437
|
-
`await`)
|
|
2438
|
-
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,
|
|
2439
2820
|
row transformations, and the metadata write in the same versionchange
|
|
2440
2821
|
transaction; a metadata-only input uses one ordinary `__metadata__` write
|
|
2441
|
-
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
|
|
2442
2824
|
`write` / `insert` / `delete` still uses one explicit
|
|
2443
2825
|
wrapper `database.write(table, scope)` transaction: the signal aborts it only
|
|
2444
2826
|
while active, a signal-driven rollback maps to `DatabaseError('ABORTED')`, and
|
|
2445
2827
|
native transaction completion is the commit boundary a late abort cannot
|
|
2446
2828
|
rewrite.
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
`
|
|
2451
|
-
|
|
2452
|
-
`
|
|
2453
|
-
|
|
2454
|
-
`
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
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.
|
|
2838
|
+
|
|
2839
|
+
### IndexedDB planning
|
|
2840
|
+
|
|
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:
|
|
2465
2853
|
|
|
2466
2854
|
```ts
|
|
2467
2855
|
import type { Condition, TableSchema } from '@orkestrel/database'
|
|
2468
2856
|
import { isKey } from '@orkestrel/database'
|
|
2469
|
-
import {
|
|
2857
|
+
import {
|
|
2858
|
+
conditionToRange,
|
|
2859
|
+
deriveIndexedDBIndexName,
|
|
2860
|
+
findAccessPlan,
|
|
2861
|
+
planIndexedDBQuery,
|
|
2862
|
+
} from '@orkestrel/database/browser'
|
|
2470
2863
|
|
|
2471
2864
|
const schema: TableSchema = {
|
|
2472
2865
|
name: 'users',
|
|
@@ -2474,8 +2867,9 @@ const schema: TableSchema = {
|
|
|
2474
2867
|
columns: [
|
|
2475
2868
|
{ name: 'id', storage: 'text', optional: false, nullable: false },
|
|
2476
2869
|
{ name: 'age', storage: 'integer', optional: false, nullable: false },
|
|
2870
|
+
{ name: 'city', storage: 'text', optional: true, nullable: false },
|
|
2477
2871
|
],
|
|
2478
|
-
indexes: [['age']],
|
|
2872
|
+
indexes: [['age'], ['city']],
|
|
2479
2873
|
}
|
|
2480
2874
|
|
|
2481
2875
|
isKey('u1') // true — a string is a usable IndexedDB key
|
|
@@ -2490,16 +2884,21 @@ const equalsAge: Condition = {
|
|
|
2490
2884
|
}
|
|
2491
2885
|
conditionToRange(equalsAge) // an IDBKeyRange.only(30) — an exact comparison operator
|
|
2492
2886
|
|
|
2493
|
-
//
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
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: {} }
|
|
2889
|
+
|
|
2890
|
+
// A range over the required `age` index is the access path, and it serves an order on age:
|
|
2891
|
+
const fromAge: Condition = { column: 'age', operator: 'from', values: [18], connector: 'and' }
|
|
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 }
|
|
2503
2902
|
```
|
|
2504
2903
|
|
|
2505
2904
|
### IndexedDB error mapping
|
|
@@ -2515,15 +2914,15 @@ import { mapIndexedDBError, mapMigrationError } from '@orkestrel/database/browse
|
|
|
2515
2914
|
declare const fault: IndexedDBError // a caught backend fault
|
|
2516
2915
|
|
|
2517
2916
|
mapIndexedDBError(fault) // → DatabaseError('CONFLICT' | 'CLOSED' | 'DRIVER', ...)
|
|
2518
|
-
mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATION'
|
|
2917
|
+
mapMigrationError(fault) // → the same, but an UPGRADE or a RECORD fault becomes 'MIGRATION'
|
|
2519
2918
|
```
|
|
2520
2919
|
|
|
2521
2920
|
### Practices
|
|
2522
2921
|
|
|
2523
2922
|
- **Declare tables in `createDatabase({ tables })` and hold the handles** —
|
|
2524
2923
|
`const users = db.table('users')`; reuse them rather than re-resolving.
|
|
2525
|
-
- **Writes admit whole, reads narrow.** At an unknown-input boundary,
|
|
2526
|
-
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
|
|
2527
2926
|
its value; a refusal carries the faults to report. Trust `get` / `records`
|
|
2528
2927
|
to return the row type.
|
|
2529
2928
|
- **Use `resolve` when absence is an error**, `get` when it is expected —
|
|
@@ -2545,34 +2944,110 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
|
|
|
2545
2944
|
- **Use `MemoryDriver` for tests and ephemeral data** — no I/O, and
|
|
2546
2945
|
`JSONDriver` swaps in unchanged when writes need to survive a restart.
|
|
2547
2946
|
|
|
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 |
|
|
2980
|
+
|
|
2981
|
+
The paging wave changes these exports and behaviors; under the no-shim law, each consumer
|
|
2982
|
+
changes in the release that adopts it. A name in this section that the package no longer
|
|
2983
|
+
exports is written plain, without code formatting.
|
|
2984
|
+
|
|
2985
|
+
| 0.0.23 | This release |
|
|
2986
|
+
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2987
|
+
| matchesQueryExactly(input, schema) | `planSQLiteQuery(input, schema)`, which returns a `ReadPlan`; a read is wholly native when `residual` equals `{}` |
|
|
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 |
|
|
2989
|
+
| matchesConditionExactly | `matchesSQLiteCondition(condition, schema)` |
|
|
2990
|
+
| matchesOrderExactly, matchesAggregateExactly, EXACT_COLUMN_STORAGE, EXACT_RANGE_COLUMN_STORAGE | Removed; `planSQLiteQuery` answers each question |
|
|
2991
|
+
| selectPlan(input, schema, indexes) | `findAccessPlan(input, schema, indexes)` for the access path, and `planIndexedDBQuery(input, schema, indexes)` for the split |
|
|
2992
|
+
| QueryPlan | `AccessPlan` |
|
|
2993
|
+
| `MemoryDriver.stream`, `JSONDriver.stream` | Removed; call `Table.scan`, or `streamPlannedRows` over the driver |
|
|
2994
|
+
| `matchesWildcardSegment(value: string, segment: string, …)` | `matchesWildcardSegment(value: readonly string[], segment: readonly string[], …)`, over code points |
|
|
2995
|
+
| `decodeValue` and `decodeRow` returning absence for a malformed cell | Both raise `DRIVER` with `table`, `column`, and `key` |
|
|
2996
|
+
| `compileOrderSQL` ending with a bare primary-key term | The primary-key term always carries `ASC` or `DESC`, in the direction of the final term |
|
|
2997
|
+
| A read that skipped a nonconforming stored row | `get`, `records`, and `scan` raise `DRIVER` with `table`, `key`, and `faults` |
|
|
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 |
|
|
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 |
|
|
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 |
|
|
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 |
|
|
3002
|
+
|
|
3003
|
+
The paging wave added names that its review then renamed or folded before release:
|
|
3004
|
+
compactReadInput is `normalizeReadInput`; comparePlans is `scanPlans`; containsValue is
|
|
3005
|
+
`matchesListed`; matchesNativeCondition is `matchesSQLiteCondition`; findNativeColumn is
|
|
3006
|
+
`findSQLiteColumn`; wrapValued is `compileGuardedSQL`; REFUSED_PRAGMAS is `PRAGMA_NAMES`, an allowlist; collectRows is removed in favor of
|
|
3007
|
+
`Array.fromAsync`; matchesNativeOrder and matchesNativeAggregate fold into
|
|
3008
|
+
`planSQLiteQuery`; classifyAbsence and the ColumnAbsence type fold into
|
|
3009
|
+
`compileConditionSQL`; decodeStoredValue folds into `decodeValue`; and `isScalar` narrows
|
|
3010
|
+
to `Scalar`.
|
|
3011
|
+
|
|
2548
3012
|
## Tests
|
|
2549
3013
|
|
|
2550
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.
|
|
2551
|
-
- [`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.
|
|
2552
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.
|
|
2553
|
-
- [`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
|
|
2554
|
-
- [`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.
|
|
2555
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.
|
|
2556
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.
|
|
2557
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.
|
|
2558
|
-
- [`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.
|
|
2559
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.
|
|
2560
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.
|
|
2561
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).
|
|
2562
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.
|
|
2563
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.
|
|
2564
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.
|
|
2565
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:'`.
|
|
2566
|
-
- [`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.
|
|
2567
|
-
- [`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
|
|
2568
|
-
- [`tests/src/server/
|
|
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.
|
|
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`.
|
|
2569
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.
|
|
2570
|
-
- [`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
|
|
2571
|
-
- [`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` (
|
|
2572
|
-
- [`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,
|
|
2573
|
-
- [`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.
|
|
2574
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).
|
|
2575
|
-
- [`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.
|
|
2576
3051
|
|
|
2577
3052
|
## See also
|
|
2578
3053
|
|