Skip to content

Commit

Permalink
await using kysely = new Kysely() support. (#1167)
Browse files Browse the repository at this point in the history
  • Loading branch information
igalklebanov authored Oct 19, 2024
1 parent 477f8c5 commit 66c0e57
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/kysely.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ import {
provideControlledConnection,
} from './util/provide-controlled-connection.js'

// @ts-ignore
Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose')

/**
* The main Kysely class.
*
Expand Down Expand Up @@ -87,7 +90,7 @@ import {
*/
export class Kysely<DB>
extends QueryCreator<DB>
implements QueryExecutorProvider
implements QueryExecutorProvider, AsyncDisposable
{
readonly #props: KyselyProps

Expand Down Expand Up @@ -509,6 +512,10 @@ export class Kysely<DB>

return this.getExecutor().executeQuery<R>(compiledQuery, queryId)
}

async [Symbol.asyncDispose]() {
await this.destroy()
}
}

export class Transaction<DB> extends Kysely<DB> {
Expand Down
65 changes: 65 additions & 0 deletions test/node/src/async-dispose.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
CompiledQuery,
DatabaseConnection,
DummyDriver,
Kysely,
PostgresAdapter,
PostgresIntrospector,
PostgresQueryCompiler,
QueryResult,
RootOperationNode,
sql,
} from '../../..'
import { expect } from './test-setup'

describe('async dispose', function () {
it('should call destroy ', async () => {
const steps: string[] = []

{
await using db = new Kysely({
dialect: {
createAdapter: () => new PostgresAdapter(),
createDriver: () =>
new (class extends DummyDriver {
async acquireConnection() {
return new (class implements DatabaseConnection {
async executeQuery<R>(): Promise<QueryResult<R>> {
steps.push('executed')
return { rows: [] }
}
streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
throw new Error('Method not implemented.')
}
})()
}
async destroy(): Promise<void> {
steps.push('destroyed')
}
})(),
createIntrospector: (db) => new PostgresIntrospector(db),
createQueryCompiler: () =>
new (class extends PostgresQueryCompiler {
compileQuery(node: RootOperationNode): CompiledQuery<unknown> {
const compiled = super.compileQuery(node)
steps.push('compiled')
return compiled
}
})(),
},
})

await sql`select 1`.execute(db)
}

steps.push('after runScope')

expect(steps).to.length.to.be.greaterThan(1)
expect(steps).to.deep.equal([
'compiled',
'executed',
'destroyed',
'after runScope',
])
})
})
2 changes: 2 additions & 0 deletions test/node/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"extends": "../../tsconfig-base.json",
"include": ["src/**/*"],
"compilerOptions": {
"target": "ES2022",
"lib": ["ESNext"],
"module": "CommonJS",
"outDir": "dist"
}
Expand Down

0 comments on commit 66c0e57

Please sign in to comment.