|
| 1 | +import type { PGlite, QueryOptions, Results, Row, Transaction } from '@electric-sql/pglite'; |
| 2 | +import { entityKind } from '~/entity.ts'; |
| 3 | +import { type Logger, NoopLogger } from '~/logger.ts'; |
| 4 | +import type { PgDialect } from '~/pg-core/dialect.ts'; |
| 5 | +import { PgTransaction } from '~/pg-core/index.ts'; |
| 6 | +import type { SelectedFieldsOrdered } from '~/pg-core/query-builders/select.types.ts'; |
| 7 | +import type { PgTransactionConfig, PreparedQueryConfig, QueryResultHKT } from '~/pg-core/session.ts'; |
| 8 | +import { PgPreparedQuery, PgSession } from '~/pg-core/session.ts'; |
| 9 | +import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; |
| 10 | +import { fillPlaceholders, type Query, sql } from '~/sql/sql.ts'; |
| 11 | +import { type Assume, mapResultRow } from '~/utils.ts'; |
| 12 | + |
| 13 | +import { types } from '@electric-sql/pglite'; |
| 14 | + |
| 15 | +export type PgliteClient = PGlite; |
| 16 | + |
| 17 | +export class PglitePreparedQuery<T extends PreparedQueryConfig> extends PgPreparedQuery<T> { |
| 18 | + static readonly [entityKind]: string = 'PglitePreparedQuery'; |
| 19 | + |
| 20 | + private rawQueryConfig: QueryOptions; |
| 21 | + private queryConfig: QueryOptions; |
| 22 | + |
| 23 | + constructor( |
| 24 | + private client: PgliteClient | Transaction, |
| 25 | + private queryString: string, |
| 26 | + private params: unknown[], |
| 27 | + private logger: Logger, |
| 28 | + private fields: SelectedFieldsOrdered | undefined, |
| 29 | + name: string | undefined, |
| 30 | + private _isResponseInArrayMode: boolean, |
| 31 | + private customResultMapper?: (rows: unknown[][]) => T['execute'], |
| 32 | + ) { |
| 33 | + super({ sql: queryString, params }); |
| 34 | + this.rawQueryConfig = { |
| 35 | + rowMode: 'object', |
| 36 | + parsers: { |
| 37 | + [types.TIMESTAMP]: (value) => value, |
| 38 | + [types.TIMESTAMPTZ]: (value) => value, |
| 39 | + [types.INTERVAL]: (value) => value, |
| 40 | + [types.DATE]: (value) => value, |
| 41 | + }, |
| 42 | + }; |
| 43 | + this.queryConfig = { |
| 44 | + rowMode: 'array', |
| 45 | + parsers: { |
| 46 | + [types.TIMESTAMP]: (value) => value, |
| 47 | + [types.TIMESTAMPTZ]: (value) => value, |
| 48 | + [types.INTERVAL]: (value) => value, |
| 49 | + [types.DATE]: (value) => value, |
| 50 | + }, |
| 51 | + }; |
| 52 | + } |
| 53 | + |
| 54 | + async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> { |
| 55 | + const params = fillPlaceholders(this.params, placeholderValues); |
| 56 | + |
| 57 | + this.logger.logQuery(this.queryString, params); |
| 58 | + |
| 59 | + const { fields, rawQueryConfig, client, queryConfig, joinsNotNullableMap, customResultMapper, queryString } = this; |
| 60 | + |
| 61 | + if (!fields && !customResultMapper) { |
| 62 | + return client.query<any[]>(queryString, params, rawQueryConfig); |
| 63 | + } |
| 64 | + |
| 65 | + const result = await client.query<any[][]>(queryString, params, queryConfig); |
| 66 | + |
| 67 | + return customResultMapper |
| 68 | + ? customResultMapper(result.rows) |
| 69 | + : result.rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap)); |
| 70 | + } |
| 71 | + |
| 72 | + all(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['all']> { |
| 73 | + const params = fillPlaceholders(this.params, placeholderValues); |
| 74 | + this.logger.logQuery(this.queryString, params); |
| 75 | + return this.client.query(this.queryString, params, this.rawQueryConfig).then((result) => result.rows); |
| 76 | + } |
| 77 | + |
| 78 | + /** @internal */ |
| 79 | + isResponseInArrayMode(): boolean { |
| 80 | + return this._isResponseInArrayMode; |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +export interface PgliteSessionOptions { |
| 85 | + logger?: Logger; |
| 86 | +} |
| 87 | + |
| 88 | +export class PgliteSession< |
| 89 | + TFullSchema extends Record<string, unknown>, |
| 90 | + TSchema extends TablesRelationalConfig, |
| 91 | +> extends PgSession<PgliteQueryResultHKT, TFullSchema, TSchema> { |
| 92 | + static readonly [entityKind]: string = 'PgliteSession'; |
| 93 | + |
| 94 | + private logger: Logger; |
| 95 | + |
| 96 | + constructor( |
| 97 | + private client: PgliteClient | Transaction, |
| 98 | + dialect: PgDialect, |
| 99 | + private schema: RelationalSchemaConfig<TSchema> | undefined, |
| 100 | + private options: PgliteSessionOptions = {}, |
| 101 | + ) { |
| 102 | + super(dialect); |
| 103 | + this.logger = options.logger ?? new NoopLogger(); |
| 104 | + } |
| 105 | + |
| 106 | + prepareQuery<T extends PreparedQueryConfig = PreparedQueryConfig>( |
| 107 | + query: Query, |
| 108 | + fields: SelectedFieldsOrdered | undefined, |
| 109 | + name: string | undefined, |
| 110 | + isResponseInArrayMode: boolean, |
| 111 | + customResultMapper?: (rows: unknown[][]) => T['execute'], |
| 112 | + ): PgPreparedQuery<T> { |
| 113 | + return new PglitePreparedQuery( |
| 114 | + this.client, |
| 115 | + query.sql, |
| 116 | + query.params, |
| 117 | + this.logger, |
| 118 | + fields, |
| 119 | + name, |
| 120 | + isResponseInArrayMode, |
| 121 | + customResultMapper, |
| 122 | + ); |
| 123 | + } |
| 124 | + |
| 125 | + override async transaction<T>( |
| 126 | + transaction: (tx: PgliteTransaction<TFullSchema, TSchema>) => Promise<T>, |
| 127 | + config?: PgTransactionConfig | undefined, |
| 128 | + ): Promise<T> { |
| 129 | + return (this.client as PgliteClient).transaction(async (client) => { |
| 130 | + const session = new PgliteSession<TFullSchema, TSchema>( |
| 131 | + client, |
| 132 | + this.dialect, |
| 133 | + this.schema, |
| 134 | + this.options, |
| 135 | + ); |
| 136 | + const tx = new PgliteTransaction(this.dialect, session, this.schema); |
| 137 | + if (config) { |
| 138 | + await tx.setTransaction(config); |
| 139 | + } |
| 140 | + return transaction(tx); |
| 141 | + }) as Promise<T>; |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +export class PgliteTransaction< |
| 146 | + TFullSchema extends Record<string, unknown>, |
| 147 | + TSchema extends TablesRelationalConfig, |
| 148 | +> extends PgTransaction<PgliteQueryResultHKT, TFullSchema, TSchema> { |
| 149 | + static readonly [entityKind]: string = 'PgliteTransaction'; |
| 150 | + |
| 151 | + override async transaction<T>(transaction: (tx: PgliteTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T> { |
| 152 | + const savepointName = `sp${this.nestedIndex + 1}`; |
| 153 | + const tx = new PgliteTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1); |
| 154 | + await tx.execute(sql.raw(`savepoint ${savepointName}`)); |
| 155 | + try { |
| 156 | + const result = await transaction(tx); |
| 157 | + await tx.execute(sql.raw(`release savepoint ${savepointName}`)); |
| 158 | + return result; |
| 159 | + } catch (err) { |
| 160 | + await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`)); |
| 161 | + throw err; |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +export interface PgliteQueryResultHKT extends QueryResultHKT { |
| 167 | + type: Results<Assume<this['row'], Row>>; |
| 168 | +} |
0 commit comments