|
| 1 | +import { |
| 2 | + CompiledQuery, |
| 3 | + DatabaseConnection, |
| 4 | + QueryResult, |
| 5 | + ReservedSql, |
| 6 | + TransactionSettings, |
| 7 | +} from "../deps.ts"; |
| 8 | +import { PostgresJSDialectError } from "./errors.ts"; |
| 9 | + |
| 10 | +export class PostgresJSConnection implements DatabaseConnection { |
| 11 | + #reservedConnection: ReservedSql; |
| 12 | + |
| 13 | + constructor(reservedConnection: ReservedSql) { |
| 14 | + this.#reservedConnection = reservedConnection; |
| 15 | + } |
| 16 | + |
| 17 | + async beginTransaction(settings: TransactionSettings): Promise<void> { |
| 18 | + const { isolationLevel } = settings; |
| 19 | + |
| 20 | + const compiledQuery = CompiledQuery.raw( |
| 21 | + isolationLevel |
| 22 | + ? `start transaction isolation level ${isolationLevel}` |
| 23 | + : "begin", |
| 24 | + ); |
| 25 | + |
| 26 | + await this.executeQuery(compiledQuery); |
| 27 | + } |
| 28 | + |
| 29 | + async commitTransaction(): Promise<void> { |
| 30 | + await this.executeQuery(CompiledQuery.raw("commit")); |
| 31 | + } |
| 32 | + |
| 33 | + async executeQuery<R>( |
| 34 | + compiledQuery: CompiledQuery<unknown>, |
| 35 | + ): Promise<QueryResult<R>> { |
| 36 | + const result = await this.#reservedConnection.unsafe<R[]>( |
| 37 | + compiledQuery.sql, |
| 38 | + // deno-lint-ignore no-explicit-any |
| 39 | + compiledQuery.parameters.slice() as any, |
| 40 | + ); |
| 41 | + |
| 42 | + const rows = Array.from(result.values()); |
| 43 | + |
| 44 | + if (["INSERT", "UPDATE", "DELETE"].includes(result.command)) { |
| 45 | + const numAffectedRows = BigInt(result.count); |
| 46 | + |
| 47 | + return { numAffectedRows, rows }; |
| 48 | + } |
| 49 | + |
| 50 | + return { rows }; |
| 51 | + } |
| 52 | + |
| 53 | + releaseConnection(): void { |
| 54 | + this.#reservedConnection.release(); |
| 55 | + |
| 56 | + this.#reservedConnection = null!; |
| 57 | + } |
| 58 | + |
| 59 | + async rollbackTransaction(): Promise<void> { |
| 60 | + await this.executeQuery(CompiledQuery.raw("rollback")); |
| 61 | + } |
| 62 | + |
| 63 | + async *streamQuery<R>( |
| 64 | + compiledQuery: CompiledQuery<unknown>, |
| 65 | + chunkSize: number, |
| 66 | + ): AsyncIterableIterator<QueryResult<R>> { |
| 67 | + if (!Number.isInteger(chunkSize) || chunkSize <= 0) { |
| 68 | + throw new PostgresJSDialectError("chunkSize must be a positive integer"); |
| 69 | + } |
| 70 | + |
| 71 | + const cursor = this.#reservedConnection |
| 72 | + // deno-lint-ignore no-explicit-any |
| 73 | + .unsafe<R[]>(compiledQuery.sql, compiledQuery.parameters.slice() as any) |
| 74 | + .cursor(chunkSize); |
| 75 | + |
| 76 | + for await (const rows of cursor) { |
| 77 | + yield { rows }; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments