-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
session.ts
246 lines (207 loc) 路 7.9 KB
/
session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import type { BatchItem } from '~/batch.ts';
import { entityKind } from '~/entity.ts';
import type { Logger } from '~/logger.ts';
import { NoopLogger } from '~/logger.ts';
import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';
import type { PreparedQuery } from '~/session.ts';
import { fillPlaceholders, type Query, sql } from '~/sql/sql.ts';
import type { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts';
import { SQLiteTransaction } from '~/sqlite-core/index.ts';
import type { SelectedFieldsOrdered } from '~/sqlite-core/query-builders/select.types.ts';
import type {
PreparedQueryConfig as PreparedQueryConfigBase,
SQLiteExecuteMethod,
SQLiteTransactionConfig,
} from '~/sqlite-core/session.ts';
import { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';
import { mapResultRow } from '~/utils.ts';
import type { AsyncBatchRemoteCallback, AsyncRemoteCallback, RemoteCallback, SqliteRemoteResult } from './driver.ts';
export interface SQLiteRemoteSessionOptions {
logger?: Logger;
}
export type PreparedQueryConfig = Omit<PreparedQueryConfigBase, 'statement' | 'run'>;
export class SQLiteRemoteSession<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteSession<'async', SqliteRemoteResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'SQLiteRemoteSession';
private logger: Logger;
constructor(
private client: RemoteCallback,
dialect: SQLiteAsyncDialect,
private schema: RelationalSchemaConfig<TSchema> | undefined,
private batchCLient?: AsyncBatchRemoteCallback,
options: SQLiteRemoteSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
}
prepareQuery<T extends Omit<PreparedQueryConfig, 'run'>>(
query: Query,
fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
isResponseInArrayMode: boolean,
customResultMapper?: (rows: unknown[][]) => unknown,
): RemotePreparedQuery<T> {
return new RemotePreparedQuery(
this.client,
query,
this.logger,
fields,
executeMethod,
isResponseInArrayMode,
customResultMapper,
);
}
async batch<T extends BatchItem<'sqlite'>[] | readonly BatchItem<'sqlite'>[]>(queries: T) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: { sql: string; params: any[]; method: 'run' | 'all' | 'values' | 'get' }[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = (preparedQuery as RemotePreparedQuery).getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push({ sql: builtQuery.sql, params: builtQuery.params, method: builtQuery.method });
}
const batchResults = await (this.batchCLient as AsyncBatchRemoteCallback)(builtQueries);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));
}
override async transaction<T>(
transaction: (tx: SQLiteProxyTransaction<TFullSchema, TSchema>) => Promise<T>,
config?: SQLiteTransactionConfig,
): Promise<T> {
const tx = new SQLiteProxyTransaction('async', this.dialect, this, this.schema);
await this.run(sql.raw(`begin${config?.behavior ? ' ' + config.behavior : ''}`));
try {
const result = await transaction(tx);
await this.run(sql`commit`);
return result;
} catch (err) {
await this.run(sql`rollback`);
throw err;
}
}
override extractRawAllValueFromBatchResult(result: unknown): unknown {
return (result as SqliteRemoteResult).rows;
}
override extractRawGetValueFromBatchResult(result: unknown): unknown {
return (result as SqliteRemoteResult).rows![0];
}
override extractRawValuesValueFromBatchResult(result: unknown): unknown {
return (result as SqliteRemoteResult).rows;
}
}
export class SQLiteProxyTransaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteTransaction<'async', SqliteRemoteResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'SQLiteProxyTransaction';
override async transaction<T>(
transaction: (tx: SQLiteProxyTransaction<TFullSchema, TSchema>) => Promise<T>,
): Promise<T> {
const savepointName = `sp${this.nestedIndex}`;
const tx = new SQLiteProxyTransaction('async', this.dialect, this.session, this.schema, this.nestedIndex + 1);
await this.session.run(sql.raw(`savepoint ${savepointName}`));
try {
const result = await transaction(tx);
await this.session.run(sql.raw(`release savepoint ${savepointName}`));
return result;
} catch (err) {
await this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
throw err;
}
}
}
export class RemotePreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends SQLitePreparedQuery<
{ type: 'async'; run: SqliteRemoteResult; all: T['all']; get: T['get']; values: T['values']; execute: T['execute'] }
> {
static readonly [entityKind]: string = 'SQLiteProxyPreparedQuery';
private method: SQLiteExecuteMethod;
constructor(
private client: RemoteCallback,
query: Query,
private logger: Logger,
private fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
private _isResponseInArrayMode: boolean,
/** @internal */ public customResultMapper?: (
rows: unknown[][],
mapColumnValue?: (value: unknown) => unknown,
) => unknown,
) {
super('async', executeMethod, query);
this.customResultMapper = customResultMapper;
this.method = executeMethod;
}
override getQuery(): Query & { method: SQLiteExecuteMethod } {
return { ...this.query, method: this.method };
}
run(placeholderValues?: Record<string, unknown>): Promise<SqliteRemoteResult> {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return (this.client as AsyncRemoteCallback)(this.query.sql, params, 'run') as Promise<
SqliteRemoteResult
>;
}
override mapAllResult(rows: unknown, isFromBatch?: boolean): unknown {
if (isFromBatch) {
rows = (rows as SqliteRemoteResult).rows;
}
if (!this.fields && !this.customResultMapper) {
return rows;
}
if (this.customResultMapper) {
return this.customResultMapper(rows as unknown[][]) as T['all'];
}
return (rows as unknown[][]).map((row) => {
return mapResultRow(
this.fields!,
row,
this.joinsNotNullableMap,
);
});
}
async all(placeholderValues?: Record<string, unknown>): Promise<T['all']> {
const { query, logger, client } = this;
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
const { rows } = await (client as AsyncRemoteCallback)(query.sql, params, 'all');
return this.mapAllResult(rows);
}
async get(placeholderValues?: Record<string, unknown>): Promise<T['get']> {
const { query, logger, client } = this;
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
const clientResult = await (client as AsyncRemoteCallback)(query.sql, params, 'get');
return this.mapGetResult(clientResult.rows);
}
override mapGetResult(rows: unknown, isFromBatch?: boolean): unknown {
if (isFromBatch) {
rows = (rows as SqliteRemoteResult).rows;
}
const row = rows as unknown[];
if (!this.fields && !this.customResultMapper) {
return row;
}
if (!row) {
return undefined;
}
if (this.customResultMapper) {
return this.customResultMapper([rows] as unknown[][]) as T['get'];
}
return mapResultRow(
this.fields!,
row,
this.joinsNotNullableMap,
);
}
async values<T extends any[] = unknown[]>(placeholderValues?: Record<string, unknown>): Promise<T[]> {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
const clientResult = await (this.client as AsyncRemoteCallback)(this.query.sql, params, 'values');
return clientResult.rows as T[];
}
/** @internal */
isResponseInArrayMode(): boolean {
return this._isResponseInArrayMode;
}
}