Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7ad0b19

Browse files
committedMar 25, 2020
unsafe: add test case which covers inserting data while iterating over the same table
1 parent 808dd6e commit 7ad0b19

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
 

‎test/44.unsafe.mode.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'use strict'
2+
const Database = require('../.');
3+
4+
// writing to a table while reading the same table within an iterator.
5+
function writeWhileIterating(db) {
6+
// create table & prepared statements
7+
db.prepare(`CREATE TABLE test (a TEXT)`).run();
8+
const stmt = {
9+
insert: db.prepare(`INSERT INTO test VALUES (?)`),
10+
each: db.prepare(`SELECT * FROM test WHERE a == 'FOO'`)
11+
};
12+
13+
// populate table with two FOO values
14+
stmt.insert.run('FOO');
15+
stmt.insert.run('FOO');
16+
17+
// iterate and insert from/to the same table at the same time
18+
// note: we insert 'BAR' which is not matched by the iterator.
19+
// warning: this is unsafe, if you insert 'FOO' here then the
20+
// database connection will hang forever, you were warned!
21+
for (let _ of stmt.each.iterate()) {
22+
stmt.insert.run('BAR');
23+
}
24+
};
25+
26+
describe('unsafe mode', () => {
27+
afterEach(() => {
28+
if (this.db) this.db.close();
29+
});
30+
31+
it('disabled: writeWhileIterating', () => {
32+
this.db = new Database(util.next(), { unsafe: false });
33+
expect(this.db.unsafe).to.be.false;
34+
expect(() => {
35+
writeWhileIterating(this.db);
36+
}).to.throw(TypeError);
37+
});
38+
it('enabled: writeWhileIterating', () => {
39+
this.db = new Database(util.next(), { unsafe: true });
40+
expect(this.db.unsafe).to.be.true;
41+
expect(() => {
42+
writeWhileIterating(this.db);
43+
}).not.throw();
44+
const aggs = this.db.prepare(`SELECT a, COUNT(a) AS total FROM test GROUP BY a`).all();
45+
expect(aggs).to.eql([
46+
{ a: 'BAR', total: 2 }, // two 'BAR' rows
47+
{ a: 'FOO', total: 2 } // two 'FOO' rows
48+
]);
49+
});
50+
});

0 commit comments

Comments
 (0)
Please sign in to comment.