-
-
Notifications
You must be signed in to change notification settings - Fork 35.3k
Expand file tree
/
Copy pathtest-sqlite-backup.mjs
More file actions
358 lines (288 loc) Β· 9.57 KB
/
test-sqlite-backup.mjs
File metadata and controls
358 lines (288 loc) Β· 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
309
310
311
312
313
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
import { isWindows, skipIfSQLiteMissing } from '../common/index.mjs';
import tmpdir from '../common/tmpdir.js';
import { join } from 'node:path';
import { describe, test } from 'node:test';
import { writeFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
skipIfSQLiteMissing();
const { backup, DatabaseSync } = await import('node:sqlite');
const isRoot = !isWindows && process.getuid() === 0;
let cnt = 0;
tmpdir.refresh();
function nextDb() {
return join(tmpdir.path, `database-${cnt++}.db`);
}
function makeSourceDb(dbPath = ':memory:') {
const database = new DatabaseSync(dbPath);
database.exec(`
CREATE TABLE data(
key INTEGER PRIMARY KEY,
value TEXT
) STRICT
`);
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
for (let i = 1; i <= 2; i++) {
insert.run(i, `value-${i}`);
}
return database;
}
describe('backup()', () => {
test('throws if the source database is not provided', (t) => {
t.assert.throws(() => {
backup();
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "sourceDb" argument must be an object.'
});
});
test('throws if path is not a string, URL, or Buffer', (t) => {
const database = makeSourceDb();
t.assert.throws(() => {
backup(database);
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "path" argument must be a string, Uint8Array, or URL without null bytes.'
});
t.assert.throws(() => {
backup(database, {});
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "path" argument must be a string, Uint8Array, or URL without null bytes.'
});
});
test('throws if the database path contains null bytes', (t) => {
const database = makeSourceDb();
t.assert.throws(() => {
backup(database, Buffer.from('l\0cation'));
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "path" argument must be a string, Uint8Array, or URL without null bytes.'
});
t.assert.throws(() => {
backup(database, 'l\0cation');
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "path" argument must be a string, Uint8Array, or URL without null bytes.'
});
});
test('throws if options is not an object', (t) => {
const database = makeSourceDb();
t.assert.throws(() => {
backup(database, 'hello.db', 'invalid');
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options" argument must be an object.'
});
});
test('throws if any of provided options is invalid', (t) => {
const database = makeSourceDb();
t.assert.throws(() => {
backup(database, 'hello.db', {
source: 42
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options.source" argument must be a string.'
});
t.assert.throws(() => {
backup(database, 'hello.db', {
target: 42
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options.target" argument must be a string.'
});
t.assert.throws(() => {
backup(database, 'hello.db', {
rate: 'invalid'
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options.rate" argument must be an integer.'
});
t.assert.throws(() => {
backup(database, 'hello.db', {
progress: 'invalid'
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options.progress" argument must be a function.'
});
});
});
test('database backup', async (t) => {
const progressFn = t.mock.fn();
const database = makeSourceDb();
const destDb = nextDb();
await backup(database, destDb, {
rate: 1,
progress: progressFn,
});
const backupDb = new DatabaseSync(destDb);
const rows = backupDb.prepare('SELECT * FROM data').all();
// The source database has two pages - using the default page size -,
// so the progress function should be called once (the last call is not made since
// the promise resolves)
t.assert.strictEqual(progressFn.mock.calls.length, 1);
t.assert.deepStrictEqual(progressFn.mock.calls[0].arguments, [{ totalPages: 2, remainingPages: 1 }]);
t.assert.deepStrictEqual(rows, [
{ __proto__: null, key: 1, value: 'value-1' },
{ __proto__: null, key: 2, value: 'value-2' },
]);
t.after(() => {
database.close();
backupDb.close();
});
});
test('backup database using location as URL', async (t) => {
const database = makeSourceDb();
const destDb = pathToFileURL(nextDb());
t.after(() => { database.close(); });
await backup(database, destDb);
const backupDb = new DatabaseSync(destDb);
t.after(() => { backupDb.close(); });
const rows = backupDb.prepare('SELECT * FROM data').all();
t.assert.deepStrictEqual(rows, [
{ __proto__: null, key: 1, value: 'value-1' },
{ __proto__: null, key: 2, value: 'value-2' },
]);
});
test('backup database using location as Buffer', async (t) => {
const database = makeSourceDb();
const destDb = Buffer.from(nextDb());
t.after(() => { database.close(); });
await backup(database, destDb);
const backupDb = new DatabaseSync(destDb);
t.after(() => { backupDb.close(); });
const rows = backupDb.prepare('SELECT * FROM data').all();
t.assert.deepStrictEqual(rows, [
{ __proto__: null, key: 1, value: 'value-1' },
{ __proto__: null, key: 2, value: 'value-2' },
]);
});
test('database backup in a single call', async (t) => {
const progressFn = t.mock.fn();
const database = makeSourceDb();
const destDb = nextDb();
// Let rate to be default (100) to backup in a single call
await backup(database, destDb, {
progress: progressFn,
});
const backupDb = new DatabaseSync(destDb);
const rows = backupDb.prepare('SELECT * FROM data').all();
t.assert.strictEqual(progressFn.mock.calls.length, 0);
t.assert.deepStrictEqual(rows, [
{ __proto__: null, key: 1, value: 'value-1' },
{ __proto__: null, key: 2, value: 'value-2' },
]);
t.after(() => {
database.close();
backupDb.close();
});
});
test('throws exception when trying to start backup from a closed database', (t) => {
t.assert.throws(() => {
const database = new DatabaseSync(':memory:');
database.close();
backup(database, 'backup.db');
}, {
code: 'ERR_INVALID_STATE',
message: 'database is not open'
});
});
test('throws if URL is not file: scheme', (t) => {
const database = new DatabaseSync(':memory:');
t.after(() => { database.close(); });
t.assert.throws(() => {
backup(database, new URL('http://example.com/backup.db'));
}, {
code: 'ERR_INVALID_URL_SCHEME',
message: 'The URL must be of scheme file:',
});
});
test('database backup fails when dest file is not writable', { skip: isRoot }, async (t) => {
const readonlyDestDb = nextDb();
writeFileSync(readonlyDestDb, '', { mode: 0o444 });
const database = makeSourceDb();
await t.assert.rejects(async () => {
await backup(database, readonlyDestDb);
}, {
code: 'ERR_SQLITE_ERROR',
message: 'attempt to write a readonly database'
});
});
test('backup fails when progress function throws', async (t) => {
const database = makeSourceDb();
const destDb = nextDb();
const progressFn = t.mock.fn(() => {
throw new Error('progress error');
});
await t.assert.rejects(async () => {
await backup(database, destDb, {
rate: 1,
progress: progressFn,
});
}, {
message: 'progress error'
});
});
test('backup fails when source db is invalid', async (t) => {
const database = makeSourceDb();
const destDb = nextDb();
await t.assert.rejects(async () => {
await backup(database, destDb, {
rate: 1,
source: 'invalid',
});
}, {
message: 'unknown database invalid'
});
});
test('backup fails when path cannot be opened', async (t) => {
const database = makeSourceDb();
await t.assert.rejects(async () => {
await backup(database, `${tmpdir.path}/invalid/backup.db`);
}, {
message: 'unable to open database file'
});
});
test('backup has correct name and length', (t) => {
t.assert.strictEqual(backup.name, 'backup');
t.assert.strictEqual(backup.length, 2);
});
test('source database is kept alive while a backup is in flight', async (t) => {
// Regression test: previously, BackupJob stored a raw DatabaseSync* and the
// source could be garbage-collected while the backup was still running,
// leading to a use-after-free when BackupJob::Finalize() dereferenced the
// stale pointer via source_->RemoveBackup(this).
const destDb = nextDb();
let database = makeSourceDb();
// Insert enough rows to ensure the backup takes multiple steps.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
for (let i = 3; i <= 500; i++) {
insert.run(i, 'A'.repeat(1024) + i);
}
const p = backup(database, destDb, {
rate: 1,
progress() {},
});
// Drop the last strong JS reference to the source database. With the bug,
// the DatabaseSync could be collected here and the in-flight backup would
// later crash while accessing the freed source.
database = null;
// Nudge the GC aggressively, but the backup must keep the source alive
// regardless. Without the fix, the source DatabaseSync would be collected
// and BackupJob::Finalize() would crash the process.
if (typeof global.gc === 'function') {
for (let i = 0; i < 5; i++) {
global.gc();
await new Promise((resolve) => setImmediate(resolve));
}
}
const totalPages = await p;
t.assert.ok(totalPages > 0);
const backupDb = new DatabaseSync(destDb);
t.after(() => { backupDb.close(); });
const rows = backupDb.prepare('SELECT COUNT(*) AS n FROM data').get();
t.assert.strictEqual(rows.n, 500);
});