Skip to content

Commit 5c976f1

Browse files
cjihrigaduh95
authored andcommittedMar 23, 2025
sqlite: add DatabaseSync.prototype[Symbol.dispose]()
This commit adds support for the explicit resource management proposal to the sqlite module. Refs: #53752 (comment) PR-URL: #57506 Reviewed-By: Zeyu "Alex" Yang <himself65@outlook.com> Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Edy Silva <edigleyssonsilva@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com> Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
1 parent fda56b9 commit 5c976f1

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed
 

‎doc/api/sqlite.md

+11
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,17 @@ targetDb.applyChangeset(changeset);
281281
// Now that the changeset has been applied, targetDb contains the same data as sourceDb.
282282
```
283283

284+
### `database[Symbol.dispose]()`
285+
286+
<!-- YAML
287+
added: REPLACEME
288+
-->
289+
290+
> Stability: 1 - Experimental
291+
292+
Closes the database connection. If the database connection is already closed
293+
then this is a no-op.
294+
284295
## Class: `Session`
285296

286297
<!-- YAML

‎lib/sqlite.js

+15-1
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;
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)
Please sign in to comment.