@chipmobilesdk/rn-local-db 0.2.0 → 0.2.1
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/CHANGELOG.md +122 -102
- package/README.md +728 -728
- package/package.json +59 -62
- package/skills/sdk-rn-local-db/SKILL.md +0 -1
- package/src/adapter/budgets.ts +67 -67
- package/src/adapter/collection.ts +303 -298
- package/src/adapter/deletion.ts +252 -252
- package/src/adapter/index.ts +64 -68
- package/src/adapter/lifecycle.ts +517 -520
- package/src/adapter/transaction.ts +71 -71
- package/src/artifacts/availability.ts +67 -67
- package/src/artifacts/cascade.ts +114 -114
- package/src/artifacts/paths.ts +29 -29
- package/src/artifacts/reconcile.ts +63 -63
- package/src/artifacts/store.ts +334 -345
- package/src/contract/adapter.ts +76 -78
- package/src/contract/attachment.ts +75 -78
- package/src/contract/backup.ts +28 -28
- package/src/contract/config.ts +54 -54
- package/src/contract/encryption.ts +34 -34
- package/src/contract/errors.ts +76 -76
- package/src/contract/migration.ts +42 -42
- package/src/contract/query.ts +81 -81
- package/src/contract/record.ts +46 -51
- package/src/contract/schema.ts +36 -36
- package/src/contract/scope.ts +36 -36
- package/src/contract/transaction.ts +52 -54
- package/src/crypto/chunked-cipher.ts +153 -150
- package/src/crypto/derive.ts +64 -64
- package/src/crypto/key-provider.ts +78 -78
- package/src/crypto/provider.ts +81 -81
- package/src/diagnostics/dev-log.ts +112 -108
- package/src/diagnostics/errors.ts +62 -66
- package/src/diagnostics/faults.ts +58 -64
- package/src/diagnostics/map-native.ts +108 -106
- package/src/diagnostics/redact.ts +137 -141
- package/src/index.ts +80 -110
- package/src/migration/executor.ts +132 -136
- package/src/migration/ledger.ts +95 -97
- package/src/migration/validate-chain.ts +65 -65
- package/src/platform/backup-android-verify.ts +88 -88
- package/src/platform/backup-ios.ts +48 -48
- package/src/platform/bytes.ts +144 -144
- package/src/platform/fs.ts +89 -89
- package/src/platform/location.ts +135 -135
- package/src/query/budgets.ts +54 -54
- package/src/query/compare.ts +91 -91
- package/src/query/cursor.ts +100 -100
- package/src/query/filter.ts +82 -82
- package/src/query/paginate.ts +51 -51
- package/src/query/sort.ts +55 -56
- package/src/query/validate.ts +171 -171
- package/src/schema/declare.ts +42 -45
- package/src/schema/validate-config.ts +158 -158
- package/src/scope/hash.ts +131 -134
- package/src/scope/normalize.ts +83 -90
- package/src/scope/validate.ts +83 -83
- package/src/sqlite/adapter.ts +26 -26
- package/src/sqlite/batch.ts +242 -242
- package/src/sqlite/catalog.ts +105 -108
- package/src/sqlite/connection.ts +227 -227
- package/src/sqlite/index-coverage.ts +54 -56
- package/src/sqlite/native.ts +83 -83
- package/src/sqlite/row-codec.ts +217 -221
- package/src/sqlite/sql-builder.ts +244 -244
- package/src/sqlite/transaction-queue.ts +87 -87
- package/src/sqlite/transactions.ts +33 -33
- package/src/sqlite/values.ts +24 -24
- package/src/testing/conformance/attachments.ts +138 -136
- package/src/testing/conformance/encryption.ts +150 -150
- package/src/testing/conformance/index.ts +161 -161
- package/src/testing/conformance/lifecycle.ts +99 -99
- package/src/testing/conformance/migrations.ts +177 -177
- package/src/testing/conformance/queries.ts +204 -167
- package/src/testing/conformance/records.ts +169 -169
- package/src/testing/conformance/scopes.ts +86 -88
- package/src/testing/conformance/transactions.ts +149 -149
- package/src/testing/faults.ts +21 -21
- package/src/testing/index.ts +17 -21
- package/src/testing/memory-adapter/collection.ts +214 -219
- package/src/testing/memory-adapter/index.ts +510 -492
- package/src/testing/memory-adapter/migrations.ts +117 -119
- package/src/testing/memory-adapter/reset.ts +50 -50
- package/src/testing/memory-adapter/store.ts +128 -134
package/src/adapter/lifecycle.ts
CHANGED
|
@@ -1,520 +1,517 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Opening and closing a database.
|
|
3
|
-
*
|
|
4
|
-
* The order of operations here is the design, not an implementation detail:
|
|
5
|
-
*
|
|
6
|
-
* 1. **Validate everything first.** Configuration, scope, and the migration
|
|
7
|
-
* chain are checked before a file is touched, so a developer error is
|
|
8
|
-
* reported against an untouched database (FR-006, FR-053).
|
|
9
|
-
* 2. **Consult the catalog before opening the scope file.** A posture
|
|
10
|
-
* mismatch is detectable there; discovering it from SQLCipher's "file is
|
|
11
|
-
* not a database" would report corruption for what is actually an app
|
|
12
|
-
* configuration change (FR-101).
|
|
13
|
-
* 3. **Migrate before returning.** Nothing observes a half-migrated schema,
|
|
14
|
-
* because there is no handle to observe it with until the chain completes
|
|
15
|
-
* (FR-055). A failure returns no handle at all (FR-050).
|
|
16
|
-
*
|
|
17
|
-
* Scope is bound here and nowhere else. The handle carries its scope key and
|
|
18
|
-
* no operation on it accepts a scope argument, so there is no `switchScope`
|
|
19
|
-
* to misuse and no read that could address another scope (FR-008a, FR-015).
|
|
20
|
-
* SC-002a's "a leak is not expressible" is this shape plus one file per
|
|
21
|
-
* scope — not a check somewhere that could be forgotten.
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
import type { Attachments, DatabaseHandle } from '../contract/adapter';
|
|
25
|
-
import type {
|
|
26
|
-
AttachmentInput,
|
|
27
|
-
AttachmentOwner,
|
|
28
|
-
ByteRange,
|
|
29
|
-
DeletionOutcome,
|
|
30
|
-
ReconciliationReport,
|
|
31
|
-
} from '../contract/attachment';
|
|
32
|
-
import type { EffectivePosture } from '../contract/backup';
|
|
33
|
-
import type { DatabaseConfig } from '../contract/config';
|
|
34
|
-
import { DiagnosticCodes } from '../contract/errors';
|
|
35
|
-
import type { IndexCoverageReport, Query } from '../contract/query';
|
|
36
|
-
import type { StorableRecordData } from '../contract/record';
|
|
37
|
-
import type { CollectionSchema } from '../contract/schema';
|
|
38
|
-
import type { ResolvedScope } from '../contract/scope';
|
|
39
|
-
import type {
|
|
40
|
-
BatchOperation,
|
|
41
|
-
BatchOutcome,
|
|
42
|
-
CollectionOps,
|
|
43
|
-
Transaction,
|
|
44
|
-
} from '../contract/transaction';
|
|
45
|
-
import { artifactAvailability } from '../artifacts/availability';
|
|
46
|
-
import { cascadeForOwner, unlinkArtifact, type DeferredUnlinks } from '../artifacts/cascade';
|
|
47
|
-
import { reconcileArtifacts } from '../artifacts/reconcile';
|
|
48
|
-
import {
|
|
49
|
-
ensureAttachmentTable,
|
|
50
|
-
listReferencesFor,
|
|
51
|
-
readArtifact,
|
|
52
|
-
removeArtifact,
|
|
53
|
-
writeArtifact,
|
|
54
|
-
type ArtifactContext,
|
|
55
|
-
} from '../artifacts/store';
|
|
56
|
-
import { deriveArtifactKey } from '../crypto/derive';
|
|
57
|
-
import { acquireKey, type KeyHandle } from '../crypto/key-provider';
|
|
58
|
-
import { isCipherAvailable } from '../crypto/provider';
|
|
59
|
-
import { raise } from '../diagnostics/errors';
|
|
60
|
-
import { instrument } from '../diagnostics/dev-log';
|
|
61
|
-
import { throwIfFaulted } from '../diagnostics/faults';
|
|
62
|
-
import { runMigrations } from '../migration/executor';
|
|
63
|
-
import { effectivePostureFor } from '../platform/backup-android-verify';
|
|
64
|
-
import { ensureManagedRoot, iosPosture } from '../platform/backup-ios';
|
|
65
|
-
import { layoutFor, type StorageLayout } from '../platform/location';
|
|
66
|
-
import { withStableTiebreaker } from '../query/sort';
|
|
67
|
-
import { indexSchemas } from '../schema/declare';
|
|
68
|
-
import { validateConfig } from '../schema/validate-config';
|
|
69
|
-
import { resolveScope } from '../scope/validate';
|
|
70
|
-
import { runBatch } from '../sqlite/batch';
|
|
71
|
-
import { ensureCatalog, readEntry, registerScope } from '../sqlite/catalog';
|
|
72
|
-
import {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
import {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
*
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
);
|
|
109
|
-
const present = new Set(info.rows.map(row => text(row.name)));
|
|
110
|
-
|
|
111
|
-
for (const field of schema.fields ?? []) {
|
|
112
|
-
const column = `f_${field.name}`;
|
|
113
|
-
if (present.has(column)) {
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
await connection.execute(addColumnSql(schema, field));
|
|
117
|
-
await connection.execute(
|
|
118
|
-
`UPDATE "c_${schema.name}" SET "${column}" = json_extract(payload, '$.${field.name}')`,
|
|
119
|
-
);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// Indexes created before 0.2.0 carry the bare declared name. Each one still
|
|
123
|
-
// attached to this table is dropped and recreated under its collection-scoped
|
|
124
|
-
// name; only indexes on this table are touched, and no row data moves.
|
|
125
|
-
const existing = await connection.execute(`PRAGMA index_list("c_${schema.name}")`);
|
|
126
|
-
const onTable = new Set(existing.rows.map(row => text(row.name)));
|
|
127
|
-
for (const index of schema.indexes ?? []) {
|
|
128
|
-
if (onTable.has(index.name) && index.name !== physicalIndexName(schema, index.name)) {
|
|
129
|
-
await connection.execute(`DROP INDEX IF EXISTS "${index.name}"`);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
for (const statement of createIndexSql(schema)) {
|
|
134
|
-
await connection.execute(statement);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function resolveEncryption(config: DatabaseConfig): boolean {
|
|
139
|
-
if (config.encryption?.enabled !== true) {
|
|
140
|
-
return false;
|
|
141
|
-
}
|
|
142
|
-
// Writing plaintext to a file the app believes is encrypted is the one
|
|
143
|
-
// outcome worse than refusing to open (research.md R1a).
|
|
144
|
-
if (!isEncryptionAvailable()) {
|
|
145
|
-
raise(DiagnosticCodes.ENCRYPTION_UNAVAILABLE, {
|
|
146
|
-
message: 'encryption was requested but SQLCipher is not compiled into this build',
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
if (!isCipherAvailable()) {
|
|
150
|
-
raise(DiagnosticCodes.ENCRYPTION_UNAVAILABLE, {
|
|
151
|
-
message: 'encryption was requested but the cipher peer is not installed',
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
return true;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
async function assertPostureMatches(
|
|
158
|
-
catalog: Connection,
|
|
159
|
-
scope: ResolvedScope,
|
|
160
|
-
encrypted: boolean,
|
|
161
|
-
): Promise<void> {
|
|
162
|
-
const entry = await readEntry(catalog, scope.key);
|
|
163
|
-
if (!entry) {
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
if (entry.deletionState === 'deleting') {
|
|
167
|
-
// An interrupted deletion is reported rather than opened over: the
|
|
168
|
-
// scope is neither present nor gone, and presenting it as healthy is
|
|
169
|
-
// the one answer FR-063 forbids. `deleteScopeData` finishes the job.
|
|
170
|
-
raise(DiagnosticCodes.SCOPE_DELETED, {
|
|
171
|
-
message: 'a previous deletion of this scope was interrupted',
|
|
172
|
-
detail: { scopeKey: scope.key },
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
if (entry.encrypted !== encrypted) {
|
|
176
|
-
// In-place conversion is not supported this phase (FR-103). Reporting
|
|
177
|
-
// the mismatch lets an app migrate deliberately; opening would either
|
|
178
|
-
// fail obscurely or write the wrong posture.
|
|
179
|
-
raise(DiagnosticCodes.ENCRYPTION_MISMATCH, {
|
|
180
|
-
message: 'encryption posture does not match the stored database',
|
|
181
|
-
detail: { scopeKey: scope.key },
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export async function openSqliteDatabase(
|
|
187
|
-
config: DatabaseConfig,
|
|
188
|
-
options: OpenOptions = {},
|
|
189
|
-
): Promise<DatabaseHandle> {
|
|
190
|
-
const now = options.now ?? (() => Date.now());
|
|
191
|
-
|
|
192
|
-
validateConfig(config);
|
|
193
|
-
throwIfFaulted('open');
|
|
194
|
-
const scope = resolveScope(config.scope);
|
|
195
|
-
const encrypted = resolveEncryption(config);
|
|
196
|
-
const includeInBackup = config.backup?.includeInPlatformBackup === true;
|
|
197
|
-
|
|
198
|
-
const layout: StorageLayout = layoutFor(config.name);
|
|
199
|
-
await ensureManagedRoot(layout, includeInBackup);
|
|
200
|
-
|
|
201
|
-
const catalog = await openConnection({ path: layout.catalogPath });
|
|
202
|
-
let key: KeyHandle | null = null;
|
|
203
|
-
let connection: Connection | null = null;
|
|
204
|
-
let released = false;
|
|
205
|
-
|
|
206
|
-
const releaseConnection = async (): Promise<void> => {
|
|
207
|
-
if (released || !connection) {
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
released = true;
|
|
211
|
-
await connection.close();
|
|
212
|
-
releaseHandleSlot();
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
try {
|
|
216
|
-
await ensureCatalog(catalog);
|
|
217
|
-
await assertPostureMatches(catalog, scope, encrypted);
|
|
218
|
-
|
|
219
|
-
if (encrypted) {
|
|
220
|
-
key = await acquireKey(config.encryption!, scope);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
acquireHandleSlot();
|
|
224
|
-
try {
|
|
225
|
-
connection = await openConnection({
|
|
226
|
-
path: layout.scopeDataPath(scope.key),
|
|
227
|
-
...(key ? { encryptionKey: key.value() } : {}),
|
|
228
|
-
});
|
|
229
|
-
} catch (error) {
|
|
230
|
-
releaseHandleSlot();
|
|
231
|
-
throw error;
|
|
232
|
-
}
|
|
233
|
-
await assertReadable(connection);
|
|
234
|
-
|
|
235
|
-
const schemas = indexSchemas(config.collections);
|
|
236
|
-
for (const schema of config.collections) {
|
|
237
|
-
await ensureCollection(connection, schema);
|
|
238
|
-
}
|
|
239
|
-
await ensureAttachmentTable(connection);
|
|
240
|
-
|
|
241
|
-
const scopeConnection = connection;
|
|
242
|
-
const schemaVersion = await runMigrations({
|
|
243
|
-
connection: scopeConnection,
|
|
244
|
-
config,
|
|
245
|
-
schemaFor: name => schemaFor(schemas, name),
|
|
246
|
-
now,
|
|
247
|
-
closeOnFailure: releaseConnection,
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
await registerScope(catalog, {
|
|
251
|
-
scopeKey: scope.key,
|
|
252
|
-
createdAt: now(),
|
|
253
|
-
deletionState: 'active',
|
|
254
|
-
backupPosture: includeInBackup ? 'included' : 'excluded',
|
|
255
|
-
encrypted,
|
|
256
|
-
});
|
|
257
|
-
await catalog.close();
|
|
258
|
-
clearScopeInvalidation(config.name, scope.key);
|
|
259
|
-
|
|
260
|
-
return buildHandle({
|
|
261
|
-
config,
|
|
262
|
-
connection: scopeConnection,
|
|
263
|
-
key,
|
|
264
|
-
layout,
|
|
265
|
-
now,
|
|
266
|
-
schemaVersion,
|
|
267
|
-
schemas,
|
|
268
|
-
scope,
|
|
269
|
-
posture: effectivePostureFor(layout, includeInBackup, iosPosture),
|
|
270
|
-
});
|
|
271
|
-
} catch (error) {
|
|
272
|
-
// No usable handle after a failed open (FR-002). Anything already
|
|
273
|
-
// acquired is released here rather than left for a caller who is about
|
|
274
|
-
// to be handed an exception instead of a handle.
|
|
275
|
-
key?.release();
|
|
276
|
-
await releaseConnection();
|
|
277
|
-
await catalog.close();
|
|
278
|
-
throw error;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function schemaFor(
|
|
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
|
-
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
if (
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
//
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
return handle;
|
|
520
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Opening and closing a database.
|
|
3
|
+
*
|
|
4
|
+
* The order of operations here is the design, not an implementation detail:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Validate everything first.** Configuration, scope, and the migration
|
|
7
|
+
* chain are checked before a file is touched, so a developer error is
|
|
8
|
+
* reported against an untouched database (FR-006, FR-053).
|
|
9
|
+
* 2. **Consult the catalog before opening the scope file.** A posture
|
|
10
|
+
* mismatch is detectable there; discovering it from SQLCipher's "file is
|
|
11
|
+
* not a database" would report corruption for what is actually an app
|
|
12
|
+
* configuration change (FR-101).
|
|
13
|
+
* 3. **Migrate before returning.** Nothing observes a half-migrated schema,
|
|
14
|
+
* because there is no handle to observe it with until the chain completes
|
|
15
|
+
* (FR-055). A failure returns no handle at all (FR-050).
|
|
16
|
+
*
|
|
17
|
+
* Scope is bound here and nowhere else. The handle carries its scope key and
|
|
18
|
+
* no operation on it accepts a scope argument, so there is no `switchScope`
|
|
19
|
+
* to misuse and no read that could address another scope (FR-008a, FR-015).
|
|
20
|
+
* SC-002a's "a leak is not expressible" is this shape plus one file per
|
|
21
|
+
* scope — not a check somewhere that could be forgotten.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { Attachments, DatabaseHandle } from '../contract/adapter';
|
|
25
|
+
import type {
|
|
26
|
+
AttachmentInput,
|
|
27
|
+
AttachmentOwner,
|
|
28
|
+
ByteRange,
|
|
29
|
+
DeletionOutcome,
|
|
30
|
+
ReconciliationReport,
|
|
31
|
+
} from '../contract/attachment';
|
|
32
|
+
import type { EffectivePosture } from '../contract/backup';
|
|
33
|
+
import type { DatabaseConfig } from '../contract/config';
|
|
34
|
+
import { DiagnosticCodes } from '../contract/errors';
|
|
35
|
+
import type { IndexCoverageReport, Query } from '../contract/query';
|
|
36
|
+
import type { StorableRecordData } from '../contract/record';
|
|
37
|
+
import type { CollectionSchema } from '../contract/schema';
|
|
38
|
+
import type { ResolvedScope } from '../contract/scope';
|
|
39
|
+
import type {
|
|
40
|
+
BatchOperation,
|
|
41
|
+
BatchOutcome,
|
|
42
|
+
CollectionOps,
|
|
43
|
+
Transaction,
|
|
44
|
+
} from '../contract/transaction';
|
|
45
|
+
import { artifactAvailability } from '../artifacts/availability';
|
|
46
|
+
import { cascadeForOwner, unlinkArtifact, type DeferredUnlinks } from '../artifacts/cascade';
|
|
47
|
+
import { reconcileArtifacts } from '../artifacts/reconcile';
|
|
48
|
+
import {
|
|
49
|
+
ensureAttachmentTable,
|
|
50
|
+
listReferencesFor,
|
|
51
|
+
readArtifact,
|
|
52
|
+
removeArtifact,
|
|
53
|
+
writeArtifact,
|
|
54
|
+
type ArtifactContext,
|
|
55
|
+
} from '../artifacts/store';
|
|
56
|
+
import { deriveArtifactKey } from '../crypto/derive';
|
|
57
|
+
import { acquireKey, type KeyHandle } from '../crypto/key-provider';
|
|
58
|
+
import { isCipherAvailable } from '../crypto/provider';
|
|
59
|
+
import { raise } from '../diagnostics/errors';
|
|
60
|
+
import { instrument } from '../diagnostics/dev-log';
|
|
61
|
+
import { throwIfFaulted } from '../diagnostics/faults';
|
|
62
|
+
import { runMigrations } from '../migration/executor';
|
|
63
|
+
import { effectivePostureFor } from '../platform/backup-android-verify';
|
|
64
|
+
import { ensureManagedRoot, iosPosture } from '../platform/backup-ios';
|
|
65
|
+
import { layoutFor, type StorageLayout } from '../platform/location';
|
|
66
|
+
import { withStableTiebreaker } from '../query/sort';
|
|
67
|
+
import { indexSchemas } from '../schema/declare';
|
|
68
|
+
import { validateConfig } from '../schema/validate-config';
|
|
69
|
+
import { resolveScope } from '../scope/validate';
|
|
70
|
+
import { runBatch } from '../sqlite/batch';
|
|
71
|
+
import { ensureCatalog, readEntry, registerScope } from '../sqlite/catalog';
|
|
72
|
+
import {
|
|
73
|
+
assertReadable,
|
|
74
|
+
openConnection,
|
|
75
|
+
type Connection,
|
|
76
|
+
type Executor,
|
|
77
|
+
} from '../sqlite/connection';
|
|
78
|
+
import { explainQuery } from '../sqlite/index-coverage';
|
|
79
|
+
import { isEncryptionAvailable } from '../sqlite/native';
|
|
80
|
+
import {
|
|
81
|
+
addColumnSql,
|
|
82
|
+
createIndexSql,
|
|
83
|
+
createTableSql,
|
|
84
|
+
physicalIndexName,
|
|
85
|
+
} from '../sqlite/row-codec';
|
|
86
|
+
import { runInTransaction } from '../sqlite/transactions';
|
|
87
|
+
import { text } from '../sqlite/values';
|
|
88
|
+
import { acquireHandleSlot, releaseHandleSlot } from './budgets';
|
|
89
|
+
import { createSqlCollection } from './collection';
|
|
90
|
+
import { clearScopeInvalidation, isScopeInvalidated } from './deletion';
|
|
91
|
+
import { createTransaction } from './transaction';
|
|
92
|
+
|
|
93
|
+
export type OpenOptions = {
|
|
94
|
+
now?: () => number;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Bring the physical tables in line with the declared schema.
|
|
99
|
+
*
|
|
100
|
+
* Adding a column rather than recreating the table is what makes declaring a
|
|
101
|
+
* new queryable field non-destructive: the payload already holds the value,
|
|
102
|
+
* so the new column is backfilled from it and no record is rewritten by hand
|
|
103
|
+
* (research.md R6).
|
|
104
|
+
*/
|
|
105
|
+
async function ensureCollection(connection: Connection, schema: CollectionSchema): Promise<void> {
|
|
106
|
+
await connection.execute(createTableSql(schema));
|
|
107
|
+
|
|
108
|
+
const info = await connection.execute(`PRAGMA table_info("c_${schema.name}")`);
|
|
109
|
+
const present = new Set(info.rows.map(row => text(row.name)));
|
|
110
|
+
|
|
111
|
+
for (const field of schema.fields ?? []) {
|
|
112
|
+
const column = `f_${field.name}`;
|
|
113
|
+
if (present.has(column)) {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
await connection.execute(addColumnSql(schema, field));
|
|
117
|
+
await connection.execute(
|
|
118
|
+
`UPDATE "c_${schema.name}" SET "${column}" = json_extract(payload, '$.${field.name}')`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Indexes created before 0.2.0 carry the bare declared name. Each one still
|
|
123
|
+
// attached to this table is dropped and recreated under its collection-scoped
|
|
124
|
+
// name; only indexes on this table are touched, and no row data moves.
|
|
125
|
+
const existing = await connection.execute(`PRAGMA index_list("c_${schema.name}")`);
|
|
126
|
+
const onTable = new Set(existing.rows.map(row => text(row.name)));
|
|
127
|
+
for (const index of schema.indexes ?? []) {
|
|
128
|
+
if (onTable.has(index.name) && index.name !== physicalIndexName(schema, index.name)) {
|
|
129
|
+
await connection.execute(`DROP INDEX IF EXISTS "${index.name}"`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
for (const statement of createIndexSql(schema)) {
|
|
134
|
+
await connection.execute(statement);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function resolveEncryption(config: DatabaseConfig): boolean {
|
|
139
|
+
if (config.encryption?.enabled !== true) {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
// Writing plaintext to a file the app believes is encrypted is the one
|
|
143
|
+
// outcome worse than refusing to open (research.md R1a).
|
|
144
|
+
if (!isEncryptionAvailable()) {
|
|
145
|
+
raise(DiagnosticCodes.ENCRYPTION_UNAVAILABLE, {
|
|
146
|
+
message: 'encryption was requested but SQLCipher is not compiled into this build',
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
if (!isCipherAvailable()) {
|
|
150
|
+
raise(DiagnosticCodes.ENCRYPTION_UNAVAILABLE, {
|
|
151
|
+
message: 'encryption was requested but the cipher peer is not installed',
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function assertPostureMatches(
|
|
158
|
+
catalog: Connection,
|
|
159
|
+
scope: ResolvedScope,
|
|
160
|
+
encrypted: boolean,
|
|
161
|
+
): Promise<void> {
|
|
162
|
+
const entry = await readEntry(catalog, scope.key);
|
|
163
|
+
if (!entry) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (entry.deletionState === 'deleting') {
|
|
167
|
+
// An interrupted deletion is reported rather than opened over: the
|
|
168
|
+
// scope is neither present nor gone, and presenting it as healthy is
|
|
169
|
+
// the one answer FR-063 forbids. `deleteScopeData` finishes the job.
|
|
170
|
+
raise(DiagnosticCodes.SCOPE_DELETED, {
|
|
171
|
+
message: 'a previous deletion of this scope was interrupted',
|
|
172
|
+
detail: { scopeKey: scope.key },
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (entry.encrypted !== encrypted) {
|
|
176
|
+
// In-place conversion is not supported this phase (FR-103). Reporting
|
|
177
|
+
// the mismatch lets an app migrate deliberately; opening would either
|
|
178
|
+
// fail obscurely or write the wrong posture.
|
|
179
|
+
raise(DiagnosticCodes.ENCRYPTION_MISMATCH, {
|
|
180
|
+
message: 'encryption posture does not match the stored database',
|
|
181
|
+
detail: { scopeKey: scope.key },
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function openSqliteDatabase(
|
|
187
|
+
config: DatabaseConfig,
|
|
188
|
+
options: OpenOptions = {},
|
|
189
|
+
): Promise<DatabaseHandle> {
|
|
190
|
+
const now = options.now ?? (() => Date.now());
|
|
191
|
+
|
|
192
|
+
validateConfig(config);
|
|
193
|
+
throwIfFaulted('open');
|
|
194
|
+
const scope = resolveScope(config.scope);
|
|
195
|
+
const encrypted = resolveEncryption(config);
|
|
196
|
+
const includeInBackup = config.backup?.includeInPlatformBackup === true;
|
|
197
|
+
|
|
198
|
+
const layout: StorageLayout = layoutFor(config.name);
|
|
199
|
+
await ensureManagedRoot(layout, includeInBackup);
|
|
200
|
+
|
|
201
|
+
const catalog = await openConnection({ path: layout.catalogPath });
|
|
202
|
+
let key: KeyHandle | null = null;
|
|
203
|
+
let connection: Connection | null = null;
|
|
204
|
+
let released = false;
|
|
205
|
+
|
|
206
|
+
const releaseConnection = async (): Promise<void> => {
|
|
207
|
+
if (released || !connection) {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
released = true;
|
|
211
|
+
await connection.close();
|
|
212
|
+
releaseHandleSlot();
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
try {
|
|
216
|
+
await ensureCatalog(catalog);
|
|
217
|
+
await assertPostureMatches(catalog, scope, encrypted);
|
|
218
|
+
|
|
219
|
+
if (encrypted) {
|
|
220
|
+
key = await acquireKey(config.encryption!, scope);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
acquireHandleSlot();
|
|
224
|
+
try {
|
|
225
|
+
connection = await openConnection({
|
|
226
|
+
path: layout.scopeDataPath(scope.key),
|
|
227
|
+
...(key ? { encryptionKey: key.value() } : {}),
|
|
228
|
+
});
|
|
229
|
+
} catch (error) {
|
|
230
|
+
releaseHandleSlot();
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
await assertReadable(connection);
|
|
234
|
+
|
|
235
|
+
const schemas = indexSchemas(config.collections);
|
|
236
|
+
for (const schema of config.collections) {
|
|
237
|
+
await ensureCollection(connection, schema);
|
|
238
|
+
}
|
|
239
|
+
await ensureAttachmentTable(connection);
|
|
240
|
+
|
|
241
|
+
const scopeConnection = connection;
|
|
242
|
+
const schemaVersion = await runMigrations({
|
|
243
|
+
connection: scopeConnection,
|
|
244
|
+
config,
|
|
245
|
+
schemaFor: name => schemaFor(schemas, name),
|
|
246
|
+
now,
|
|
247
|
+
closeOnFailure: releaseConnection,
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
await registerScope(catalog, {
|
|
251
|
+
scopeKey: scope.key,
|
|
252
|
+
createdAt: now(),
|
|
253
|
+
deletionState: 'active',
|
|
254
|
+
backupPosture: includeInBackup ? 'included' : 'excluded',
|
|
255
|
+
encrypted,
|
|
256
|
+
});
|
|
257
|
+
await catalog.close();
|
|
258
|
+
clearScopeInvalidation(config.name, scope.key);
|
|
259
|
+
|
|
260
|
+
return buildHandle({
|
|
261
|
+
config,
|
|
262
|
+
connection: scopeConnection,
|
|
263
|
+
key,
|
|
264
|
+
layout,
|
|
265
|
+
now,
|
|
266
|
+
schemaVersion,
|
|
267
|
+
schemas,
|
|
268
|
+
scope,
|
|
269
|
+
posture: effectivePostureFor(layout, includeInBackup, iosPosture),
|
|
270
|
+
});
|
|
271
|
+
} catch (error) {
|
|
272
|
+
// No usable handle after a failed open (FR-002). Anything already
|
|
273
|
+
// acquired is released here rather than left for a caller who is about
|
|
274
|
+
// to be handed an exception instead of a handle.
|
|
275
|
+
key?.release();
|
|
276
|
+
await releaseConnection();
|
|
277
|
+
await catalog.close();
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function schemaFor(schemas: ReadonlyMap<string, CollectionSchema>, name: string): CollectionSchema {
|
|
283
|
+
const schema = schemas.get(name);
|
|
284
|
+
if (!schema) {
|
|
285
|
+
raise(DiagnosticCodes.CONFIG_INVALID, {
|
|
286
|
+
message: 'collection is not declared',
|
|
287
|
+
detail: { collection: name },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return schema;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
type HandleContext = {
|
|
294
|
+
config: DatabaseConfig;
|
|
295
|
+
connection: Connection;
|
|
296
|
+
key: KeyHandle | null;
|
|
297
|
+
layout: StorageLayout;
|
|
298
|
+
now(): number;
|
|
299
|
+
schemaVersion: number;
|
|
300
|
+
schemas: ReadonlyMap<string, CollectionSchema>;
|
|
301
|
+
scope: ResolvedScope;
|
|
302
|
+
posture: EffectivePosture;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
function buildHandle(context: HandleContext): DatabaseHandle {
|
|
306
|
+
const { config, connection, layout, scope, schemas } = context;
|
|
307
|
+
let closed = false;
|
|
308
|
+
|
|
309
|
+
const assertUsable = (): void => {
|
|
310
|
+
if (closed) {
|
|
311
|
+
raise(DiagnosticCodes.CLOSED_HANDLE, { message: 'handle is closed' });
|
|
312
|
+
}
|
|
313
|
+
if (isScopeInvalidated(config.name, scope.key)) {
|
|
314
|
+
// The deletion did not wait for this handle, and this handle does
|
|
315
|
+
// not get to keep answering from data that is gone (FR-059a).
|
|
316
|
+
raise(DiagnosticCodes.SCOPE_DELETED, {
|
|
317
|
+
message: 'scope was deleted beneath this handle',
|
|
318
|
+
detail: { scopeKey: scope.key },
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// Everything below is built against an explicit executor: the connection for
|
|
324
|
+
// the handle, the transaction's own executor inside `transaction`. Nothing
|
|
325
|
+
// infers which one from the connection's state, which is how a write from
|
|
326
|
+
// outside used to be swallowed by an in-flight transaction (LDB-01).
|
|
327
|
+
const artifactsOn = (executor: Executor): ArtifactContext => ({
|
|
328
|
+
executor: () => executor,
|
|
329
|
+
layout,
|
|
330
|
+
scopeKey: scope.key,
|
|
331
|
+
artifactKey: attachmentId =>
|
|
332
|
+
context.key ? deriveArtifactKey(context.key.value(), scope.key, attachmentId) : null,
|
|
333
|
+
now: context.now,
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
const rawCollection = <T extends StorableRecordData>(
|
|
337
|
+
name: string,
|
|
338
|
+
executor: Executor,
|
|
339
|
+
): CollectionOps<T> => {
|
|
340
|
+
assertUsable();
|
|
341
|
+
return instrument(
|
|
342
|
+
name,
|
|
343
|
+
'sqlite',
|
|
344
|
+
createSqlCollection<T>({
|
|
345
|
+
executor: () => executor,
|
|
346
|
+
schema: schemaFor(schemas, name),
|
|
347
|
+
now: context.now,
|
|
348
|
+
assertUsable,
|
|
349
|
+
}) as unknown as Record<string, (...args: never[]) => unknown>,
|
|
350
|
+
) as unknown as CollectionOps<T>;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Record deletion optionally takes its artifacts with it (FR-070).
|
|
355
|
+
*
|
|
356
|
+
* Off unless the app asks: a package that deleted a user's files as a side
|
|
357
|
+
* effect of a record delete would be making a decision that is not its to
|
|
358
|
+
* make. The outcome carries what was removed and what could not be.
|
|
359
|
+
*/
|
|
360
|
+
const collectionOn = <T extends StorableRecordData>(
|
|
361
|
+
name: string,
|
|
362
|
+
executor: Executor,
|
|
363
|
+
deferred?: DeferredUnlinks,
|
|
364
|
+
): CollectionOps<T> => {
|
|
365
|
+
const ops = rawCollection<T>(name, executor);
|
|
366
|
+
if (config.cascadeAttachments !== true) {
|
|
367
|
+
return ops;
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
...ops,
|
|
371
|
+
async delete(id: string) {
|
|
372
|
+
const outcome = await ops.delete(id);
|
|
373
|
+
const cascade = await cascadeForOwner(
|
|
374
|
+
artifactsOn(executor),
|
|
375
|
+
executor,
|
|
376
|
+
{ collection: name, id },
|
|
377
|
+
deferred,
|
|
378
|
+
);
|
|
379
|
+
return { ...outcome, cascade };
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
const attachmentsOn = (executor: Executor, deferred?: DeferredUnlinks): Attachments => {
|
|
385
|
+
const artifacts = artifactsOn(executor);
|
|
386
|
+
return {
|
|
387
|
+
write(input: AttachmentInput) {
|
|
388
|
+
assertUsable();
|
|
389
|
+
return writeArtifact(artifacts, input);
|
|
390
|
+
},
|
|
391
|
+
read(id: string, range?: ByteRange) {
|
|
392
|
+
assertUsable();
|
|
393
|
+
return readArtifact(artifacts, id, range);
|
|
394
|
+
},
|
|
395
|
+
availability(id: string) {
|
|
396
|
+
assertUsable();
|
|
397
|
+
return artifactAvailability(artifacts, executor, id);
|
|
398
|
+
},
|
|
399
|
+
remove(id: string): Promise<DeletionOutcome> {
|
|
400
|
+
assertUsable();
|
|
401
|
+
return removeArtifact(artifacts, id, deferred);
|
|
402
|
+
},
|
|
403
|
+
listFor(owner: AttachmentOwner) {
|
|
404
|
+
assertUsable();
|
|
405
|
+
return listReferencesFor(executor, owner);
|
|
406
|
+
},
|
|
407
|
+
reconcile(options): Promise<ReconciliationReport> {
|
|
408
|
+
assertUsable();
|
|
409
|
+
return reconcileArtifacts(artifacts, executor, options);
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
const collectionFor = <T extends StorableRecordData>(name: string): CollectionOps<T> =>
|
|
415
|
+
collectionOn<T>(name, connection);
|
|
416
|
+
const attachments = attachmentsOn(connection);
|
|
417
|
+
|
|
418
|
+
const handle: DatabaseHandle = {
|
|
419
|
+
scopeKey: scope.key,
|
|
420
|
+
schemaVersion: context.schemaVersion,
|
|
421
|
+
backupPosture: context.posture,
|
|
422
|
+
isEncrypted: context.key !== null,
|
|
423
|
+
|
|
424
|
+
collection: collectionFor,
|
|
425
|
+
|
|
426
|
+
async transaction<R>(fn: (tx: Transaction) => Promise<R>): Promise<R> {
|
|
427
|
+
assertUsable();
|
|
428
|
+
const pendingUnlinks: string[] = [];
|
|
429
|
+
const deferred: DeferredUnlinks = { add: path => pendingUnlinks.push(path) };
|
|
430
|
+
let aborted = false;
|
|
431
|
+
const result = await runInTransaction(connection, async tx => {
|
|
432
|
+
const managed = createTransaction({
|
|
433
|
+
collection: name => collectionOn(name, tx, deferred),
|
|
434
|
+
attachments: () => attachmentsOn(tx, deferred),
|
|
435
|
+
rollback: async () => {
|
|
436
|
+
aborted = true;
|
|
437
|
+
await tx.rollback();
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
const value = await fn(managed.transaction);
|
|
441
|
+
if (!managed.isSettled()) {
|
|
442
|
+
throwIfFaulted('commit');
|
|
443
|
+
}
|
|
444
|
+
managed.settle();
|
|
445
|
+
return value;
|
|
446
|
+
});
|
|
447
|
+
// Committed (a thrown body never gets here). Only now are files whose
|
|
448
|
+
// references the transaction deleted safe to remove; one that cannot be
|
|
449
|
+
// removed stays on disk as an orphan reconciliation reports.
|
|
450
|
+
if (!aborted) {
|
|
451
|
+
for (const path of pendingUnlinks) {
|
|
452
|
+
await unlinkArtifact(path);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return result;
|
|
456
|
+
},
|
|
457
|
+
|
|
458
|
+
async batch(operations: BatchOperation[]): Promise<BatchOutcome> {
|
|
459
|
+
assertUsable();
|
|
460
|
+
const outcome = await runBatch(
|
|
461
|
+
{
|
|
462
|
+
connection,
|
|
463
|
+
schemaFor: name => schemaFor(schemas, name),
|
|
464
|
+
now: context.now,
|
|
465
|
+
},
|
|
466
|
+
operations,
|
|
467
|
+
);
|
|
468
|
+
if (config.cascadeAttachments !== true) {
|
|
469
|
+
return outcome;
|
|
470
|
+
}
|
|
471
|
+
// The batch has committed, so its hard deletes cascade exactly as a
|
|
472
|
+
// collection delete does. Skipping them left every attachment of a
|
|
473
|
+
// batch-deleted record behind as an orphan.
|
|
474
|
+
const artifacts = artifactsOn(connection);
|
|
475
|
+
const outcomes = [];
|
|
476
|
+
for (const [index, operation] of operations.entries()) {
|
|
477
|
+
const written = outcome.outcomes[index]!;
|
|
478
|
+
if (operation.type !== 'delete') {
|
|
479
|
+
outcomes.push(written);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const cascade = await cascadeForOwner(artifacts, connection, {
|
|
483
|
+
collection: operation.collection,
|
|
484
|
+
id: operation.id,
|
|
485
|
+
});
|
|
486
|
+
outcomes.push({ ...written, cascade });
|
|
487
|
+
}
|
|
488
|
+
return { ...outcome, outcomes };
|
|
489
|
+
},
|
|
490
|
+
|
|
491
|
+
attachments: () => attachments,
|
|
492
|
+
|
|
493
|
+
explain(collection: string, query?: Query): Promise<IndexCoverageReport> {
|
|
494
|
+
assertUsable();
|
|
495
|
+
return explainQuery(
|
|
496
|
+
connection,
|
|
497
|
+
schemaFor(schemas, collection),
|
|
498
|
+
query,
|
|
499
|
+
withStableTiebreaker(query?.sort),
|
|
500
|
+
);
|
|
501
|
+
},
|
|
502
|
+
|
|
503
|
+
async close(): Promise<void> {
|
|
504
|
+
if (closed) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
closed = true;
|
|
508
|
+
// The key goes first: a close that fails at the filesystem must not
|
|
509
|
+
// leave key material alive in a handle nobody can use (FR-098).
|
|
510
|
+
context.key?.release();
|
|
511
|
+
await connection.close();
|
|
512
|
+
releaseHandleSlot();
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
return handle;
|
|
517
|
+
}
|