-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
AbstractSqlConnection.ts
248 lines (192 loc) · 7.45 KB
/
AbstractSqlConnection.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
247
248
import type { Knex } from 'knex';
import { knex } from 'knex';
import { readFile } from 'fs-extra';
import type {
AnyEntity, Configuration, ConnectionOptions, EntityData, IsolationLevel, LoggerContext, QueryResult,
Transaction, TransactionEventBroadcaster } from '@mikro-orm/core';
import { Connection, EventType, Utils,
} from '@mikro-orm/core';
import type { AbstractSqlPlatform } from './AbstractSqlPlatform';
import { MonkeyPatchable } from './MonkeyPatchable';
const parentTransactionSymbol = Symbol('parentTransaction');
function isRootTransaction<T>(trx: Transaction<T>) {
return !Object.getOwnPropertySymbols(trx).includes(parentTransactionSymbol);
}
export abstract class AbstractSqlConnection extends Connection {
private static __patched = false;
protected override platform!: AbstractSqlPlatform;
protected client!: Knex;
constructor(config: Configuration, options?: ConnectionOptions, type?: 'read' | 'write') {
super(config, options, type);
this.patchKnexClient();
}
abstract createKnex(): void;
/** @inheritDoc */
connect(): void | Promise<void> {
this.createKnex();
}
getKnex(): Knex {
if (!this.client) {
this.createKnex();
}
return this.client;
}
override async close(force?: boolean): Promise<void> {
await super.close(force);
await this.getKnex().destroy();
}
async isConnected(): Promise<boolean> {
try {
await this.getKnex().raw('select 1');
return true;
} catch {
return false;
}
}
override async transactional<T>(cb: (trx: Transaction<Knex.Transaction>) => Promise<T>, options: { isolationLevel?: IsolationLevel; ctx?: Knex.Transaction; eventBroadcaster?: TransactionEventBroadcaster } = {}): Promise<T> {
const trx = await this.begin(options);
try {
const ret = await cb(trx);
await this.commit(trx, options.eventBroadcaster);
return ret;
} catch (error) {
await this.rollback(trx, options.eventBroadcaster);
throw error;
}
}
override async begin(options: { isolationLevel?: IsolationLevel; ctx?: Knex.Transaction; eventBroadcaster?: TransactionEventBroadcaster } = {}): Promise<Knex.Transaction> {
if (!options.ctx) {
await options.eventBroadcaster?.dispatchEvent(EventType.beforeTransactionStart);
}
const trx = await (options.ctx || this.getKnex()).transaction(null, { isolationLevel: options.isolationLevel });
if (!options.ctx) {
await options.eventBroadcaster?.dispatchEvent(EventType.afterTransactionStart, trx);
} else {
trx[parentTransactionSymbol as unknown as keyof Knex.Transaction] = options.ctx;
}
return trx;
}
override async commit(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void> {
const runTrxHooks = isRootTransaction(ctx);
if (runTrxHooks) {
await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionCommit, ctx);
}
ctx.commit();
await ctx.executionPromise; // https://github.com/knex/knex/issues/3847#issuecomment-626330453
if (runTrxHooks) {
await eventBroadcaster?.dispatchEvent(EventType.afterTransactionCommit, ctx);
}
}
override async rollback(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void> {
const runTrxHooks = isRootTransaction(ctx);
if (runTrxHooks) {
await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionRollback, ctx);
}
await ctx.rollback();
if (runTrxHooks) {
await eventBroadcaster?.dispatchEvent(EventType.afterTransactionRollback, ctx);
}
}
async execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params: unknown[] = [], method: 'all' | 'get' | 'run' = 'all', ctx?: Transaction, loggerContext?: LoggerContext): Promise<T> {
await this.ensureConnection();
if (Utils.isObject<Knex.QueryBuilder | Knex.Raw>(queryOrKnex)) {
ctx ??= ((queryOrKnex as any).client.transacting ? queryOrKnex : null);
const q = queryOrKnex.toSQL();
queryOrKnex = q.sql;
params = q.bindings as any[];
}
const formatted = this.platform.formatQuery(queryOrKnex, params);
const sql = this.getSql(queryOrKnex, formatted);
const res = await this.executeQuery<any>(sql, () => {
const query = this.getKnex().raw(formatted);
if (ctx) {
query.transacting(ctx);
}
return query;
}, { query: queryOrKnex, params, ...loggerContext });
return this.transformRawResult<T>(res, method);
}
/**
* Execute raw SQL queries from file
*/
async loadFile(path: string): Promise<void> {
const buf = await readFile(path);
await this.getKnex().raw(buf.toString());
}
protected createKnexClient(type: string): Knex {
const driverOptions = this.config.get('driverOptions');
if (driverOptions.context?.client instanceof knex.Client) {
this.logger.log('info', 'Reusing knex client provided via `driverOptions`');
return driverOptions as Knex;
}
return knex<any, any>(this.getKnexOptions(type))
.on('query', data => {
if (!data.__knexQueryUid) {
this.logQuery(data.sql.toLowerCase().replace(/;$/, ''));
}
});
}
protected getKnexOptions(type: string): Knex.Config {
const config = Utils.merge({
client: type,
connection: this.getConnectionOptions(),
pool: this.config.get('pool'),
}, this.config.get('driverOptions'));
const options = config.connection as ConnectionOptions;
const password = options.password;
if (!(password instanceof Function)) {
return config;
}
config.connection = async () => {
const pw = await password();
if (typeof pw === 'string') {
return { ...options, password: pw };
}
return {
...options,
password: pw.password,
expirationChecker: pw.expirationChecker,
};
};
return config;
}
private getSql(query: string, formatted: string): string {
const logger = this.config.getLogger();
if (!logger.isEnabled('query')) {
return query;
}
if (logger.isEnabled('query-params')) {
return formatted;
}
return this.getKnex().client.positionBindings(query);
}
/**
* do not call `positionBindings` when there are no bindings - it was messing up with
* already interpolated strings containing `?`, and escaping that was not enough to
* support edge cases like `\\?` strings (as `positionBindings` was removing the `\\`)
*/
private patchKnexClient(): void {
const { Client, TableCompiler } = MonkeyPatchable;
const query = Client.prototype.query;
if (AbstractSqlConnection.__patched) {
return;
}
AbstractSqlConnection.__patched = true;
Client.prototype.query = function (this: any, connection: any, obj: any) {
if (typeof obj === 'string') {
obj = { sql: obj };
}
if ((obj.bindings ?? []).length > 0) {
return query.call(this, connection, obj);
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const { __knexUid, __knexTxId } = connection;
this.emit('query', Object.assign({ __knexUid, __knexTxId }, obj));
return MonkeyPatchable.QueryExecutioner.executeQuery(connection, obj, this);
};
TableCompiler.prototype.raw = function (this: any, query: string) {
this.pushQuery(query);
};
}
protected abstract transformRawResult<T>(res: any, method: 'all' | 'get' | 'run'): T;
}