-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
DatabaseDriver.ts
412 lines (328 loc) · 15.2 KB
/
DatabaseDriver.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import type {
CountOptions,
DeleteOptions,
DriverMethodOptions,
FindOneOptions,
FindOptions,
IDatabaseDriver,
LockOptions,
NativeInsertUpdateManyOptions,
NativeInsertUpdateOptions,
OrderDefinition,
} from './IDatabaseDriver';
import { EntityManagerType } from './IDatabaseDriver';
import type {
ConnectionType,
Dictionary,
EntityData,
EntityDictionary,
EntityKey,
EntityMetadata,
EntityProperty,
FilterObject,
FilterQuery,
PopulateOptions,
Primary,
} from '../typings';
import type { MetadataStorage } from '../metadata';
import type { Connection, QueryResult, Transaction } from '../connections';
import type { Configuration, ConnectionOptions } from '../utils';
import { Cursor, EntityComparator, Utils } from '../utils';
import type { QueryOrderKeys, QueryOrderMap } from '../enums';
import { QueryOrder, QueryOrderNumeric, ReferenceKind } from '../enums';
import type { Platform } from '../platforms';
import type { Collection } from '../entity/Collection';
import { EntityManager } from '../EntityManager';
import { ValidationError } from '../errors';
import { DriverException } from '../exceptions';
import { helper } from '../entity/wrap';
export abstract class DatabaseDriver<C extends Connection> implements IDatabaseDriver<C> {
[EntityManagerType]!: EntityManager<this>;
protected readonly connection!: C;
protected readonly replicas: C[] = [];
protected readonly platform!: Platform;
protected readonly logger = this.config.getLogger();
protected comparator!: EntityComparator;
protected metadata!: MetadataStorage;
protected constructor(readonly config: Configuration,
protected readonly dependencies: string[]) { }
async init(): Promise<void> {
// do nothing on this level
}
abstract find<T extends object, P extends string = never, F extends string = '*'>(entityName: string, where: FilterQuery<T>, options?: FindOptions<T, P, F>): Promise<EntityData<T>[]>;
abstract findOne<T extends object, P extends string = never, F extends string = '*'>(entityName: string, where: FilterQuery<T>, options?: FindOneOptions<T, P, F>): Promise<EntityData<T> | null>;
abstract nativeInsert<T extends object>(entityName: string, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
abstract nativeInsertMany<T extends object>(entityName: string, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
abstract nativeUpdate<T extends object>(entityName: string, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
async nativeUpdateMany<T extends object>(entityName: string, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>> {
throw new Error(`Batch updates are not supported by ${this.constructor.name} driver`);
}
abstract nativeDelete<T extends object>(entityName: string, where: FilterQuery<T>, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
abstract count<T extends object, P extends string = never>(entityName: string, where: FilterQuery<T>, options?: CountOptions<T, P>): Promise<number>;
createEntityManager<D extends IDatabaseDriver = IDatabaseDriver>(useContext?: boolean): D[typeof EntityManagerType] {
return new EntityManager(this.config, this, this.metadata, useContext) as unknown as EntityManager<D>;
}
/* istanbul ignore next */
async findVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: FindOptions<T, any, any>): Promise<EntityData<T>[]> {
throw new Error(`Virtual entities are not supported by ${this.constructor.name} driver.`);
}
/* istanbul ignore next */
async countVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: CountOptions<T>): Promise<number> {
throw new Error(`Counting virtual entities is not supported by ${this.constructor.name} driver.`);
}
async aggregate(entityName: string, pipeline: any[]): Promise<any[]> {
throw new Error(`Aggregations are not supported by ${this.constructor.name} driver`);
}
async loadFromPivotTable<T extends object, O extends object>(prop: EntityProperty, owners: Primary<O>[][], where?: FilterQuery<any>, orderBy?: OrderDefinition<T>, ctx?: Transaction, options?: FindOptions<T, any, any>): Promise<Dictionary<T[]>> {
throw new Error(`${this.constructor.name} does not use pivot tables`);
}
async syncCollection<T extends object, O extends object>(coll: Collection<T, O>, options?: DriverMethodOptions): Promise<void> {
const pk = coll.property.targetMeta!.primaryKeys[0];
const data = { [coll.property.name]: coll.getIdentifiers(pk) } as EntityData<T>;
await this.nativeUpdate<T>(coll.owner.constructor.name, helper(coll.owner).getPrimaryKey() as FilterQuery<T>, data, options);
}
mapResult<T extends object>(result: EntityDictionary<T>, meta?: EntityMetadata<T>, populate: PopulateOptions<T>[] = []): EntityData<T> | null {
if (!result || !meta) {
return result ?? null;
}
return this.comparator.mapResult<T>(meta.className, result);
}
async connect(): Promise<C> {
await this.connection.connect();
await Promise.all(this.replicas.map(replica => replica.connect()));
return this.connection;
}
async reconnect(): Promise<C> {
await this.close(true);
await this.connect();
await this.init();
return this.connection;
}
getConnection(type: ConnectionType = 'write'): C {
if (type === 'write' || this.replicas.length === 0) {
return this.connection as C;
}
const rand = Utils.randomInt(0, this.replicas.length - 1);
return this.replicas[rand] as C;
}
async close(force?: boolean): Promise<void> {
await Promise.all(this.replicas.map(replica => replica.close(force)));
await this.connection.close(force);
}
getPlatform(): Platform {
return this.platform;
}
setMetadata(metadata: MetadataStorage): void {
this.metadata = metadata;
this.comparator = new EntityComparator(this.metadata, this.platform);
this.connection.setMetadata(metadata);
this.connection.setPlatform(this.platform);
this.replicas.forEach(replica => {
replica.setMetadata(metadata);
replica.setPlatform(this.platform);
});
}
getMetadata(): MetadataStorage {
return this.metadata;
}
getDependencies(): string[] {
return this.dependencies;
}
protected processCursorOptions<T extends object, P extends string>(meta: EntityMetadata<T>, options: FindOptions<T, P, any>, orderBy: OrderDefinition<T>): { orderBy: OrderDefinition<T>[]; where: FilterQuery<T> } {
const { first, last, before, after, overfetch } = options;
const limit = first || last;
const isLast = !first && !!last;
const definition = Cursor.getDefinition(meta, orderBy);
const $and: FilterQuery<T>[] = [];
// allow POJO as well, we care only about the correct key being present
const isCursor = (val: unknown, key: 'startCursor' | 'endCursor'): val is Cursor<T, any> => {
return !!val && typeof val === 'object' && key in val;
};
const createCursor = (val: unknown, key: 'startCursor' | 'endCursor', inverse = false) => {
let def = isCursor(val, key) ? val[key] : val;
if (Utils.isPlainObject<FilterObject<T>>(def)) {
def = Cursor.for<T>(meta, def, orderBy);
}
const offsets = def ? Cursor.decode(def as string) as Dictionary[] : [];
if (definition.length === offsets.length) {
return this.createCursorCondition<T>(definition, offsets, inverse);
}
return {} as FilterQuery<T>;
};
if (after) {
$and.push(createCursor(after, 'endCursor'));
}
if (before) {
$and.push(createCursor(before, 'startCursor', true));
}
if (limit) {
options.limit = limit + (overfetch ? 1 : 0);
}
const createOrderBy = (prop: string, direction: QueryOrderKeys<T>): OrderDefinition<T> => {
if (Utils.isPlainObject(direction)) {
const value = Utils.keys(direction).reduce((o, key) => {
Object.assign(o, createOrderBy(key as string, direction[key] as QueryOrderKeys<T>));
return o;
}, {});
return ({ [prop]: value }) as OrderDefinition<T>;
}
const desc = direction as unknown === QueryOrderNumeric.DESC || direction.toString().toLowerCase() === 'desc';
const dir = Utils.xor(desc, isLast) ? 'desc' : 'asc';
return ({ [prop]: dir }) as OrderDefinition<T>;
};
return {
orderBy: definition.map(([prop, direction]) => createOrderBy(prop, direction)),
where: ($and.length > 1 ? { $and } : { ...$and[0] }) as FilterQuery<T>,
};
}
protected createCursorCondition<T extends object>(definition: (readonly [keyof T & string, QueryOrder])[], offsets: Dictionary[], inverse = false): FilterQuery<T> {
const createCondition = (prop: string, direction: QueryOrderKeys<T>, offset: Dictionary, eq = false) => {
if (Utils.isPlainObject(direction)) {
const value = Utils.keys(direction).reduce((o, key) => {
Object.assign(o, createCondition(key as string, direction[key] as QueryOrderKeys<T>, offset[prop][key], eq));
return o;
}, {});
return ({ [prop]: value });
}
const desc = direction as unknown === QueryOrderNumeric.DESC || direction.toString().toLowerCase() === 'desc';
const operator = Utils.xor(desc, inverse) ? '$lt' : '$gt';
return { [prop]: { [operator + (eq ? 'e' : '')]: offset } } as FilterQuery<T>;
};
const [order, ...otherOrders] = definition;
const [offset, ...otherOffsets] = offsets;
const [prop, direction] = order;
if (!otherOrders.length) {
return createCondition(prop, direction, offset) as FilterQuery<T>;
}
return {
...createCondition(prop, direction, offset, true),
$or: [
createCondition(prop, direction, offset),
this.createCursorCondition(otherOrders, otherOffsets, inverse),
],
} as FilterQuery<T>;
}
protected inlineEmbeddables<T extends object>(meta: EntityMetadata<T>, data: T, where?: boolean): void {
Utils.keys(data).forEach(k => {
if (Utils.isOperator(k as string)) {
Utils.asArray(data[k]).forEach(payload => this.inlineEmbeddables(meta, payload as T, where));
}
});
meta.props.forEach(prop => {
if (prop.kind === ReferenceKind.EMBEDDED && prop.object && !where && Utils.isObject(data[prop.name])) {
return;
}
if (prop.kind === ReferenceKind.EMBEDDED && Utils.isObject(data[prop.name])) {
const props = prop.embeddedProps;
let unknownProp = false;
Object.keys(data[prop.name] as Dictionary).forEach(kk => {
// explicitly allow `$exists`, `$eq` and `$ne` operators here as they can't be misused this way
const operator = Object.keys(data[prop.name] as Dictionary).some(f => Utils.isOperator(f) && !['$exists', '$ne', '$eq'].includes(f));
if (operator) {
throw ValidationError.cannotUseOperatorsInsideEmbeddables(meta.name!, prop.name, data);
}
if (prop.object && where) {
const inline: (payload: any, sub: EntityProperty, path: string[]) => void = (payload: any, sub: EntityProperty, path: string[]) => {
if (sub.kind === ReferenceKind.EMBEDDED && Utils.isObject(payload[sub.embedded![1]])) {
return Object.keys(payload[sub.embedded![1]]).forEach(kkk => {
if (!sub.embeddedProps[kkk]) {
throw ValidationError.invalidEmbeddableQuery(meta.className, kkk, sub.type);
}
inline(payload[sub.embedded![1]], sub.embeddedProps[kkk], [...path, sub.embedded![1]]);
});
}
data[`${path.join('.')}.${sub.embedded![1]}` as EntityKey<T>] = payload[sub.embedded![1]];
};
// we might be using some native JSON operator, e.g. with mongodb's `$geoWithin` or `$exists`
if (props[kk]) {
inline(data[prop.name], props[kk], [prop.name]);
} else {
unknownProp = true;
}
} else if (props[kk]) {
data[props[kk].name as EntityKey<T>] = data[prop.name][props[kk].embedded![1] as EntityKey<T>] as T[EntityKey<T>];
} else {
throw ValidationError.invalidEmbeddableQuery(meta.className, kk, prop.type);
}
});
if (!unknownProp) {
delete data[prop.name];
}
}
});
}
protected getPivotOrderBy<T>(prop: EntityProperty<T>, orderBy?: OrderDefinition<T>): QueryOrderMap<T>[] {
if (!Utils.isEmpty(orderBy)) {
return orderBy as QueryOrderMap<T>[];
}
if (!Utils.isEmpty(prop.orderBy)) {
return Utils.asArray(prop.orderBy);
}
if (prop.fixedOrder) {
return [{ [`${prop.pivotEntity}.${prop.fixedOrderColumn}`]: QueryOrder.ASC } as QueryOrderMap<T>];
}
return [];
}
protected getPrimaryKeyFields(entityName: string): string[] {
const meta = this.metadata.find(entityName);
return meta ? Utils.flatten(meta.getPrimaryProps().map(pk => pk.fieldNames)) : [this.config.getNamingStrategy().referenceColumnName()];
}
protected getPivotInverseProperty(prop: EntityProperty): EntityProperty {
const pivotMeta = this.metadata.find(prop.pivotEntity)!;
if (prop.owner) {
return pivotMeta.relations[0];
}
return pivotMeta.relations[1];
}
protected createReplicas(cb: (c: ConnectionOptions) => C): C[] {
const replicas = this.config.get('replicas', [])!;
const ret: C[] = [];
const props = ['dbName', 'clientUrl', 'host', 'port', 'user', 'password', 'multipleStatements', 'pool', 'name'] as const;
replicas.forEach((conf: Partial<ConnectionOptions>) => {
props.forEach(prop => (conf[prop] as any) = prop in conf ? conf[prop] : this.config.get(prop));
ret.push(cb(conf as ConnectionOptions));
});
return ret;
}
async lockPessimistic<T extends object>(entity: T, options: LockOptions): Promise<void> {
throw new Error(`Pessimistic locks are not supported by ${this.constructor.name} driver`);
}
/**
* @inheritDoc
*/
convertException(exception: Error): DriverException {
if (exception instanceof DriverException) {
return exception;
}
return this.platform.getExceptionConverter().convertException(exception);
}
protected rethrow<T>(promise: Promise<T>): Promise<T> {
return promise.catch(e => {
throw this.convertException(e);
});
}
/**
* @internal
*/
getTableName<T>(meta: EntityMetadata<T>, options: NativeInsertUpdateManyOptions<T>): string {
const tableName = this.platform.quoteIdentifier(meta.tableName);
const schema = this.getSchemaName(meta, options);
if (schema) {
return this.platform.quoteIdentifier(schema) + '.' + tableName;
}
return tableName;
}
/**
* @internal
*/
getSchemaName(meta?: EntityMetadata, options?: { schema?: string }): string | undefined {
if (meta?.schema && meta.schema !== '*') {
return meta.schema;
}
if (options?.schema === '*') {
return this.config.get('schema');
}
const schemaName = meta?.schema === '*' ? this.config.get('schema') : meta?.schema;
return options?.schema ?? schemaName ?? this.config.get('schema');
}
}