| 22 | const PRIVATE_RELEASE_METHOD: unique symbol = Symbol() |
| 23 | |
| 24 | export class PostgresDriver implements Driver { |
| 25 | readonly #config: PostgresDialectConfig |
| 26 | readonly #connections = new WeakMap<PostgresPoolClient, DatabaseConnection>() |
| 27 | #pool?: PostgresPool |
| 28 | |
| 29 | constructor(config: PostgresDialectConfig) { |
| 30 | this.#config = freeze({ ...config }) |
| 31 | } |
| 32 | |
| 33 | async init(options?: AbortableOperationOptions): Promise<void> { |
| 34 | this.#pool = isFunction(this.#config.pool) |
| 35 | ? await this.#config.pool(options) |
| 36 | : this.#config.pool |
| 37 | } |
| 38 | |
| 39 | async acquireConnection( |
| 40 | options?: AbortableOperationOptions, |
| 41 | ): Promise<DatabaseConnection> { |
| 42 | const client = await this.#pool!.connect() |
| 43 | |
| 44 | let connection = this.#connections.get(client) |
| 45 | |
| 46 | if (!connection) { |
| 47 | connection = new PostgresConnection(client, { |
| 48 | controlClient: this.#config.controlClient || this.#pool!.Client, |
| 49 | cursor: this.#config.cursor ?? null, |
| 50 | poolOptions: this.#pool!.options, |
| 51 | }) |
| 52 | this.#connections.set(client, connection) |
| 53 | |
| 54 | // The driver must take care of calling `onCreateConnection` when a new |
| 55 | // connection is created. The `pg` module doesn't provide an async hook |
| 56 | // for the connection creation. We need to call the method explicitly. |
| 57 | if (this.#config.onCreateConnection) { |
| 58 | await this.#config.onCreateConnection(connection, options) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | if (this.#config.onReserveConnection) { |
| 63 | await this.#config.onReserveConnection(connection, options) |
| 64 | } |
| 65 | |
| 66 | return connection |
| 67 | } |
| 68 | |
| 69 | async beginTransaction( |
| 70 | connection: DatabaseConnection, |
| 71 | settings: TransactionSettings, |
| 72 | ): Promise<void> { |
| 73 | let sql = 'begin' |
| 74 | |
| 75 | if (settings.isolationLevel || settings.accessMode) { |
| 76 | sql = 'start transaction' |
| 77 | |
| 78 | if (settings.isolationLevel) { |
| 79 | sql += ` isolation level ${settings.isolationLevel}` |
| 80 | } |
| 81 |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…