@baukit/data-contracts-expo-sqlite 0.7.2 → 0.7.3

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/src/index.ts ADDED
@@ -0,0 +1,164 @@
1
+ import {
2
+ type KeyValueStore,
3
+ type RecordStore,
4
+ type ReentrantStorageTransaction,
5
+ type SchemaMetadataStore,
6
+ type StoredRecord,
7
+ type TransactionalStorageStore,
8
+ normalizeStorageError,
9
+ } from '@baukit/data-contracts';
10
+
11
+ import {
12
+ type ExpoSqliteDatabase,
13
+ QueuedDatabase,
14
+ type SQLiteFileConnection,
15
+ TransactionScope,
16
+ fileScope,
17
+ } from './queued-database.js';
18
+ import {
19
+ CREATE_ADAPTER_TABLES,
20
+ KeyValueStatements,
21
+ RecordStatements,
22
+ type SQLiteConnection,
23
+ SchemaMetadataStatements,
24
+ type StatementScope,
25
+ write,
26
+ } from './statements.js';
27
+
28
+ export type { ExpoSqliteDatabase } from './queued-database.js';
29
+ export {
30
+ ExpoSqliteConnection,
31
+ type ExpoSqliteConnectionOptions,
32
+ type SqliteStatements,
33
+ type SqliteTransaction,
34
+ } from './connection.js';
35
+
36
+ const alwaysAvailable = (): void => undefined;
37
+
38
+ /**
39
+ * A namespaced Expo SQLite implementation of Baukit's provider-neutral RecordStore.
40
+ * Statements share one queue with every adapter store that uses the same database file.
41
+ */
42
+ export class SqliteRecordStore<T extends StoredRecord> extends RecordStatements<T> {
43
+ public constructor(database: SQLiteFileConnection, namespace: string) {
44
+ super(fileScope(database, alwaysAvailable), namespace);
45
+ }
46
+ }
47
+
48
+ /** Namespaced key/value storage ordered with every adapter store on the same database file. */
49
+ export class SqliteKeyValueStore extends KeyValueStatements {
50
+ public constructor(database: SQLiteFileConnection, namespace: string) {
51
+ super(fileScope(database, alwaysAvailable), namespace);
52
+ }
53
+ }
54
+
55
+ /** Namespaced schema metadata ordered with every adapter store on the same database file. */
56
+ export class SqliteSchemaMetadataStore extends SchemaMetadataStatements {
57
+ public constructor(database: SQLiteFileConnection, namespace: string) {
58
+ super(fileScope(database, alwaysAvailable), namespace);
59
+ }
60
+ }
61
+
62
+ class ExpoSqliteTransaction<T extends StoredRecord> implements ReentrantStorageTransaction<T> {
63
+ public readonly keyValues: KeyValueStatements;
64
+ public readonly records: RecordStatements<T>;
65
+ public readonly schemaMetadata: SchemaMetadataStatements;
66
+ private readonly scope: TransactionScope;
67
+
68
+ public constructor(connection: SQLiteConnection, namespace: string) {
69
+ this.scope = new TransactionScope(connection);
70
+ this.keyValues = new KeyValueStatements(this.scope, namespace);
71
+ this.records = new RecordStatements<T>(this.scope, namespace);
72
+ this.schemaMetadata = new SchemaMetadataStatements(this.scope, namespace);
73
+ }
74
+
75
+ public async withTransaction<TResult>(
76
+ operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
77
+ ): Promise<TResult> {
78
+ this.scope.assertAvailable();
79
+ try {
80
+ return await operation(this);
81
+ } catch (cause) {
82
+ throw normalizeStorageError(cause);
83
+ }
84
+ }
85
+
86
+ public finish(): void {
87
+ this.scope.finish();
88
+ }
89
+ }
90
+
91
+ export interface ExpoSqliteStoreOptions {
92
+ /** Close the supplied database when this adapter closes. Defaults to false. */
93
+ readonly closeDatabase?: boolean;
94
+ }
95
+
96
+ /**
97
+ * Complete namespaced adapter using Expo SQLite exclusive write transactions.
98
+ * Root statements, transactions, and close run one at a time in call order, shared with every
99
+ * adapter store on the same database file.
100
+ */
101
+ export class ExpoSqliteStore<T extends StoredRecord> implements TransactionalStorageStore<T> {
102
+ public readonly keyValues: KeyValueStore;
103
+ public readonly records: RecordStore<T>;
104
+ public readonly schemaMetadata: SchemaMetadataStore;
105
+ private readonly root: StatementScope;
106
+ private readonly queued: QueuedDatabase;
107
+
108
+ public constructor(
109
+ database: ExpoSqliteDatabase,
110
+ private readonly namespace: string,
111
+ options: ExpoSqliteStoreOptions = {},
112
+ ) {
113
+ if (namespace.length === 0) {
114
+ throw new TypeError('Storage namespace must not be empty.');
115
+ }
116
+ this.queued = new QueuedDatabase(database, options.closeDatabase === true);
117
+ this.root = fileScope(database, () => {
118
+ this.queued.assertOpen();
119
+ });
120
+ this.keyValues = new KeyValueStatements(this.root, namespace);
121
+ this.records = new RecordStatements<T>(this.root, namespace);
122
+ this.schemaMetadata = new SchemaMetadataStatements(this.root, namespace);
123
+ }
124
+
125
+ public async initialize(): Promise<void> {
126
+ this.queued.assertOpen();
127
+ await write(() => this.root.run((connection) => connection.execAsync(CREATE_ADAPTER_TABLES)));
128
+ }
129
+
130
+ public async withTransaction<TResult>(
131
+ operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
132
+ ): Promise<TResult> {
133
+ this.queued.assertOpen();
134
+ try {
135
+ return await this.queued.enqueue(() => this.runExclusive(operation));
136
+ } catch (cause) {
137
+ throw normalizeStorageError(cause);
138
+ }
139
+ }
140
+
141
+ /** Rejects new work, waits for accepted work, and settles every caller with one result. */
142
+ public close(): Promise<void> {
143
+ return this.queued.close();
144
+ }
145
+
146
+ private async runExclusive<TResult>(
147
+ operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
148
+ ): Promise<TResult> {
149
+ let transaction: ExpoSqliteTransaction<T> | undefined;
150
+ let outcome: { value: TResult } | undefined;
151
+ try {
152
+ await this.queued.database.withExclusiveTransactionAsync(async (connection) => {
153
+ transaction = new ExpoSqliteTransaction<T>(connection, this.namespace);
154
+ outcome = { value: await operation(transaction) };
155
+ });
156
+ } finally {
157
+ transaction?.finish();
158
+ }
159
+ if (outcome === undefined) {
160
+ throw new Error('SQLite transaction completed without a callback result.');
161
+ }
162
+ return outcome.value;
163
+ }
164
+ }
@@ -0,0 +1,171 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ createSqliteMigrationConformanceTests,
5
+ type NodeSqliteConnection,
6
+ type NodeSqliteDatabase,
7
+ type SqliteMigrationConformanceAdapter,
8
+ type SqliteMigrationStep,
9
+ } from './testing.js';
10
+
11
+ interface RunnerOptions {
12
+ readonly transactional: boolean;
13
+ readonly refusesNewer: boolean;
14
+ }
15
+
16
+ interface VersionRow {
17
+ readonly version: number | null;
18
+ }
19
+
20
+ const HISTORY_TABLE = `CREATE TABLE IF NOT EXISTS migration_history (
21
+ version INTEGER PRIMARY KEY NOT NULL,
22
+ name TEXT NOT NULL
23
+ )`;
24
+
25
+ async function applyStep(
26
+ connection: NodeSqliteConnection,
27
+ step: SqliteMigrationStep,
28
+ ): Promise<void> {
29
+ await connection.execAsync(step.sql);
30
+ await connection.runAsync(
31
+ 'INSERT INTO migration_history (version, name) VALUES (?, ?)',
32
+ step.version,
33
+ step.name,
34
+ );
35
+ }
36
+
37
+ async function assertNotNewer(
38
+ database: NodeSqliteDatabase,
39
+ steps: readonly SqliteMigrationStep[],
40
+ ): Promise<void> {
41
+ const row = await database.getFirstAsync<VersionRow>(
42
+ 'SELECT max(version) AS version FROM migration_history',
43
+ );
44
+ const known = Math.max(0, ...steps.map((step) => step.version));
45
+ if ((row?.version ?? 0) > known) {
46
+ throw new Error(`database version ${String(row?.version)} is newer than ${String(known)}`);
47
+ }
48
+ }
49
+
50
+ function historyRunner(options: RunnerOptions): SqliteMigrationConformanceAdapter {
51
+ return {
52
+ migrate: async (database, steps) => {
53
+ await database.execAsync(HISTORY_TABLE);
54
+ if (options.refusesNewer) {
55
+ await assertNotNewer(database, steps);
56
+ }
57
+ const rows = await database.getAllAsync<VersionRow>('SELECT version FROM migration_history');
58
+ const applied = new Set(rows.map((row) => row.version));
59
+ const pending = [...steps]
60
+ .sort((left, right) => left.version - right.version)
61
+ .filter((step) => !applied.has(step.version));
62
+ for (const step of pending) {
63
+ if (options.transactional) {
64
+ await database.withExclusiveTransactionAsync((transaction) =>
65
+ applyStep(transaction, step),
66
+ );
67
+ } else {
68
+ await applyStep(database, step);
69
+ }
70
+ }
71
+ },
72
+ };
73
+ }
74
+
75
+ const ADD_COLUMN = /^ALTER TABLE (\w+) ADD COLUMN (\w+)/i;
76
+
77
+ async function hasColumn(
78
+ database: NodeSqliteDatabase,
79
+ table: string,
80
+ column: string,
81
+ ): Promise<boolean> {
82
+ const row = await database.getFirstAsync(
83
+ 'SELECT 1 FROM pragma_table_info(?) WHERE name = ?',
84
+ table,
85
+ column,
86
+ );
87
+ return row !== null;
88
+ }
89
+
90
+ async function runIdempotent(database: NodeSqliteDatabase, statement: string): Promise<void> {
91
+ const addColumn = ADD_COLUMN.exec(statement);
92
+ if (addColumn?.[1] !== undefined && addColumn[2] !== undefined) {
93
+ if (!(await hasColumn(database, addColumn[1], addColumn[2]))) {
94
+ await database.execAsync(statement);
95
+ }
96
+ return;
97
+ }
98
+ await database.execAsync(
99
+ statement
100
+ .replace(/^CREATE TABLE /i, 'CREATE TABLE IF NOT EXISTS ')
101
+ .replace(/^INSERT INTO /i, 'INSERT OR IGNORE INTO '),
102
+ );
103
+ }
104
+
105
+ /** Idempotent DDL and column probes with no history: re-runnable, but neither atomic nor version-aware. */
106
+ const versionlessRunner: SqliteMigrationConformanceAdapter = {
107
+ migrate: async (database, steps) => {
108
+ for (const step of steps) {
109
+ const statements = step.sql
110
+ .split(';')
111
+ .map((statement) => statement.trim())
112
+ .filter(Boolean);
113
+ for (const statement of statements) {
114
+ await runIdempotent(database, statement);
115
+ }
116
+ }
117
+ },
118
+ };
119
+
120
+ async function failedCases(adapter: SqliteMigrationConformanceAdapter): Promise<string[]> {
121
+ const failed: string[] = [];
122
+ for (const testCase of createSqliteMigrationConformanceTests(adapter)) {
123
+ try {
124
+ await testCase.run();
125
+ } catch {
126
+ failed.push(testCase.name);
127
+ }
128
+ }
129
+ return failed;
130
+ }
131
+
132
+ const ROLLBACK_CASE = 'rolls back a failed step completely and applies it after a fix';
133
+ const NEWER_BUILD_CASE = 'refuses a database written by a newer build and leaves it unchanged';
134
+
135
+ describe('createSqliteMigrationConformanceTests', () => {
136
+ describe('with a transactional runner that refuses newer databases', () => {
137
+ for (const testCase of createSqliteMigrationConformanceTests(
138
+ historyRunner({ transactional: true, refusesNewer: true }),
139
+ )) {
140
+ it(testCase.name, testCase.run);
141
+ }
142
+ });
143
+
144
+ it('catches a partially applied step when the runner skips the transaction', async () => {
145
+ await expect(
146
+ failedCases(historyRunner({ transactional: false, refusesNewer: true })),
147
+ ).resolves.toEqual([ROLLBACK_CASE]);
148
+ });
149
+
150
+ it('catches a runner that accepts a database from a newer build', async () => {
151
+ await expect(
152
+ failedCases(historyRunner({ transactional: true, refusesNewer: false })),
153
+ ).resolves.toEqual([NEWER_BUILD_CASE]);
154
+ });
155
+
156
+ it('catches both defects in a runner without version history', async () => {
157
+ await expect(failedCases(versionlessRunner)).resolves.toEqual([
158
+ ROLLBACK_CASE,
159
+ NEWER_BUILD_CASE,
160
+ ]);
161
+ });
162
+
163
+ it('names the failed expectation', async () => {
164
+ const [newerBuild] = createSqliteMigrationConformanceTests(
165
+ historyRunner({ transactional: true, refusesNewer: false }),
166
+ ).filter((testCase) => testCase.name === NEWER_BUILD_CASE);
167
+ await expect(newerBuild?.run()).rejects.toThrow(
168
+ 'SQLite migration conformance failed: an older build accepted a database that a newer build migrated',
169
+ );
170
+ });
171
+ });
@@ -0,0 +1,281 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ import { NodeSqliteDatabase } from './node-sqlite.js';
6
+
7
+ /** One versioned schema change, in the shape most product runners already accept. */
8
+ export interface SqliteMigrationStep {
9
+ readonly version: number;
10
+ readonly name: string;
11
+ readonly sql: string;
12
+ }
13
+
14
+ export interface SqliteMigrationConformanceAdapter {
15
+ /**
16
+ * Runs the product's migration runner over `steps`, the complete list one app build ships,
17
+ * usually by wrapping `database` in the product's own Expo driver. Rejects when the runner
18
+ * fails or refuses the database.
19
+ */
20
+ migrate(database: NodeSqliteDatabase, steps: readonly SqliteMigrationStep[]): Promise<void>;
21
+ }
22
+
23
+ export interface SqliteMigrationConformanceTestCase {
24
+ readonly name: string;
25
+ readonly run: () => Promise<void>;
26
+ }
27
+
28
+ interface NameRow {
29
+ readonly name: string;
30
+ }
31
+
32
+ interface CountRow {
33
+ readonly count: number;
34
+ }
35
+
36
+ const ITEMS_TABLE = 'conformance_items';
37
+ const SETTINGS_TABLE = 'conformance_settings';
38
+ const PARTIAL_TABLE = 'conformance_partial';
39
+ const RANK_COLUMN = 'rank';
40
+
41
+ const CREATE_ITEMS: SqliteMigrationStep = {
42
+ version: 1,
43
+ name: 'conformance_create_items',
44
+ sql: `CREATE TABLE ${ITEMS_TABLE} (id TEXT PRIMARY KEY NOT NULL, label TEXT NOT NULL);`,
45
+ };
46
+
47
+ const SEED_SETTINGS: SqliteMigrationStep = {
48
+ version: 2,
49
+ name: 'conformance_seed_settings',
50
+ sql: `CREATE TABLE ${SETTINGS_TABLE} (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL);
51
+ INSERT INTO ${SETTINGS_TABLE} (key, value) VALUES ('seeded', 'once');`,
52
+ };
53
+
54
+ const ADD_RANK: SqliteMigrationStep = {
55
+ version: 3,
56
+ name: 'conformance_add_item_rank',
57
+ sql: `ALTER TABLE ${ITEMS_TABLE} ADD COLUMN ${RANK_COLUMN} INTEGER NOT NULL DEFAULT 0;`,
58
+ };
59
+
60
+ const FAILING_ADD_RANK: SqliteMigrationStep = {
61
+ ...ADD_RANK,
62
+ sql: `${ADD_RANK.sql}
63
+ CREATE TABLE ${PARTIAL_TABLE} (id TEXT);
64
+ INSERT INTO conformance_missing_table (id) VALUES ('fails');`,
65
+ };
66
+
67
+ const NEWER_BUILD_STEP: SqliteMigrationStep = {
68
+ version: 4,
69
+ name: 'conformance_newer_build',
70
+ sql: 'CREATE TABLE conformance_newer_build (id TEXT);',
71
+ };
72
+
73
+ const CURRENT_STEPS = [CREATE_ITEMS, SEED_SETTINGS, ADD_RANK] as const;
74
+
75
+ class ConformanceFailure extends Error {
76
+ public constructor(detail: string) {
77
+ super(`SQLite migration conformance failed: ${detail}`);
78
+ this.name = 'ConformanceFailure';
79
+ }
80
+ }
81
+
82
+ function assert(condition: boolean, detail: string): asserts condition {
83
+ if (!condition) {
84
+ throw new ConformanceFailure(detail);
85
+ }
86
+ }
87
+
88
+ /** One database file that a case can close and reopen, removed when the case ends. */
89
+ class ConformanceFile {
90
+ private readonly open = new Set<NodeSqliteDatabase>();
91
+
92
+ public constructor(private readonly path: string) {}
93
+
94
+ public connect(): NodeSqliteDatabase {
95
+ const database = new NodeSqliteDatabase(this.path);
96
+ this.open.add(database);
97
+ return database;
98
+ }
99
+
100
+ public async restart(database: NodeSqliteDatabase): Promise<NodeSqliteDatabase> {
101
+ this.open.delete(database);
102
+ await database.closeAsync();
103
+ return this.connect();
104
+ }
105
+
106
+ public async closeAll(): Promise<void> {
107
+ const handles = [...this.open];
108
+ this.open.clear();
109
+ await Promise.allSettled(handles.map((database) => database.closeAsync()));
110
+ }
111
+ }
112
+
113
+ async function withDatabaseFile(run: (file: ConformanceFile) => Promise<void>): Promise<void> {
114
+ const directory = await mkdtemp(join(tmpdir(), 'baukit-sqlite-migrations-'));
115
+ const file = new ConformanceFile(join(directory, 'database.sqlite'));
116
+ try {
117
+ await run(file);
118
+ } finally {
119
+ await file.closeAll();
120
+ await rm(directory, { recursive: true, force: true });
121
+ }
122
+ }
123
+
124
+ async function rejects(operation: () => Promise<void>): Promise<boolean> {
125
+ try {
126
+ await operation();
127
+ return false;
128
+ } catch {
129
+ return true;
130
+ }
131
+ }
132
+
133
+ function quoteIdentifier(name: string): string {
134
+ return `"${name.replaceAll('"', '""')}"`;
135
+ }
136
+
137
+ async function tableNames(database: NodeSqliteDatabase): Promise<Set<string>> {
138
+ const rows = await database.getAllAsync<NameRow>(
139
+ "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",
140
+ );
141
+ return new Set(rows.map((row) => row.name));
142
+ }
143
+
144
+ async function columnNames(database: NodeSqliteDatabase, table: string): Promise<Set<string>> {
145
+ const rows = await database.getAllAsync<NameRow>(
146
+ `SELECT name FROM pragma_table_info(${quoteSqlText(table)})`,
147
+ );
148
+ return new Set(rows.map((row) => row.name));
149
+ }
150
+
151
+ async function rowCount(database: NodeSqliteDatabase, table: string): Promise<number> {
152
+ const row = await database.getFirstAsync<CountRow>(
153
+ `SELECT count(*) AS count FROM ${quoteIdentifier(table)}`,
154
+ );
155
+ return row?.count ?? 0;
156
+ }
157
+
158
+ function quoteSqlText(value: string): string {
159
+ return `'${value.replaceAll("'", "''")}'`;
160
+ }
161
+
162
+ /** Schema objects, `user_version`, and every table's rows, for an unchanged-database check. */
163
+ async function snapshot(database: NodeSqliteDatabase): Promise<string> {
164
+ const objects = await database.getAllAsync<{ readonly type: string; readonly name: string }>(
165
+ 'SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name',
166
+ );
167
+ const userVersion = await database.getFirstAsync('PRAGMA user_version');
168
+ const tables: Record<string, unknown[]> = {};
169
+ for (const object of objects.filter((candidate) => candidate.type === 'table')) {
170
+ tables[object.name] = await database.getAllAsync(
171
+ `SELECT * FROM ${quoteIdentifier(object.name)} ORDER BY rowid`,
172
+ );
173
+ }
174
+ return JSON.stringify({ objects, userVersion, tables });
175
+ }
176
+
177
+ async function assertCurrentSchema(database: NodeSqliteDatabase): Promise<void> {
178
+ const tables = await tableNames(database);
179
+ assert(tables.has(ITEMS_TABLE), `${ITEMS_TABLE} is missing after migration`);
180
+ assert(tables.has(SETTINGS_TABLE), `${SETTINGS_TABLE} is missing after migration`);
181
+ const columns = await columnNames(database, ITEMS_TABLE);
182
+ assert(columns.has(RANK_COLUMN), `${ITEMS_TABLE}.${RANK_COLUMN} is missing after migration`);
183
+ const seeded = await rowCount(database, SETTINGS_TABLE);
184
+ assert(seeded === 1, `step 2 ran ${String(seeded)} times instead of once`);
185
+ }
186
+
187
+ /**
188
+ * Builds framework-neutral cases for a product's SQLite migration runner: fresh install,
189
+ * upgrade, restart, rollback of a failed step, and refusal of a database written by a newer
190
+ * build. Register each case with the test runner's `it`.
191
+ */
192
+ export function createSqliteMigrationConformanceTests(
193
+ adapter: SqliteMigrationConformanceAdapter,
194
+ ): readonly SqliteMigrationConformanceTestCase[] {
195
+ return [
196
+ {
197
+ name: 'applies every step to a fresh database',
198
+ run: () =>
199
+ withDatabaseFile(async (file) => {
200
+ const database = file.connect();
201
+ await adapter.migrate(database, CURRENT_STEPS);
202
+ await assertCurrentSchema(database);
203
+ }),
204
+ },
205
+ {
206
+ name: 'upgrades an older database and keeps its rows',
207
+ run: () =>
208
+ withDatabaseFile(async (file) => {
209
+ let database = file.connect();
210
+ await adapter.migrate(database, [CREATE_ITEMS]);
211
+ await database.runAsync(
212
+ `INSERT INTO ${ITEMS_TABLE} (id, label) VALUES (?, ?)`,
213
+ 'kept',
214
+ 'written before the upgrade',
215
+ );
216
+ database = await file.restart(database);
217
+ await adapter.migrate(database, CURRENT_STEPS);
218
+ await assertCurrentSchema(database);
219
+ const kept = await database.getFirstAsync<{ readonly rank: number }>(
220
+ `SELECT ${RANK_COLUMN} AS rank FROM ${ITEMS_TABLE} WHERE id = ?`,
221
+ 'kept',
222
+ );
223
+ assert(kept?.rank === 0, 'a row written before the upgrade was lost or not defaulted');
224
+ }),
225
+ },
226
+ {
227
+ name: 'applies nothing again after a restart',
228
+ run: () =>
229
+ withDatabaseFile(async (file) => {
230
+ let database = file.connect();
231
+ await adapter.migrate(database, CURRENT_STEPS);
232
+ const before = await snapshot(database);
233
+ database = await file.restart(database);
234
+ await adapter.migrate(database, CURRENT_STEPS);
235
+ await assertCurrentSchema(database);
236
+ assert(
237
+ (await snapshot(database)) === before,
238
+ 'running the same steps again changed the database',
239
+ );
240
+ }),
241
+ },
242
+ {
243
+ name: 'rolls back a failed step completely and applies it after a fix',
244
+ run: () =>
245
+ withDatabaseFile(async (file) => {
246
+ let database = file.connect();
247
+ const failed = await rejects(() =>
248
+ adapter.migrate(database, [CREATE_ITEMS, SEED_SETTINGS, FAILING_ADD_RANK]),
249
+ );
250
+ assert(failed, 'a step whose last statement fails did not reject');
251
+ assert(
252
+ !(await tableNames(database)).has(PARTIAL_TABLE),
253
+ 'a failed step left a table from its earlier statements (partially applied migration)',
254
+ );
255
+ assert(
256
+ !(await columnNames(database, ITEMS_TABLE)).has(RANK_COLUMN),
257
+ 'a failed step left a column from its earlier statements (partially applied migration)',
258
+ );
259
+ database = await file.restart(database);
260
+ await adapter.migrate(database, CURRENT_STEPS);
261
+ await assertCurrentSchema(database);
262
+ }),
263
+ },
264
+ {
265
+ name: 'refuses a database written by a newer build and leaves it unchanged',
266
+ run: () =>
267
+ withDatabaseFile(async (file) => {
268
+ let database = file.connect();
269
+ await adapter.migrate(database, [...CURRENT_STEPS, NEWER_BUILD_STEP]);
270
+ database = await file.restart(database);
271
+ const before = await snapshot(database);
272
+ const refused = await rejects(() => adapter.migrate(database, CURRENT_STEPS));
273
+ assert(refused, 'an older build accepted a database that a newer build migrated');
274
+ assert(
275
+ (await snapshot(database)) === before,
276
+ 'refusing a newer database still changed it',
277
+ );
278
+ }),
279
+ },
280
+ ];
281
+ }