Skip to content

Commit f9f6f5c

Browse files
authored
Merge pull request #110 from malthe/async-dispose-prep-stmt
Add async dispose to prepared statement
2 parents e889223 + a6d9952 commit f9f6f5c

File tree

4 files changed

+18
-11
lines changed

4 files changed

+18
-11
lines changed

CHANGES.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ In next release ...
55
type instead of a value.
66

77
- Add `[Symbol.asyncDispose]` method to support [Explicit Resource
8-
Management](https://github.com/tc39/proposal-explicit-resource-management).
8+
Management](https://github.com/tc39/proposal-explicit-resource-management). This
9+
works on the client object as well as prepared statements.
910

1011
- Add `off` method to disable event listening.
1112

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ When the prepared statement is no longer needed, it should be closed to release
242242
```typescript
243243
await statement.close();
244244
```
245+
With TypeScript 5.2+ it's also possible to use the `await using` construct which automatically closes the statement at the end of the block.
246+
245247

246248
Prepared statements can be used (executed) multiple times, even concurrently.
247249

src/client.ts

+13-10
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export interface Notification {
9696
payload: string;
9797
}
9898

99-
export interface PreparedStatement<T = ResultRecord> {
99+
export interface PreparedStatement<T = ResultRecord> extends AsyncDisposable {
100100
close: (portal?: string) => Promise<void>;
101101
execute: (
102102
values?: any[],
@@ -535,16 +535,19 @@ export class ClientImpl {
535535
const types = this.parameterDescriptionQueue.shift();
536536
this.cleanupQueue.expect(Cleanup.ParameterDescription);
537537

538+
const close = () => {
539+
return new Promise<void>((resolve) => {
540+
this.writer.close(providedNameOrGenerated, 'S');
541+
this.closeHandlerQueue.push(resolve);
542+
this.cleanupQueue.push(Cleanup.Close);
543+
this.writer.flush();
544+
this.send();
545+
});
546+
};
547+
538548
resolve({
539-
close: () => {
540-
return new Promise<void>((resolve) => {
541-
this.writer.close(providedNameOrGenerated, 'S');
542-
this.closeHandlerQueue.push(resolve);
543-
this.cleanupQueue.push(Cleanup.Close);
544-
this.writer.flush();
545-
this.send();
546-
});
547-
},
549+
[Symbol.asyncDispose]: close,
550+
close,
548551
execute: (
549552
values?: any[],
550553
portal?: string,

test/client.test.ts

+1
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,7 @@ describe('Query', () => {
505505
deepEqual(result1, { names: ['i'], rows: [[1]], status: 'SELECT 1' });
506506
const result2 = await stmt.execute([2]);
507507
deepEqual(result2.rows, [[2]]);
508+
deepEqual(stmt.close, stmt[Symbol.asyncDispose]);
508509
await stmt.close();
509510
});
510511

0 commit comments

Comments
 (0)