-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
session.ts
172 lines (149 loc) 路 5.66 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
import type { OPSQLiteConnection, QueryResult } from '@op-engineering/op-sqlite';
import { entityKind } from '~/entity.ts';
import type { Logger } from '~/logger.ts';
import { NoopLogger } from '~/logger.ts';
import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.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,
type SQLiteExecuteMethod,
SQLitePreparedQuery,
SQLiteSession,
type SQLiteTransactionConfig,
} from '~/sqlite-core/session.ts';
import { mapResultRow } from '~/utils.ts';
export interface OPSQLiteSessionOptions {
logger?: Logger;
}
type PreparedQueryConfig = Omit<PreparedQueryConfigBase, 'statement' | 'run'>;
export class OPSQLiteSession<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteSession<'async', QueryResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'OPSQLiteSession';
private logger: Logger;
constructor(
private client: OPSQLiteConnection,
dialect: SQLiteAsyncDialect,
private schema: RelationalSchemaConfig<TSchema> | undefined,
options: OPSQLiteSessionOptions = {},
) {
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,
): OPSQLitePreparedQuery<T> {
return new OPSQLitePreparedQuery(
this.client,
query,
this.logger,
fields,
executeMethod,
isResponseInArrayMode,
customResultMapper,
);
}
override transaction<T>(
transaction: (tx: OPSQLiteTransaction<TFullSchema, TSchema>) => T,
config: SQLiteTransactionConfig = {},
): T {
const tx = new OPSQLiteTransaction('async', this.dialect, this, this.schema);
this.run(sql.raw(`begin${config?.behavior ? ' ' + config.behavior : ''}`));
try {
const result = transaction(tx);
this.run(sql`commit`);
return result;
} catch (err) {
this.run(sql`rollback`);
throw err;
}
}
}
export class OPSQLiteTransaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteTransaction<'async', QueryResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'OPSQLiteTransaction';
override transaction<T>(transaction: (tx: OPSQLiteTransaction<TFullSchema, TSchema>) => T): T {
const savepointName = `sp${this.nestedIndex}`;
const tx = new OPSQLiteTransaction('async', this.dialect, this.session, this.schema, this.nestedIndex + 1);
this.session.run(sql.raw(`savepoint ${savepointName}`));
try {
const result = transaction(tx);
this.session.run(sql.raw(`release savepoint ${savepointName}`));
return result;
} catch (err) {
this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
throw err;
}
}
}
export class OPSQLitePreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends SQLitePreparedQuery<
{ type: 'async'; run: QueryResult; all: T['all']; get: T['get']; values: T['values']; execute: T['execute'] }
> {
static readonly [entityKind]: string = 'OPSQLitePreparedQuery';
constructor(
private client: OPSQLiteConnection,
query: Query,
private logger: Logger,
private fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
private _isResponseInArrayMode: boolean,
private customResultMapper?: (rows: unknown[][]) => unknown,
) {
super('sync', executeMethod, query);
}
run(placeholderValues?: Record<string, unknown>): Promise<QueryResult> {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return this.client.executeAsync(this.query.sql, params);
}
async all(placeholderValues?: Record<string, unknown>): Promise<T['all']> {
const { fields, joinsNotNullableMap, query, logger, customResultMapper, client } = this;
if (!fields && !customResultMapper) {
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
return client.execute(query.sql, params).rows?._array || [];
}
const rows = await this.values(placeholderValues) as unknown[][];
if (customResultMapper) {
return customResultMapper(rows) as T['all'];
}
return rows.map((row) => mapResultRow(fields!, row, joinsNotNullableMap));
}
async get(placeholderValues?: Record<string, unknown>): Promise<T['get']> {
const { fields, joinsNotNullableMap, customResultMapper, query, logger, client } = this;
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
if (!fields && !customResultMapper) {
const rows = client.execute(query.sql, params).rows?._array || [];
return rows[0];
}
const rows = await this.values(placeholderValues) as unknown[][];
const row = rows[0];
if (!row) {
return undefined;
}
if (customResultMapper) {
return customResultMapper(rows) as T['get'];
}
return mapResultRow(fields!, row, joinsNotNullableMap);
}
values(placeholderValues?: Record<string, unknown>): Promise<T['values']> {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return this.client.executeRawAsync(this.query.sql, params);
}
/** @internal */
isResponseInArrayMode(): boolean {
return this._isResponseInArrayMode;
}
}