diff --git a/README.md b/README.md index 2d71e96..fb7941c 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,24 @@ function inflate(field, value) { } ``` +#### Experimental: `useSharedConnection` + +As of version 1.3.0, `PlanetScaleDialect` supports using a shared `@planetscale/database` connection for all non-transaction queries, to improve query performance. This option is not enabled by default, but can be enabled by setting the `useSharedConnection` option to `true`. Transaction queries will always run using their own connection. + +This is an experimental feature, and may be removed in a future version. + +```typescript +import {Kysely} from 'kysely' +import {PlanetScaleDialect} from 'kysely-planetscale' + +const db = new Kysely({ + dialect: new PlanetScaleDialect({ + url: process.env.DATABASE_URL, + useSharedConnection: true, + }), +}) +``` + ## License MIT License, see `LICENSE`. diff --git a/src/index.ts b/src/index.ts index fa8a7bd..d7a6a92 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,14 @@ import { * * @see https://github.com/planetscale/database-js#usage */ -export interface PlanetScaleDialectConfig extends Config {} +export interface PlanetScaleDialectConfig extends Config { + /** + * Use a single `@planetscale/database` connection for all non-transaction queries. + * + * @default false + */ + useSharedConnection?: boolean +} /** * PlanetScale dialect that uses the [PlanetScale Serverless Driver for JavaScript][0]. @@ -99,14 +106,19 @@ class PlanetScaleDriver implements Driver { async destroy(): Promise {} } +const sharedConnections = new WeakMap() + class PlanetScaleConnection implements DatabaseConnection { #config: PlanetScaleDialectConfig #conn: Connection #transactionClient?: PlanetScaleConnection - constructor(config: PlanetScaleDialectConfig) { + constructor(config: PlanetScaleDialectConfig, isForTransaction = false) { this.#config = config - this.#conn = connect({cast: inflateDates, ...config}) + const useSharedConnection = config.useSharedConnection && !isForTransaction + const sharedConnection = useSharedConnection ? sharedConnections.get(config) : undefined + this.#conn = sharedConnection ?? connect({cast: inflateDates, ...config}) + if (useSharedConnection) sharedConnections.set(config, this.#conn) } async executeQuery(compiledQuery: CompiledQuery): Promise> { @@ -138,7 +150,7 @@ class PlanetScaleConnection implements DatabaseConnection { } async beginTransaction() { - this.#transactionClient = this.#transactionClient ?? new PlanetScaleConnection(this.#config) + this.#transactionClient = this.#transactionClient ?? new PlanetScaleConnection(this.#config, true) await this.#transactionClient.#conn.execute('BEGIN') }