|
| 1 | +import type { Database, Primitive } from 'db0'; |
| 2 | +import { type Cache, NoopCache } from '~/cache/core/cache.ts'; |
| 3 | +import type { WithCacheConfig } from '~/cache/core/types.ts'; |
| 4 | +import { entityKind } from '~/entity.ts'; |
| 5 | +import type { Logger } from '~/logger.ts'; |
| 6 | +import { NoopLogger } from '~/logger.ts'; |
| 7 | +import type { PgDialect } from '~/pg-core/dialect.ts'; |
| 8 | +import { PgTransaction } from '~/pg-core/index.ts'; |
| 9 | +import type { SelectedFieldsOrdered } from '~/pg-core/query-builders/select.types.ts'; |
| 10 | +import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from '~/pg-core/session.ts'; |
| 11 | +import { PgPreparedQuery, PgSession } from '~/pg-core/session.ts'; |
| 12 | +import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; |
| 13 | +import { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts'; |
| 14 | +import { mapResultRow } from '~/utils.ts'; |
| 15 | + |
| 16 | +export interface Db0PgSessionOptions { |
| 17 | + logger?: Logger; |
| 18 | + cache?: Cache; |
| 19 | +} |
| 20 | + |
| 21 | +export interface Db0PgQueryResult { |
| 22 | + rows: unknown[]; |
| 23 | + rowCount: number; |
| 24 | +} |
| 25 | + |
| 26 | +export class Db0PgPreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends PgPreparedQuery<T> { |
| 27 | + static override readonly [entityKind]: string = 'Db0PgPreparedQuery'; |
| 28 | + |
| 29 | + constructor( |
| 30 | + private client: Database, |
| 31 | + private queryString: string, |
| 32 | + private params: unknown[], |
| 33 | + private logger: Logger, |
| 34 | + cache: Cache, |
| 35 | + queryMetadata: { type: 'select' | 'update' | 'delete' | 'insert'; tables: string[] } | undefined, |
| 36 | + cacheConfig: WithCacheConfig | undefined, |
| 37 | + private fields: SelectedFieldsOrdered | undefined, |
| 38 | + name: string | undefined, |
| 39 | + private _isResponseInArrayMode: boolean, |
| 40 | + private customResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => T['execute'], |
| 41 | + ) { |
| 42 | + super({ sql: queryString, params }, cache, queryMetadata, cacheConfig); |
| 43 | + } |
| 44 | + |
| 45 | + async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> { |
| 46 | + const params = fillPlaceholders(this.params, placeholderValues) as Primitive[]; |
| 47 | + this.logger.logQuery(this.queryString, params); |
| 48 | + |
| 49 | + const { fields, client, customResultMapper, queryString, joinsNotNullableMap } = this; |
| 50 | + |
| 51 | + if (!fields && !customResultMapper) { |
| 52 | + return await this.queryWithCache(queryString, params, async () => { |
| 53 | + const stmt = client.prepare(queryString); |
| 54 | + const rows = await stmt.all(...params) as unknown[]; |
| 55 | + return { rows, rowCount: rows.length } as T['execute']; |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + // db0 doesn't have array mode, so we get objects and convert to arrays |
| 60 | + return await this.queryWithCache(queryString, params, async () => { |
| 61 | + const stmt = client.prepare(queryString); |
| 62 | + const rows = await stmt.all(...params) as Record<string, unknown>[]; |
| 63 | + const arrayRows = rows.map((row) => Object.values(row)); |
| 64 | + |
| 65 | + if (customResultMapper) { |
| 66 | + return customResultMapper(arrayRows); |
| 67 | + } |
| 68 | + |
| 69 | + return arrayRows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap)); |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + async all(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['all']> { |
| 74 | + const params = fillPlaceholders(this.params, placeholderValues) as Primitive[]; |
| 75 | + this.logger.logQuery(this.queryString, params); |
| 76 | + return await this.queryWithCache(this.queryString, params, async () => { |
| 77 | + const stmt = this.client.prepare(this.queryString); |
| 78 | + return stmt.all(...params) as Promise<T['all']>; |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + /** @internal */ |
| 83 | + isResponseInArrayMode(): boolean { |
| 84 | + return this._isResponseInArrayMode; |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +export class Db0PgSession< |
| 89 | + TFullSchema extends Record<string, unknown>, |
| 90 | + TSchema extends TablesRelationalConfig, |
| 91 | +> extends PgSession<Db0PgQueryResultHKT, TFullSchema, TSchema> { |
| 92 | + static override readonly [entityKind]: string = 'Db0PgSession'; |
| 93 | + |
| 94 | + private logger: Logger; |
| 95 | + private cache: Cache; |
| 96 | + |
| 97 | + constructor( |
| 98 | + private client: Database, |
| 99 | + dialect: PgDialect, |
| 100 | + private schema: RelationalSchemaConfig<TSchema> | undefined, |
| 101 | + private options: Db0PgSessionOptions = {}, |
| 102 | + ) { |
| 103 | + super(dialect); |
| 104 | + this.logger = options.logger ?? new NoopLogger(); |
| 105 | + this.cache = options.cache ?? new NoopCache(); |
| 106 | + } |
| 107 | + |
| 108 | + prepareQuery<T extends PreparedQueryConfig = PreparedQueryConfig>( |
| 109 | + query: Query, |
| 110 | + fields: SelectedFieldsOrdered | undefined, |
| 111 | + name: string | undefined, |
| 112 | + isResponseInArrayMode: boolean, |
| 113 | + customResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => T['execute'], |
| 114 | + queryMetadata?: { type: 'select' | 'update' | 'delete' | 'insert'; tables: string[] }, |
| 115 | + cacheConfig?: WithCacheConfig, |
| 116 | + ): PgPreparedQuery<T> { |
| 117 | + return new Db0PgPreparedQuery( |
| 118 | + this.client, |
| 119 | + query.sql, |
| 120 | + query.params, |
| 121 | + this.logger, |
| 122 | + this.cache, |
| 123 | + queryMetadata, |
| 124 | + cacheConfig, |
| 125 | + fields, |
| 126 | + name, |
| 127 | + isResponseInArrayMode, |
| 128 | + customResultMapper, |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + override async transaction<T>( |
| 133 | + transaction: (tx: Db0PgTransaction<TFullSchema, TSchema>) => Promise<T>, |
| 134 | + config?: PgTransactionConfig, |
| 135 | + ): Promise<T> { |
| 136 | + const tx = new Db0PgTransaction<TFullSchema, TSchema>(this.dialect, this, this.schema); |
| 137 | + |
| 138 | + let beginSql = 'begin'; |
| 139 | + if (config) { |
| 140 | + const chunks: string[] = []; |
| 141 | + if (config.isolationLevel) { |
| 142 | + chunks.push(`isolation level ${config.isolationLevel}`); |
| 143 | + } |
| 144 | + if (config.accessMode) { |
| 145 | + chunks.push(config.accessMode); |
| 146 | + } |
| 147 | + if (typeof config.deferrable === 'boolean') { |
| 148 | + chunks.push(config.deferrable ? 'deferrable' : 'not deferrable'); |
| 149 | + } |
| 150 | + if (chunks.length > 0) { |
| 151 | + beginSql = `begin ${chunks.join(' ')}`; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + await this.execute(sql.raw(beginSql)); |
| 156 | + try { |
| 157 | + const result = await transaction(tx); |
| 158 | + await this.execute(sql`commit`); |
| 159 | + return result; |
| 160 | + } catch (err) { |
| 161 | + await this.execute(sql`rollback`); |
| 162 | + throw err; |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + override async count(countSql: SQL): Promise<number> { |
| 167 | + const res = await this.execute<Db0PgQueryResult>(countSql); |
| 168 | + return Number((res.rows[0] as Record<string, unknown>)['count']); |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +export class Db0PgTransaction< |
| 173 | + TFullSchema extends Record<string, unknown>, |
| 174 | + TSchema extends TablesRelationalConfig, |
| 175 | +> extends PgTransaction<Db0PgQueryResultHKT, TFullSchema, TSchema> { |
| 176 | + static override readonly [entityKind]: string = 'Db0PgTransaction'; |
| 177 | + |
| 178 | + override async transaction<T>( |
| 179 | + transaction: (tx: Db0PgTransaction<TFullSchema, TSchema>) => Promise<T>, |
| 180 | + ): Promise<T> { |
| 181 | + const savepointName = `sp${this.nestedIndex + 1}`; |
| 182 | + const tx = new Db0PgTransaction<TFullSchema, TSchema>(this.dialect, this.session, this.schema, this.nestedIndex + 1); |
| 183 | + await tx.execute(sql.raw(`savepoint ${savepointName}`)); |
| 184 | + try { |
| 185 | + const result = await transaction(tx); |
| 186 | + await tx.execute(sql.raw(`release savepoint ${savepointName}`)); |
| 187 | + return result; |
| 188 | + } catch (err) { |
| 189 | + await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`)); |
| 190 | + throw err; |
| 191 | + } |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +export interface Db0PgQueryResultHKT extends PgQueryResultHKT { |
| 196 | + type: Db0PgQueryResult; |
| 197 | +} |
0 commit comments