@chipmobilesdk/rn-local-db 0.1.0

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.
Files changed (81) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +726 -0
  3. package/package.json +61 -0
  4. package/src/adapter/budgets.ts +67 -0
  5. package/src/adapter/collection.ts +298 -0
  6. package/src/adapter/deletion.ts +238 -0
  7. package/src/adapter/index.ts +68 -0
  8. package/src/adapter/lifecycle.ts +444 -0
  9. package/src/adapter/transaction.ts +65 -0
  10. package/src/artifacts/availability.ts +69 -0
  11. package/src/artifacts/cascade.ts +78 -0
  12. package/src/artifacts/paths.ts +29 -0
  13. package/src/artifacts/reconcile.ts +63 -0
  14. package/src/artifacts/store.ts +323 -0
  15. package/src/contract/adapter.ts +78 -0
  16. package/src/contract/attachment.ts +72 -0
  17. package/src/contract/backup.ts +28 -0
  18. package/src/contract/config.ts +54 -0
  19. package/src/contract/encryption.ts +34 -0
  20. package/src/contract/errors.ts +76 -0
  21. package/src/contract/migration.ts +40 -0
  22. package/src/contract/query.ts +81 -0
  23. package/src/contract/record.ts +42 -0
  24. package/src/contract/schema.ts +36 -0
  25. package/src/contract/scope.ts +36 -0
  26. package/src/contract/transaction.ts +46 -0
  27. package/src/crypto/chunked-cipher.ts +144 -0
  28. package/src/crypto/derive.ts +63 -0
  29. package/src/crypto/key-provider.ts +78 -0
  30. package/src/crypto/provider.ts +81 -0
  31. package/src/diagnostics/dev-log.ts +108 -0
  32. package/src/diagnostics/errors.ts +66 -0
  33. package/src/diagnostics/faults.ts +64 -0
  34. package/src/diagnostics/map-native.ts +106 -0
  35. package/src/diagnostics/redact.ts +141 -0
  36. package/src/index.ts +110 -0
  37. package/src/migration/executor.ts +136 -0
  38. package/src/migration/ledger.ts +97 -0
  39. package/src/migration/validate-chain.ts +65 -0
  40. package/src/platform/backup-android-verify.ts +88 -0
  41. package/src/platform/backup-ios.ts +48 -0
  42. package/src/platform/fs.ts +89 -0
  43. package/src/platform/location.ts +135 -0
  44. package/src/query/budgets.ts +57 -0
  45. package/src/query/compare.ts +91 -0
  46. package/src/query/cursor.ts +99 -0
  47. package/src/query/filter.ts +82 -0
  48. package/src/query/paginate.ts +51 -0
  49. package/src/query/sort.ts +56 -0
  50. package/src/query/validate.ts +171 -0
  51. package/src/schema/declare.ts +45 -0
  52. package/src/schema/validate-config.ts +158 -0
  53. package/src/scope/hash.ts +134 -0
  54. package/src/scope/normalize.ts +90 -0
  55. package/src/scope/validate.ts +83 -0
  56. package/src/sqlite/adapter.ts +26 -0
  57. package/src/sqlite/batch.ts +232 -0
  58. package/src/sqlite/catalog.ts +108 -0
  59. package/src/sqlite/connection.ts +205 -0
  60. package/src/sqlite/index-coverage.ts +53 -0
  61. package/src/sqlite/native.ts +83 -0
  62. package/src/sqlite/row-codec.ts +201 -0
  63. package/src/sqlite/sql-builder.ts +244 -0
  64. package/src/sqlite/transactions.ts +33 -0
  65. package/src/sqlite/values.ts +24 -0
  66. package/src/testing/conformance/attachments.ts +136 -0
  67. package/src/testing/conformance/encryption.ts +150 -0
  68. package/src/testing/conformance/index.ts +161 -0
  69. package/src/testing/conformance/lifecycle.ts +99 -0
  70. package/src/testing/conformance/migrations.ts +177 -0
  71. package/src/testing/conformance/queries.ts +167 -0
  72. package/src/testing/conformance/records.ts +169 -0
  73. package/src/testing/conformance/scopes.ts +88 -0
  74. package/src/testing/conformance/transactions.ts +149 -0
  75. package/src/testing/faults.ts +21 -0
  76. package/src/testing/index.ts +21 -0
  77. package/src/testing/memory-adapter/collection.ts +219 -0
  78. package/src/testing/memory-adapter/index.ts +388 -0
  79. package/src/testing/memory-adapter/migrations.ts +119 -0
  80. package/src/testing/memory-adapter/reset.ts +50 -0
  81. package/src/testing/memory-adapter/store.ts +134 -0
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The storage engine peer, behind one lazy accessor.
3
+ *
4
+ * Every native call the package makes to SQLite passes through this type.
5
+ * Note what is missing: `executeSync`. op-sqlite ships it, and using it would
6
+ * put a database read on the interface thread — the one thing PERF-001's
7
+ * 16-millisecond rule cannot survive (research.md R9). A surface that cannot
8
+ * express the synchronous call is a stronger guarantee than a review comment.
9
+ */
10
+
11
+ import { DiagnosticCodes } from '../contract/errors';
12
+ import { raise } from '../diagnostics/errors';
13
+
14
+ export type SqlValue = string | number | boolean | null | undefined;
15
+
16
+ export type ExecuteResult = {
17
+ rows: Record<string, unknown>[];
18
+ rowsAffected: number;
19
+ };
20
+
21
+ export type NativeTransaction = {
22
+ execute(sql: string, params?: SqlValue[]): Promise<ExecuteResult>;
23
+ commit(): Promise<void>;
24
+ rollback(): Promise<void>;
25
+ };
26
+
27
+ export type NativeDatabase = {
28
+ execute(sql: string, params?: SqlValue[]): Promise<ExecuteResult>;
29
+ executeBatch(commands: [string, SqlValue[]?][]): Promise<ExecuteResult>;
30
+ transaction<T>(fn: (tx: NativeTransaction) => Promise<T>): Promise<T>;
31
+ close(): Promise<void>;
32
+ delete(): Promise<void>;
33
+ };
34
+
35
+ export type OpenOptions = {
36
+ name: string;
37
+ location?: string;
38
+ /** SQLCipher only. Never logged, never persisted, never returned (FR-098). */
39
+ encryptionKey?: string;
40
+ };
41
+
42
+ export type Engine = {
43
+ open(options: OpenOptions): NativeDatabase;
44
+ isSQLCipher?: () => boolean;
45
+ };
46
+
47
+ let override: Engine | null = null;
48
+ let cached: Engine | null = null;
49
+
50
+ /** Swap the engine. Tests only. */
51
+ export function setEngine(next: Engine | null): void {
52
+ override = next;
53
+ cached = null;
54
+ }
55
+
56
+ export function engine(): Engine {
57
+ if (override) {
58
+ return override;
59
+ }
60
+ if (!cached) {
61
+ try {
62
+ cached = require('@op-engineering/op-sqlite') as Engine;
63
+ } catch (error) {
64
+ raise(DiagnosticCodes.OPEN_FAILED, {
65
+ message: 'storage engine peer is not installed',
66
+ cause: error,
67
+ });
68
+ }
69
+ }
70
+ return cached!;
71
+ }
72
+
73
+ /**
74
+ * Whether SQLCipher is compiled into this build.
75
+ *
76
+ * A build flag in the consuming app, not a separate peer (research.md R1a).
77
+ * An app that enables encryption without it must fail loudly rather than
78
+ * write plaintext to a file it believes is encrypted.
79
+ */
80
+ export function isEncryptionAvailable(): boolean {
81
+ const current = engine();
82
+ return typeof current.isSQLCipher === 'function' ? current.isSQLCipher() === true : false;
83
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Table shape, and the payload-as-truth rule.
3
+ *
4
+ * Every read reconstructs the record from `payload` alone. The projected
5
+ * `f_*` columns are written on every write and consulted only by `WHERE` and
6
+ * `ORDER BY` — never by a read path (research.md R6).
7
+ *
8
+ * That single rule is what makes two requirements structural rather than
9
+ * carefully maintained. FR-018's byte fidelity holds because nothing else is
10
+ * consulted to rebuild a record, and FR-019's explicit-null versus
11
+ * absent-field distinction holds because a NULL projected column cannot be
12
+ * ambiguous if no read ever looks at it.
13
+ */
14
+
15
+ import type { StorableRecordData, StoredRecord } from '../contract/record';
16
+ import type { CollectionSchema, FieldDeclaration } from '../contract/schema';
17
+ import { collectionTable, hasSoftDelete, hasTimestamps, projectedColumn } from '../schema/declare';
18
+ import type { SqlValue } from './native';
19
+ import { num, text } from './values';
20
+
21
+ export const RESERVED_COLUMNS = ['id', 'payload', 'created_at', 'updated_at', 'deleted_at'];
22
+
23
+ /** SQLite affinity for a declared field type. */
24
+ function affinityOf(field: FieldDeclaration): string {
25
+ switch (field.type) {
26
+ case 'number':
27
+ case 'timestamp':
28
+ return 'REAL';
29
+ case 'boolean':
30
+ return 'INTEGER';
31
+ case 'string':
32
+ default:
33
+ return 'TEXT';
34
+ }
35
+ }
36
+
37
+ export function createTableSql(schema: CollectionSchema): string {
38
+ const columns = [
39
+ 'id TEXT PRIMARY KEY',
40
+ 'payload TEXT NOT NULL',
41
+ 'created_at INTEGER',
42
+ 'updated_at INTEGER',
43
+ 'deleted_at INTEGER',
44
+ ...(schema.fields ?? []).map(
45
+ field => `"${projectedColumn(field.name)}" ${affinityOf(field)}`,
46
+ ),
47
+ ];
48
+ return `CREATE TABLE IF NOT EXISTS "${collectionTable(schema.name)}" (${columns.join(', ')})`;
49
+ }
50
+
51
+ export function addColumnSql(schema: CollectionSchema, field: FieldDeclaration): string {
52
+ return `ALTER TABLE "${collectionTable(schema.name)}" ADD COLUMN "${projectedColumn(
53
+ field.name,
54
+ )}" ${affinityOf(field)}`;
55
+ }
56
+
57
+ export function createIndexSql(schema: CollectionSchema): string[] {
58
+ const table = collectionTable(schema.name);
59
+ const statements = (schema.indexes ?? []).map(index => {
60
+ const columns = index.fields.map(field => `"${projectedColumn(field)}"`).join(', ');
61
+ return `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS "${
62
+ index.name
63
+ }" ON "${table}" (${columns})`;
64
+ });
65
+ if (hasSoftDelete(schema)) {
66
+ // Every default query carries `deleted_at IS NULL`, so without this the
67
+ // exclusion turns the cheapest possible filter into a full scan.
68
+ statements.push(
69
+ `CREATE INDEX IF NOT EXISTS "${table}_live" ON "${table}" (deleted_at)`,
70
+ );
71
+ }
72
+ return statements;
73
+ }
74
+
75
+ /**
76
+ * Project a declared field for the WHERE and ORDER BY columns.
77
+ *
78
+ * Anything that is not a comparable primitive projects to NULL. A nested
79
+ * object has no defensible ordering, and inventing one would make a filter
80
+ * silently match records a consumer never meant to select.
81
+ */
82
+ export function projectValue(data: StorableRecordData, field: FieldDeclaration): SqlValue {
83
+ if (!Object.prototype.hasOwnProperty.call(data, field.name)) {
84
+ return null;
85
+ }
86
+ const value = data[field.name];
87
+ if (value === null) {
88
+ return null;
89
+ }
90
+ switch (typeof value) {
91
+ case 'boolean':
92
+ return value ? 1 : 0;
93
+ case 'number':
94
+ return Number.isFinite(value) ? value : null;
95
+ case 'string':
96
+ return value;
97
+ default:
98
+ return null;
99
+ }
100
+ }
101
+
102
+ export function projectedValues(schema: CollectionSchema, data: StorableRecordData): SqlValue[] {
103
+ return (schema.fields ?? []).map(field => projectValue(data, field));
104
+ }
105
+
106
+ export function projectedColumnNames(schema: CollectionSchema): string[] {
107
+ return (schema.fields ?? []).map(field => projectedColumn(field.name));
108
+ }
109
+
110
+ /** Serialize on the way in, so a caller mutating its object cannot change
111
+ * what is stored (FR-022). */
112
+ export function encodePayload(data: StorableRecordData): string {
113
+ return JSON.stringify(data ?? {});
114
+ }
115
+
116
+ export type CollectionRow = {
117
+ id: string;
118
+ payload: string;
119
+ created_at?: number | null;
120
+ updated_at?: number | null;
121
+ deleted_at?: number | null;
122
+ };
123
+
124
+ /**
125
+ * Rebuild a record from the payload column and nothing else.
126
+ *
127
+ * The timestamp and soft-delete fields are surfaced only when the collection
128
+ * declared them, so a consumer cannot come to depend on a field the schema
129
+ * never promised.
130
+ */
131
+ export function decodeRow<T extends StorableRecordData>(
132
+ schema: CollectionSchema,
133
+ row: Record<string, unknown>,
134
+ ): StoredRecord<T> {
135
+ const record: StoredRecord<T> = {
136
+ id: text(row.id),
137
+ data: JSON.parse(text(row.payload)) as T,
138
+ };
139
+ if (hasTimestamps(schema)) {
140
+ if (row.created_at != null) {
141
+ record.createdAt = num(row.created_at);
142
+ }
143
+ if (row.updated_at != null) {
144
+ record.updatedAt = num(row.updated_at);
145
+ }
146
+ }
147
+ if (hasSoftDelete(schema)) {
148
+ record.deletedAt = row.deleted_at == null ? null : num(row.deleted_at);
149
+ }
150
+ return record;
151
+ }
152
+
153
+ export type WriteColumns = {
154
+ columns: string[];
155
+ values: SqlValue[];
156
+ };
157
+
158
+ export function insertColumns(
159
+ schema: CollectionSchema,
160
+ id: string,
161
+ data: StorableRecordData,
162
+ now: number,
163
+ ): WriteColumns {
164
+ const columns = ['id', 'payload'];
165
+ const values: SqlValue[] = [id, encodePayload(data)];
166
+
167
+ if (hasTimestamps(schema)) {
168
+ columns.push('created_at', 'updated_at');
169
+ values.push(now, now);
170
+ }
171
+ if (hasSoftDelete(schema)) {
172
+ columns.push('deleted_at');
173
+ values.push(null);
174
+ }
175
+ const projected = projectedValues(schema, data);
176
+ for (const [index, name] of projectedColumnNames(schema).entries()) {
177
+ columns.push(name);
178
+ values.push(projected[index]!);
179
+ }
180
+ return { columns, values };
181
+ }
182
+
183
+ export function updateAssignments(
184
+ schema: CollectionSchema,
185
+ data: StorableRecordData,
186
+ now: number,
187
+ ): WriteColumns {
188
+ const columns = ['payload'];
189
+ const values: SqlValue[] = [encodePayload(data)];
190
+
191
+ if (hasTimestamps(schema)) {
192
+ columns.push('updated_at');
193
+ values.push(now);
194
+ }
195
+ const projected = projectedValues(schema, data);
196
+ for (const [index, name] of projectedColumnNames(schema).entries()) {
197
+ columns.push(name);
198
+ values.push(projected[index]!);
199
+ }
200
+ return { columns, values };
201
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Filter tree to parameterized SQL.
3
+ *
4
+ * Nothing a consumer supplies is ever concatenated into a statement. Field
5
+ * names are resolved through the schema first — validation has already run
6
+ * and rejected anything undeclared (FR-034) — so the only identifiers that
7
+ * reach SQL are ones this package generated from a declaration it checked.
8
+ * Values bind as parameters, without exception. Injection stops being a thing
9
+ * to remember and becomes a thing the shape of the code prevents.
10
+ *
11
+ * The other half of this file is keyset pagination. `OFFSET` was rejected for
12
+ * two measured reasons (research.md R6): it degrades linearly at the 100,000
13
+ * record budget because the engine still walks the skipped rows, and it
14
+ * shifts pages under concurrent writes so a record can be skipped or returned
15
+ * twice — the exact failure SC-007 forbids.
16
+ */
17
+
18
+ import type { FilterNode, FilterValue, SortKey } from '../contract/query';
19
+ import { projectedColumn } from '../schema/declare';
20
+ import type { SqlValue } from './native';
21
+
22
+ export type SqlFragment = {
23
+ sql: string;
24
+ params: SqlValue[];
25
+ };
26
+
27
+ const TRUE: SqlFragment = { sql: '1', params: [] };
28
+ const FALSE: SqlFragment = { sql: '0', params: [] };
29
+
30
+ function columnFor(field: string): string {
31
+ return field === 'id' ? 'id' : `"${projectedColumn(field)}"`;
32
+ }
33
+
34
+ /**
35
+ * The JSON path for a declared field.
36
+ *
37
+ * Safe to interpolate: the field name came from a schema declaration that
38
+ * validation already matched against `^[A-Za-z][A-Za-z0-9_]{0,62}$`, so it
39
+ * cannot carry a quote, a dollar sign, or a path separator.
40
+ */
41
+ function jsonType(field: string): string {
42
+ return `json_type(payload, '$.${field}')`;
43
+ }
44
+
45
+ /** Present, and holding something a comparison can be defined over. */
46
+ function presentPrimitive(field: string): string {
47
+ return `(${jsonType(field)} IS NOT NULL AND ${jsonType(field)} NOT IN ('object', 'array'))`;
48
+ }
49
+
50
+ /** Present and explicitly null — the condition `isNull` actually means. */
51
+ function isExplicitNull(field: string): string {
52
+ return `${jsonType(field)} = 'null'`;
53
+ }
54
+
55
+ /** Booleans project to 0/1, so a bound parameter has to match. */
56
+ function bind(value: FilterValue): SqlValue {
57
+ return typeof value === 'boolean' ? (value ? 1 : 0) : value;
58
+ }
59
+
60
+ function comparison(node: Extract<FilterNode, { field: string }>): SqlFragment {
61
+ const field = node.field;
62
+ const column = columnFor(field);
63
+
64
+ switch (node.op) {
65
+ case 'exists':
66
+ return {
67
+ sql: node.value ? `${jsonType(field)} IS NOT NULL` : `${jsonType(field)} IS NULL`,
68
+ params: [],
69
+ };
70
+
71
+ case 'isNull':
72
+ return { sql: isExplicitNull(field), params: [] };
73
+
74
+ case 'isNotNull':
75
+ return {
76
+ sql: `(${jsonType(field)} IS NOT NULL AND ${jsonType(field)} != 'null')`,
77
+ params: [],
78
+ };
79
+
80
+ case 'eq':
81
+ // Matching an explicit null needs the JSON type: `col = NULL` is
82
+ // NULL in SQL, which is not true, and a projected NULL cannot tell
83
+ // "absent" from "null" on its own.
84
+ return node.value === null
85
+ ? { sql: isExplicitNull(field), params: [] }
86
+ : { sql: `${column} = ?`, params: [bind(node.value)] };
87
+
88
+ case 'ne':
89
+ return node.value === null
90
+ ? {
91
+ sql: `(${presentPrimitive(field)} AND ${jsonType(field)} != 'null')`,
92
+ params: [],
93
+ }
94
+ : {
95
+ sql: `(${presentPrimitive(field)} AND ${column} IS NOT ?)`,
96
+ params: [bind(node.value)],
97
+ };
98
+
99
+ case 'lt':
100
+ case 'lte':
101
+ case 'gt':
102
+ case 'gte': {
103
+ if (node.value === null) {
104
+ // An ordered comparison against null has no answer; SQL would
105
+ // return NULL and the in-memory adapter returns false. Being
106
+ // explicit keeps the two identical.
107
+ return FALSE;
108
+ }
109
+ const operator = { lt: '<', lte: '<=', gt: '>', gte: '>=' }[node.op];
110
+ return {
111
+ sql: `(${column} IS NOT NULL AND ${column} ${operator} ?)`,
112
+ params: [bind(node.value)],
113
+ };
114
+ }
115
+
116
+ case 'between': {
117
+ const [low, high] = node.value;
118
+ if (low === null || high === null) {
119
+ return FALSE;
120
+ }
121
+ return {
122
+ sql: `(${column} IS NOT NULL AND ${column} BETWEEN ? AND ?)`,
123
+ params: [bind(low), bind(high)],
124
+ };
125
+ }
126
+
127
+ case 'in':
128
+ case 'nin': {
129
+ const values = node.value;
130
+ const nonNull = values.filter((value): value is Exclude<FilterValue, null> => value !== null);
131
+ const acceptsNull = values.length !== nonNull.length;
132
+
133
+ const clauses: string[] = [];
134
+ const params: SqlValue[] = [];
135
+ if (nonNull.length > 0) {
136
+ clauses.push(`${column} IN (${nonNull.map(() => '?').join(', ')})`);
137
+ params.push(...nonNull.map(value => bind(value)));
138
+ }
139
+ if (acceptsNull) {
140
+ clauses.push(isExplicitNull(field));
141
+ }
142
+ const membership = clauses.length > 0 ? `(${clauses.join(' OR ')})` : '0';
143
+
144
+ if (node.op === 'in') {
145
+ return { sql: membership, params };
146
+ }
147
+ // `nin` excludes, but only among records that have the field at
148
+ // all: an absent field satisfies no comparison, negated or not.
149
+ return {
150
+ sql: `(${presentPrimitive(field)} AND NOT IFNULL(${membership}, 0))`,
151
+ params,
152
+ };
153
+ }
154
+
155
+ default:
156
+ return FALSE;
157
+ }
158
+ }
159
+
160
+ export function buildFilter(node: FilterNode | undefined): SqlFragment {
161
+ if (!node) {
162
+ return TRUE;
163
+ }
164
+ switch (node.op) {
165
+ case 'and':
166
+ case 'or': {
167
+ const parts = node.nodes.map(child => buildFilter(child));
168
+ return {
169
+ sql: `(${parts.map(part => part.sql).join(node.op === 'and' ? ' AND ' : ' OR ')})`,
170
+ params: parts.flatMap(part => part.params),
171
+ };
172
+ }
173
+ case 'not': {
174
+ const inner = buildFilter(node.node);
175
+ // IFNULL, because NOT NULL is NULL in SQL and would quietly drop
176
+ // rows the in-memory adapter keeps.
177
+ return { sql: `(NOT IFNULL(${inner.sql}, 0))`, params: inner.params };
178
+ }
179
+ default:
180
+ return comparison(node);
181
+ }
182
+ }
183
+
184
+ export function buildOrderBy(sort: SortKey[]): string {
185
+ return sort
186
+ .map(key => `${columnFor(key.field)} ${key.direction === 'desc' ? 'DESC' : 'ASC'}`)
187
+ .join(', ');
188
+ }
189
+
190
+ /**
191
+ * The keyset predicate: everything strictly after the cursor position.
192
+ *
193
+ * Lexicographic across the sort keys — equal on the first means the second
194
+ * decides, down to the `id` tiebreaker that guarantees a total order. NULL is
195
+ * treated as smaller than every value, matching both SQLite's default
196
+ * ordering and `compareValues`, so the two adapters page identically.
197
+ */
198
+ export function buildKeysetPredicate(sort: SortKey[], anchor: FilterValue[]): SqlFragment {
199
+ const params: SqlValue[] = [];
200
+
201
+ const build = (index: number): string => {
202
+ if (index >= sort.length) {
203
+ return '0';
204
+ }
205
+ const key = sort[index]!;
206
+ const column = columnFor(key.field);
207
+ const value = anchor[index] ?? null;
208
+ const descending = key.direction === 'desc';
209
+
210
+ let strictly: string;
211
+ if (descending) {
212
+ if (value === null) {
213
+ // Nothing sorts before null, so a descending walk anchored on
214
+ // null has nothing left ahead of it on this key.
215
+ strictly = '0';
216
+ } else {
217
+ strictly = `(${column} IS NULL OR ${column} < ?)`;
218
+ params.push(bind(value));
219
+ }
220
+ } else if (value === null) {
221
+ strictly = `${column} IS NOT NULL`;
222
+ } else {
223
+ strictly = `${column} > ?`;
224
+ params.push(bind(value));
225
+ }
226
+
227
+ const equal = `${column} IS ?`;
228
+ const equalParam = bind(value);
229
+
230
+ if (index === sort.length - 1) {
231
+ return strictly;
232
+ }
233
+
234
+ // Params are pushed in the order the fragments are concatenated, so the
235
+ // equality parameter has to land between this key's comparison and the
236
+ // next key's fragment.
237
+ const head = `(${strictly} OR (${equal} AND `;
238
+ params.push(equalParam);
239
+ const tail = build(index + 1);
240
+ return `${head}${tail}))`;
241
+ };
242
+
243
+ return { sql: build(0), params };
244
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The transaction primitive.
3
+ *
4
+ * A transaction never spans two scopes, and not because a check forbids it:
5
+ * a transaction runs on one connection, a connection is opened against one
6
+ * scope's file, and the public surface offers no way to reach a second one
7
+ * from inside. FR-038 is a type error rather than a runtime one (research.md
8
+ * R2).
9
+ *
10
+ * Rollback fidelity is SQLite's, not this package's. A failure at any step
11
+ * unwinds through the engine's own `ROLLBACK`, which is the only way SC-006's
12
+ * "identical to its pre-transaction state, every time" survives a process
13
+ * kill halfway through.
14
+ */
15
+
16
+ import type { Connection, TransactionExecutor } from './connection';
17
+
18
+ /**
19
+ * Run `body` inside one transaction on one scope.
20
+ *
21
+ * Deliberately thin. The interesting behavior — read-your-own-writes,
22
+ * terminal-state rejection, what a settled transaction does when used again —
23
+ * belongs to `adapter/transaction.ts`, where both adapters can be held to the
24
+ * same rules.
25
+ */
26
+ export function runInTransaction<R>(
27
+ connection: Connection,
28
+ body: (tx: TransactionExecutor) => Promise<R>,
29
+ ): Promise<R> {
30
+ return connection.transaction(body);
31
+ }
32
+
33
+ export type { TransactionExecutor };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Reading values back out of a result row.
3
+ *
4
+ * The engine hands back `unknown` per column, and every read site would
5
+ * otherwise repeat the same `String(...)` / `Number(...)` coercion with a
6
+ * slightly different null check. One place to do it means one place where the
7
+ * "NULL means absent, not empty string" rule is decided.
8
+ */
9
+
10
+ export function text(value: unknown): string {
11
+ return typeof value === 'string' ? value : String(value as string | number | boolean);
12
+ }
13
+
14
+ export function num(value: unknown): number {
15
+ return typeof value === 'number' ? value : Number(value as string | number);
16
+ }
17
+
18
+ export function maybeText(value: unknown): string | null {
19
+ return value == null ? null : text(value);
20
+ }
21
+
22
+ export function maybeNum(value: unknown): number | null {
23
+ return value == null ? null : num(value);
24
+ }