Skip to content

Commit 80593b2

Browse files
committed
sqlite: add DatabaseSync.prototype[Symbol.dispose]()
This commit adds support for the explicit resource management proposal to the sqlite module. Refs: nodejs#53752 (comment)
1 parent 824c6a5 commit 80593b2

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

doc/api/sqlite.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,17 @@ targetDb.applyChangeset(changeset);
291291
// Now that the changeset has been applied, targetDb contains the same data as sourceDb.
292292
```
293293

294+
### `database[Symbol.dispose]()`
295+
296+
<!-- YAML
297+
added: REPLACEME
298+
-->
299+
300+
> Stability: 1 - Experimental
301+
302+
Closes the database connection. If the database connection is already closed
303+
then this is a no-op.
304+
294305
## Class: `Session`
295306

296307
<!-- YAML

lib/sqlite.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
11
'use strict';
2+
const {
3+
SymbolDispose,
4+
} = primordials;
25
const { emitExperimentalWarning } = require('internal/util');
6+
const binding = internalBinding('sqlite');
37

48
emitExperimentalWarning('SQLite');
5-
module.exports = internalBinding('sqlite');
9+
10+
// TODO(cjihrig): Move this to C++ once Symbol.dispose reaches Stage 4.
11+
binding.DatabaseSync.prototype[SymbolDispose] = function() {
12+
try {
13+
this.close();
14+
} catch {
15+
// Ignore errors.
16+
}
17+
};
18+
19+
module.exports = binding;
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
require('../common');
3+
const tmpdir = require('../common/tmpdir');
4+
const assert = require('node:assert');
5+
const { join } = require('node:path');
6+
const { DatabaseSync } = require('node:sqlite');
7+
const { suite, test } = require('node:test');
8+
let cnt = 0;
9+
10+
tmpdir.refresh();
11+
12+
function nextDb() {
13+
return join(tmpdir.path, `database-${cnt++}.db`);
14+
}
15+
16+
suite('DatabaseSync.prototype[Symbol.dispose]()', () => {
17+
test('closes an open database', () => {
18+
const db = new DatabaseSync(nextDb());
19+
db[Symbol.dispose]();
20+
assert.throws(() => {
21+
db.close();
22+
}, /database is not open/);
23+
});
24+
25+
test('supports databases that are not open', () => {
26+
const db = new DatabaseSync(nextDb(), { open: false });
27+
db[Symbol.dispose]();
28+
assert.throws(() => {
29+
db.close();
30+
}, /database is not open/);
31+
});
32+
});

0 commit comments

Comments
 (0)