|
| 1 | +import type { Connection, ExecuteOptions, FullResult, Tx } from '@tidbcloud/serverless'; |
| 2 | + |
| 3 | +import { entityKind } from '~/entity.ts'; |
| 4 | +import type { Logger } from '~/logger.ts'; |
| 5 | +import { NoopLogger } from '~/logger.ts'; |
| 6 | +import type { MySqlDialect } from '~/mysql-core/dialect.ts'; |
| 7 | +import type { SelectedFieldsOrdered } from '~/mysql-core/query-builders/select.types.ts'; |
| 8 | +import { |
| 9 | + MySqlSession, |
| 10 | + MySqlTransaction, |
| 11 | + PreparedQuery, |
| 12 | + type PreparedQueryConfig, |
| 13 | + type PreparedQueryHKT, |
| 14 | + type QueryResultHKT, |
| 15 | +} from '~/mysql-core/session.ts'; |
| 16 | +import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; |
| 17 | +import { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts'; |
| 18 | +import { type Assume, mapResultRow } from '~/utils.ts'; |
| 19 | + |
| 20 | +const executeRawConfig = { fullResult: true } satisfies ExecuteOptions; |
| 21 | +const queryConfig = { arrayMode: true } satisfies ExecuteOptions; |
| 22 | + |
| 23 | +export class TiDBServerlessPreparedQuery<T extends PreparedQueryConfig> extends PreparedQuery<T> { |
| 24 | + static readonly [entityKind]: string = 'TiDBPreparedQuery'; |
| 25 | + |
| 26 | + constructor( |
| 27 | + private client: Tx | Connection, |
| 28 | + private queryString: string, |
| 29 | + private params: unknown[], |
| 30 | + private logger: Logger, |
| 31 | + private fields: SelectedFieldsOrdered | undefined, |
| 32 | + private customResultMapper?: (rows: unknown[][]) => T['execute'], |
| 33 | + ) { |
| 34 | + super(); |
| 35 | + } |
| 36 | + |
| 37 | + async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> { |
| 38 | + const params = fillPlaceholders(this.params, placeholderValues); |
| 39 | + |
| 40 | + this.logger.logQuery(this.queryString, params); |
| 41 | + |
| 42 | + const { fields, client, queryString, joinsNotNullableMap, customResultMapper } = this; |
| 43 | + if (!fields && !customResultMapper) { |
| 44 | + return client.execute(queryString, params, executeRawConfig); |
| 45 | + } |
| 46 | + |
| 47 | + const rows = await client.execute(queryString, params, queryConfig) as unknown[][]; |
| 48 | + |
| 49 | + if (customResultMapper) { |
| 50 | + return customResultMapper(rows); |
| 51 | + } |
| 52 | + |
| 53 | + return rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap)); |
| 54 | + } |
| 55 | + |
| 56 | + override iterator(_placeholderValues?: Record<string, unknown>): AsyncGenerator<T['iterator']> { |
| 57 | + throw new Error('Streaming is not supported by the TiDB Cloud Serverless driver'); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export interface TiDBServerlessSessionOptions { |
| 62 | + logger?: Logger; |
| 63 | +} |
| 64 | + |
| 65 | +export class TiDBServerlessSession< |
| 66 | + TFullSchema extends Record<string, unknown>, |
| 67 | + TSchema extends TablesRelationalConfig, |
| 68 | +> extends MySqlSession<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> { |
| 69 | + static readonly [entityKind]: string = 'TiDBServerlessSession'; |
| 70 | + |
| 71 | + private logger: Logger; |
| 72 | + private client: Tx | Connection; |
| 73 | + |
| 74 | + constructor( |
| 75 | + private baseClient: Connection, |
| 76 | + dialect: MySqlDialect, |
| 77 | + tx: Tx | undefined, |
| 78 | + private schema: RelationalSchemaConfig<TSchema> | undefined, |
| 79 | + private options: TiDBServerlessSessionOptions = {}, |
| 80 | + ) { |
| 81 | + super(dialect); |
| 82 | + this.client = tx ?? baseClient; |
| 83 | + this.logger = options.logger ?? new NoopLogger(); |
| 84 | + } |
| 85 | + |
| 86 | + prepareQuery<T extends PreparedQueryConfig = PreparedQueryConfig>( |
| 87 | + query: Query, |
| 88 | + fields: SelectedFieldsOrdered | undefined, |
| 89 | + customResultMapper?: (rows: unknown[][]) => T['execute'], |
| 90 | + ): PreparedQuery<T> { |
| 91 | + return new TiDBServerlessPreparedQuery( |
| 92 | + this.client, |
| 93 | + query.sql, |
| 94 | + query.params, |
| 95 | + this.logger, |
| 96 | + fields, |
| 97 | + customResultMapper, |
| 98 | + ); |
| 99 | + } |
| 100 | + |
| 101 | + override all<T = unknown>(query: SQL): Promise<T[]> { |
| 102 | + const querySql = this.dialect.sqlToQuery(query); |
| 103 | + this.logger.logQuery(querySql.sql, querySql.params); |
| 104 | + return this.client.execute(querySql.sql, querySql.params) as Promise<T[]>; |
| 105 | + } |
| 106 | + |
| 107 | + override async transaction<T>( |
| 108 | + transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>, |
| 109 | + ): Promise<T> { |
| 110 | + const nativeTx = await this.baseClient.begin(); |
| 111 | + try { |
| 112 | + const session = new TiDBServerlessSession(this.baseClient, this.dialect, nativeTx, this.schema, this.options); |
| 113 | + const tx = new TiDBServerlessTransaction<TFullSchema, TSchema>( |
| 114 | + this.dialect, |
| 115 | + session as MySqlSession<any, any, any, any>, |
| 116 | + this.schema, |
| 117 | + ); |
| 118 | + const result = await transaction(tx); |
| 119 | + await nativeTx.commit(); |
| 120 | + return result; |
| 121 | + } catch (err) { |
| 122 | + await nativeTx.rollback(); |
| 123 | + throw err; |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +export class TiDBServerlessTransaction< |
| 129 | + TFullSchema extends Record<string, unknown>, |
| 130 | + TSchema extends TablesRelationalConfig, |
| 131 | +> extends MySqlTransaction<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> { |
| 132 | + static readonly [entityKind]: string = 'TiDBServerlessTransaction'; |
| 133 | + |
| 134 | + constructor( |
| 135 | + dialect: MySqlDialect, |
| 136 | + session: MySqlSession, |
| 137 | + schema: RelationalSchemaConfig<TSchema> | undefined, |
| 138 | + nestedIndex = 0, |
| 139 | + ) { |
| 140 | + super(dialect, session, schema, nestedIndex, 'default'); |
| 141 | + } |
| 142 | + |
| 143 | + override async transaction<T>( |
| 144 | + transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>, |
| 145 | + ): Promise<T> { |
| 146 | + const savepointName = `sp${this.nestedIndex + 1}`; |
| 147 | + const tx = new TiDBServerlessTransaction<TFullSchema, TSchema>( |
| 148 | + this.dialect, |
| 149 | + this.session, |
| 150 | + this.schema, |
| 151 | + this.nestedIndex + 1, |
| 152 | + ); |
| 153 | + await tx.execute(sql.raw(`savepoint ${savepointName}`)); |
| 154 | + try { |
| 155 | + const result = await transaction(tx); |
| 156 | + await tx.execute(sql.raw(`release savepoint ${savepointName}`)); |
| 157 | + return result; |
| 158 | + } catch (err) { |
| 159 | + await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`)); |
| 160 | + throw err; |
| 161 | + } |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +export interface TiDBServerlessQueryResultHKT extends QueryResultHKT { |
| 166 | + type: FullResult; |
| 167 | +} |
| 168 | + |
| 169 | +export interface TiDBServerlessPreparedQueryHKT extends PreparedQueryHKT { |
| 170 | + type: TiDBServerlessPreparedQuery<Assume<this['config'], PreparedQueryConfig>>; |
| 171 | +} |
0 commit comments