import { type CountOptions, type DeleteOptions, type DriverMethodOptions, EntityManagerType, type FindOneOptions, type FindOptions, type IDatabaseDriver, type LockOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type OrderDefinition, type StreamOptions, } from './IDatabaseDriver.js'; import type { ConnectionType, Constructor, Dictionary, EntityData, EntityDictionary, EntityKey, EntityMetadata, EntityName, EntityProperty, FilterObject, FilterQuery, PopulateOptions, Primary, } from '../typings.js'; import type { MetadataStorage } from '../metadata/MetadataStorage.js'; import type { Connection, QueryResult, Transaction } from '../connections/Connection.js'; import { Utils } from '../utils/Utils.js'; import { type Configuration, type ConnectionOptions } from '../utils/Configuration.js'; import { Cursor } from '../utils/Cursor.js'; import type { EntityComparator } from '../utils/EntityComparator.js'; import { isRaw, raw } from '../utils/RawQueryFragment.js'; import { type QueryOrder, type QueryOrderKeys, QueryOrderNumeric, ReferenceKind } from '../enums.js'; import type { Platform } from '../platforms/Platform.js'; import type { Collection } from '../entity/Collection.js'; import { EntityManager } from '../EntityManager.js'; import { CursorError, ValidationError } from '../errors.js'; import { DriverException } from '../exceptions.js'; import { helper } from '../entity/wrap.js'; import { Reference } from '../entity/Reference.js'; import { PolymorphicRef } from '../entity/PolymorphicRef.js'; import { JsonType } from '../types/JsonType.js'; import { QueryHelper } from '../utils/QueryHelper.js'; import { MikroORM } from '../MikroORM.js'; /** Abstract base class for all database drivers, implementing common driver logic. */ export abstract class DatabaseDriver implements IDatabaseDriver { [EntityManagerType]!: EntityManager; protected readonly connection!: C; protected readonly replicas: C[] = []; protected readonly platform!: Platform; protected comparator!: EntityComparator; protected metadata!: MetadataStorage; protected constructor( readonly config: Configuration, protected readonly dependencies: string[], ) {} abstract find( entityName: EntityName, where: FilterQuery, options?: FindOptions, ): Promise[]>; abstract findOne( entityName: EntityName, where: FilterQuery, options?: FindOneOptions, ): Promise | null>; abstract nativeInsert( entityName: EntityName, data: EntityDictionary, options?: NativeInsertUpdateOptions, ): Promise>; abstract nativeInsertMany( entityName: EntityName, data: EntityDictionary[], options?: NativeInsertUpdateManyOptions, transform?: (sql: string) => string, ): Promise>; abstract nativeUpdate( entityName: EntityName, where: FilterQuery, data: EntityDictionary, options?: NativeInsertUpdateOptions, ): Promise>; async nativeUpdateMany( entityName: EntityName, where: FilterQuery[], data: EntityDictionary[], options?: NativeInsertUpdateManyOptions, ): Promise> { throw new Error(`Batch updates are not supported by ${this.constructor.name} driver`); } abstract nativeDelete( entityName: EntityName, where: FilterQuery, options?: DeleteOptions, ): Promise>; async nativeClone( entityName: EntityName, where: FilterQuery, overrides?: EntityData, options?: NativeInsertUpdateOptions, ): Promise> { throw new Error(`${this.constructor.name} does not support nativeClone`); } abstract count( entityName: EntityName, where: FilterQuery, options?: CountOptions, ): Promise; /** Creates a new EntityManager instance bound to this driver. */ createEntityManager(useContext?: boolean): this[typeof EntityManagerType] { const EntityManagerClass = this.config.get('entityManager', EntityManager); return new EntityManagerClass(this.config, this, this.metadata, useContext); } /* v8 ignore next */ async findVirtual( entityName: EntityName, where: FilterQuery, options: FindOptions, ): Promise[]> { throw new Error(`Virtual entities are not supported by ${this.constructor.name} driver.`); } /* v8 ignore next */ async countVirtual( entityName: EntityName, where: FilterQuery, options: CountOptions, ): Promise { throw new Error(`Counting virtual entities is not supported by ${this.constructor.name} driver.`); } async aggregate(entityName: EntityName, pipeline: any[]): Promise { throw new Error(`Aggregations are not supported by ${this.constructor.name} driver`); } async loadFromPivotTable( prop: EntityProperty, owners: Primary[][], where?: FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, pivotJoin?: boolean, ): Promise> { throw new Error(`${this.constructor.name} does not use pivot tables`); } async syncCollections( collections: Iterable>, options?: DriverMethodOptions, ): Promise { for (const coll of collections) { /* v8 ignore else */ if (!coll.property.owner) { if (coll.getSnapshot() === undefined) { throw ValidationError.cannotModifyInverseCollection(coll.owner, coll.property); } continue; } /* v8 ignore next */ { const pk = coll.property.targetMeta!.primaryKeys[0]; const data = { [coll.property.name]: coll.getIdentifiers(pk) } as EntityData; await this.nativeUpdate( coll.owner.constructor, helper(coll.owner).getPrimaryKey() as FilterQuery, data, options, ); } } } /** Maps raw database result to entity data, converting column names to property names. */ mapResult( result: EntityDictionary, meta?: EntityMetadata, populate: PopulateOptions[] = [], ): EntityData | null { if (!result || !meta) { return result ?? null; } return this.comparator.mapResult(meta, result); } /** Opens the primary connection and all read replicas. */ async connect(options?: { skipOnConnect?: boolean }): Promise { await this.connection.connect(options); await Promise.all(this.replicas.map(replica => replica.connect() as Promise)); return this.connection; } /** Closes all connections and re-establishes them. */ async reconnect(options?: { skipOnConnect?: boolean }): Promise { await this.close(true); await this.connect(options); return this.connection; } /** Returns the write connection or a random read replica. */ getConnection(type: ConnectionType = 'write'): C { if (type === 'write' || this.replicas.length === 0) { return this.connection; } const rand = Utils.randomInt(0, this.replicas.length - 1); return this.replicas[rand]; } /** Closes the primary connection and all read replicas. */ async close(force?: boolean): Promise { await Promise.all(this.replicas.map(replica => replica.close(force))); await this.connection.close(force); } /** Returns the database platform abstraction for this driver. */ getPlatform(): Platform { return this.platform; } /** Sets the metadata storage and initializes the comparator for all connections. */ setMetadata(metadata: MetadataStorage): void { this.metadata = metadata; this.comparator = this.config.getComparator(metadata); this.connection.setMetadata(metadata); this.connection.setPlatform(this.platform); this.replicas.forEach(replica => { replica.setMetadata(metadata); replica.setPlatform(this.platform); }); } /** Returns the metadata storage used by this driver. */ getMetadata(): MetadataStorage { return this.metadata; } /** Returns the names of native database dependencies required by this driver. */ getDependencies(): string[] { return this.dependencies; } protected isPopulated( meta: EntityMetadata, prop: EntityProperty, hint: PopulateOptions, name?: string, ): boolean { if (hint.field === prop.name || hint.field === name || hint.all) { return true; } if (prop.embedded && hint.children && meta.properties[prop.embedded[0]].name === hint.field) { return hint.children.some(c => this.isPopulated(meta, prop, c as PopulateOptions, prop.embedded![1])); } return false; } protected processCursorOptions( meta: EntityMetadata, options: FindOptions, orderBy: OrderDefinition, ): { orderBy: OrderDefinition[]; where: FilterQuery } { const { first, last, before, after, overfetch } = options; const limit = first ?? last; const isLast = !first && !!last; const definition = Cursor.getDefinition(meta, orderBy); const $and: FilterQuery[] = []; // allow POJO as well, we care only about the correct key being present const isCursor = (val: unknown, key: 'startCursor' | 'endCursor'): val is Cursor => { return !!val && typeof val === 'object' && key in val; }; const createCursor = (val: unknown, key: 'startCursor' | 'endCursor', inverse = false) => { const def: unknown = Reference.unwrapReference((isCursor(val, key) ? val[key] : val) as T); let offsets: unknown[]; let fromJson = false; // entity (and reference) instances are supported as cursors too, their properties are read the same way if (Utils.isPlainObject>(def) || Utils.isEntity>(def)) { // POJO values are already JS values, extract them ordered per the definition, // without the JSON round trip `Cursor.for` + `Cursor.decode` would impose offsets = definition.map(([key]) => { if (def[key] === undefined) { throw CursorError.missingValue(meta.className, key as string); } return def[key]; }); } else { try { /* v8 ignore next */ offsets = def ? Cursor.decode(def as string) : []; } catch (error) { throw CursorError.invalidCursor(meta.className, error as Error); } fromJson = true; } if (definition.length > 0 && definition.length === offsets.length) { return this.createCursorCondition(definition, offsets as Dictionary[], inverse, meta, fromJson); } /* v8 ignore next */ return {} as FilterQuery; }; if (after) { $and.push(createCursor(after, 'endCursor')); } if (before) { $and.push(createCursor(before, 'startCursor', true)); } if (limit != null) { options.limit = limit + (overfetch ? 1 : 0); } const createOrderBy = ( prop: string, direction: QueryOrderKeys, properties: Dictionary = meta.properties as Dictionary, ): OrderDefinition => { const propMeta = properties[prop]; if (Utils.isPlainObject(direction)) { const childProps = propMeta?.kind === ReferenceKind.EMBEDDED ? propMeta.embeddedProps : propMeta?.targetMeta?.properties; const value = Utils.getObjectQueryKeys(direction).reduce((o, key) => { Object.assign( o, createOrderBy(key as string, direction[key] as unknown as QueryOrderKeys, childProps ?? {}), ); return o; }, {}); return { [prop]: value } as OrderDefinition; } const { desc, nullsFirst, explicit } = this.parseCursorDirection(direction); const dir = Utils.xor(desc, isLast) ? 'desc' : 'asc'; // only a requested placement is spelled out, an unqualified direction already lands where the // condition expects it; backward pagination reverses the ordering, so the placement flips too if (explicit) { const nulls = Utils.xor(nullsFirst, isLast) ? 'first' : 'last'; return { [prop]: `${dir} nulls ${nulls}` } as OrderDefinition; } return { [prop]: dir } as OrderDefinition; }; // the cursor condition is created at the driver level, after the EM already converted custom types // in the user `where`, so we need to run the same conversion over it explicitly const where = QueryHelper.processWhere({ where: ($and.length > 1 ? { $and } : { ...$and[0] }) as FilterQuery, entityName: meta.class, metadata: this.metadata, platform: this.platform, convertCustomTypes: options.convertCustomTypes, }); return { orderBy: definition.map(([prop, direction]) => createOrderBy(prop, direction)), where, }; } /** * Resolves a leaf `orderBy` direction into the two flags the rewritten `orderBy` and the cursor * condition have to agree on, or pagination skips rows at the null boundary. A placement the caller * asked for wins where the platform can honor it, anything else follows the platform's own default, * which is what the untouched `orderBy` will get. */ private parseCursorDirection(direction: unknown): { desc: boolean; nullsFirst: boolean; explicit: boolean } { const dir = ('' + direction).toLowerCase(); const desc = direction === QueryOrderNumeric.DESC || dir.startsWith('desc'); const nullsFirst = dir.includes('nulls first'); const explicit = (nullsFirst || dir.includes('nulls last')) && this.platform.supportsNullsOrdering(); if (!explicit) { return { desc, nullsFirst: this.platform.sortsNullsLowest() ? !desc : desc, explicit }; } return { desc, nullsFirst, explicit }; } /** * Restores the JS value of a single cursor offset. String-cursor values (`fromJson`) are decoded * JSON: types implementing `fromJSON` own the round trip, other custom types restore via * `convertToJSValue`, with `Date` healing for date-like columns based on the property type (never * based on the string shape alone). POJO values are already JS values and only date-like strings * are healed. Values compared against a JSON document keep their serialized form instead, unless * the platform preserves native date types inside JSON documents (mongo). */ private mapCursorOffset( prop: EntityProperty | undefined, value: unknown, insideJson: boolean, fromJson: boolean, ): unknown { if (Utils.isScalarReference(value)) { value = value.unwrap(); } // scalar direction on a relation orders by its primary key if (Utils.isEntity(value, true)) { value = helper(value).getPrimaryKey(); } if (value == null) { return value; } // mongo preserves native date types inside JSON documents, restored JS values compare directly if (insideJson && !this.platform.preservesDatesInsideJson()) { // compared against the JSON document, which holds the JSON form of the database value if (value instanceof Date) { return value.toISOString(); } if (prop?.customType && fromJson) { const restored = prop.customType.fromJSON ? prop.customType.fromJSON(value, this.platform) : prop.customType.convertToJSValue(value, this.platform); // a restored `Date` compares against its ISO string in the document, everything else // keeps the JS value and gets its single `convertToDatabaseValue` in `processWhere` if (restored instanceof Date) { const converted = prop.customType.convertToDatabaseValue(restored, this.platform, { fromQuery: true, key: prop.name, mode: 'query', }); if (converted instanceof Date) { return converted.toISOString(); } } return restored; } return value; } if (prop?.customType) { if (fromJson && prop.customType.fromJSON) { // the type owns its JSON round trip return prop.customType.fromJSON(value, this.platform); } // A string is either a serialized form (string cursor) or a hand-written one (POJO). // Types whose JS value is a `Date` must receive one. The rest get the string first, // so any sub-millisecond precision survives. if ( typeof value === 'string' && (prop.runtimeType === 'Date' || this.platform.getMappedType(prop.columnTypes?.[0] ?? '').runtimeType === 'Date') ) { if (prop.runtimeType !== 'Date') { try { return prop.customType.convertToJSValue(value, this.platform); } catch { // the type cannot read the serialized string, fall back to the `Date` form } } return prop.customType.convertToJSValue(new Date(value), this.platform); } // serialized non-string values still need restoring; POJO values are already JS values return fromJson ? prop.customType.convertToJSValue(value, this.platform) : value; } if (typeof value === 'string' && prop?.runtimeType === 'Date') { return new Date(value); } return value; } protected createCursorCondition( definition: (readonly [keyof T & string, QueryOrder])[], offsets: Dictionary[], inverse: boolean, meta: EntityMetadata, fromJson = false, ): FilterQuery { const createCondition = ( prop: string, direction: QueryOrderKeys, offset: Dictionary, eq = false, path = prop, properties: Dictionary = meta.properties as Dictionary, insideJson = false, nullable = false, ): Dictionary => { const propMeta = properties[prop]; // nullable relations and embeddables null out their joined columns, and a formula can yield null unannounced nullable ||= !!propMeta?.nullable || !!propMeta?.formula; if (Utils.isPlainObject(direction)) { if (offset === undefined) { throw CursorError.missingValue(meta.className, path); } // POJO cursors can carry entity, reference or embeddable class instances, read their properties directly offset = Reference.unwrapReference(offset); const childProps = propMeta?.kind === ReferenceKind.EMBEDDED ? propMeta.embeddedProps : propMeta?.targetMeta?.properties; insideJson ||= (propMeta?.kind === ReferenceKind.EMBEDDED && !!propMeta.object) || propMeta?.customType instanceof JsonType; const keys = Utils.keys(direction); const child = (key: (typeof keys)[number], childEq: boolean) => createCondition( key, direction[key] as QueryOrderKeys, // a null relation offset means the whole sort key is null, propagate it to the leaves offset === null ? null : offset[key], childEq, `${path}.${key}`, childProps ?? {}, insideJson, nullable, ); // the group's own keys are a keyset in their own right, so they decompose the same way the // top level does; merging them into one object would compare every key independently instead const lex = (index: number): Dictionary => { const key = keys[index]; if (index === keys.length - 1) { return child(key, eq); } const atOrPast = child(key, true); const tail = lex(index + 1); // an unconstrained tail matches anything, leaving only the `at or past` prefix to constrain const past = Utils.hasObjectKeys(tail) ? { $or: [child(key, false), tail] } : {}; if (!Utils.hasObjectKeys(past)) { return atOrPast; } return Utils.hasObjectKeys(atOrPast) ? { $and: [atOrPast, past] } : past; }; const value = keys.length > 0 ? lex(0) : {}; // an unconstrained group condition must not degrade to `{ [prop]: {} }` return Utils.hasObjectKeys(value) ? { [prop]: value } : {}; } const { desc: isDesc, nullsFirst } = this.parseCursorDirection(direction); const operator = Utils.xor(isDesc, inverse) ? '$lt' : '$gt'; // For leaf-level properties, undefined means missing value if (offset === undefined) { throw CursorError.missingValue(meta.className, path); } // string-cursor values are client supplied, so a value the type cannot restore is an // invalid cursor, letting callers map `CursorError` to a client error response try { offset = this.mapCursorOffset(propMeta, offset, insideJson, fromJson) as Dictionary; } catch (error) { if (!fromJson || error instanceof CursorError) { throw error; } throw CursorError.invalidCursor(meta.className, error as Error); } // Handle null offset (intentional null cursor value) if (offset === null) { // hasItemsAfterNull: forward + nullsFirst, or backward + nullsLast const hasItemsAfterNull = Utils.xor(nullsFirst, inverse); if (eq) { // at-or-after a null sort key means every row when non-null rows follow the null block, // so the tie-breaker in the `$or` sibling can reach past it return hasItemsAfterNull ? {} : { [prop]: null }; } // Strict comparison with null cursor value if (hasItemsAfterNull) { return { [prop]: { $ne: null } }; } // No items after null in this direction, return impossible condition return { [prop]: [] } as Dictionary; } // Non-null offset const condition = { [prop]: { [operator + (eq ? 'e' : '')]: offset } }; // null sort keys lie past the offset here, and no comparison ever matches them if (nullable && !Utils.xor(nullsFirst, inverse)) { return { $or: [condition, { [prop]: null }] }; } return condition; }; const [order, ...otherOrders] = definition; const [offset, ...otherOffsets] = offsets; const [prop, direction] = order; if (!otherOrders.length) { return createCondition(prop, direction, offset) as FilterQuery; } const atOrPast = createCondition(prop, direction, offset, true); const past = { $or: [ createCondition(prop, direction, offset), this.createCursorCondition(otherOrders, otherOffsets, inverse, meta, fromJson), ], }; // the `at or past` prefix is itself a group condition when it compares against nulls if ('$or' in atOrPast) { return { $and: [atOrPast, past] } as FilterQuery; } return { ...atOrPast, ...past } as FilterQuery; } /** @internal Polymorphic embeddable variants can declare same-named properties with different field names. */ protected variantProps(prop: EntityProperty, data?: Dictionary): Dictionary { const meta = prop.targetMeta; // eslint-disable-next-line eqeqeq const variant = meta?.polymorphs?.find(m => m.discriminatorValue == data?.[meta.discriminatorColumn!]); const props = variant ? { ...prop.embeddedProps } : prop.embeddedProps; for (const p of variant ? Object.values(props) : []) { if (variant!.properties[p.embedded![1]] && Utils.isSameKind(variant!.properties[p.embedded![1]], p)) { props[p.embedded![1]] = p; } } return props; } /** @internal */ mapDataToFieldNames( data: Dictionary, stringifyJsonArrays: boolean, properties?: Record, convertCustomTypes?: boolean, object?: boolean, ): Dictionary { if (!properties || data == null) { return data; } data = Object.assign({}, data); // copy first Object.keys(data).forEach(k => { const prop = properties[k]; if (!prop) { return; } if (prop.embeddedProps && !prop.object && !object) { const copy = data[k]; delete data[k]; Object.assign( data, this.mapDataToFieldNames(copy, stringifyJsonArrays, this.variantProps(prop, copy), convertCustomTypes), ); return; } if (prop.embeddedProps && (object || prop.object)) { const copy = data[k]; delete data[k]; if (prop.array) { data[prop.fieldNames[0]] = copy?.map((item: Dictionary) => this.mapDataToFieldNames( item, stringifyJsonArrays, this.variantProps(prop, item), convertCustomTypes, true, ), ); } else { data[prop.fieldNames[0]] = this.mapDataToFieldNames( copy, stringifyJsonArrays, this.variantProps(prop, copy), convertCustomTypes, true, ); } if (stringifyJsonArrays && prop.array && !object) { data[prop.fieldNames[0]] = this.platform.convertJsonToDatabaseValue(data[prop.fieldNames[0]]); } return; } // Handle polymorphic relations - convert tuple or PolymorphicRef to separate columns // Tuple format: ['discriminator', id] or ['discriminator', id1, id2] for composite keys // Must be checked BEFORE joinColumns array handling since polymorphic uses fieldNames (includes discriminator) if (prop.polymorphic && prop.fieldNames && prop.fieldNames.length >= 2) { let discriminator: string | undefined; let ids: unknown[]; if (Array.isArray(data[k]) && typeof data[k][0] === 'string' && prop.discriminatorMap?.[data[k][0]]) { // Tuple format: ['discriminator', ...ids] const [disc, ...rest] = data[k]; discriminator = disc; ids = rest; } else if (data[k] instanceof PolymorphicRef) { // PolymorphicRef wrapper (internal use) discriminator = data[k].discriminator; const polyId = data[k].id; // Handle object-style composite key IDs like { tenantId: 1, orgId: 100 } if (polyId && typeof polyId === 'object' && !Array.isArray(polyId)) { const targetEntity = prop.discriminatorMap?.[discriminator]; const targetMeta = this.metadata.get(targetEntity!); ids = targetMeta.primaryKeys.map(pk => (polyId as Record)[pk]); } else { ids = Utils.asArray(polyId); } } if (discriminator) { const discriminatorColumn = prop.fieldNames[0]; const idColumns = prop.fieldNames.slice(1); delete data[k]; data[discriminatorColumn] = discriminator; idColumns.forEach((col, idx) => { data[col] = ids[idx]; }); return; } } if (prop.joinColumns && Array.isArray(data[k])) { const copy = Utils.flatten(data[k]); delete data[k]; (prop.ownColumns ?? prop.joinColumns).forEach(col => (data[col] = copy[prop.joinColumns.indexOf(col)])); return; } if (prop.joinColumns?.length > 1 && data[k] == null) { delete data[k]; prop.ownColumns.forEach(joinColumn => (data[joinColumn] = null)); return; } if ( prop.customType && convertCustomTypes && !(prop.customType instanceof JsonType && object) && !isRaw(data[k]) ) { data[k] = prop.customType.convertToDatabaseValue(data[k], this.platform, { fromQuery: true, key: k, mode: 'query-data', }); } if (prop.hasConvertToDatabaseValueSQL && !prop.object && !isRaw(data[k])) { const quoted = this.platform.quoteValue(data[k]); const sql = prop.customType!.convertToDatabaseValueSQL!(quoted, this.platform); data[k] = raw(sql.replace(/\?/g, '\\?')); } if (prop.fieldNames) { Utils.renameKey(data, k, this.getScalarFieldName(prop)); } }); return data; } protected inlineEmbeddables(meta: EntityMetadata, data: T, where?: boolean): void { /* v8 ignore next */ if (data == null) { return; } 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`, `$ne`, `$elemMatch` and `$all` 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', '$elemMatch', '$all'].includes(f), ); if (operator) { throw ValidationError.cannotUseOperatorsInsideEmbeddables(meta.class, 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.class, kkk, sub.type); } inline(payload[sub.embedded![1]], sub.embeddedProps[kkk], [...path, sub.fieldNames[0]]); }); } data[`${path.join('.')}.${sub.fieldNames[0]}` as EntityKey] = payload[sub.embedded![1]]; }; const parentPropName = kk.substring(0, kk.indexOf('.')); // we might be using some native JSON operator, e.g. with mongodb's `$geoWithin` or `$exists` if (props[kk]) { /* v8 ignore next */ inline(data[prop.name], props[kk] || props[parentPropName], [prop.fieldNames[0]]); } else if (props[parentPropName]) { data[`${prop.fieldNames[0]}.${kk}` as keyof T] = (data[prop.name] as Dictionary)[kk]; } else { unknownProp = true; } } else if (props[kk]) { data[props[kk].fieldNames[0] as EntityKey] = data[prop.name][ props[kk].embedded![1] as never ] as T[EntityKey]; } else { throw ValidationError.invalidEmbeddableQuery(meta.class, kk, prop.type); } }); if (!unknownProp) { delete data[prop.name]; } } }); } protected getPrimaryKeyFields(meta: EntityMetadata): string[] { return meta.getPrimaryProps().flatMap(pk => pk.fieldNames); } /** Column a scalar value of the property maps to; a composite FK given as a scalar holds only the target PK, which belongs to the column referencing it. */ protected getScalarFieldName(prop: EntityProperty): string { if (prop.fieldNames.length < 2 || prop.polymorphic || !prop.targetMeta) { return prop.fieldNames[0]; } const idx = prop.referencedColumnNames.indexOf(prop.targetMeta.getPrimaryProps()[0]?.fieldNames[0]); return prop.fieldNames[idx === -1 ? 0 : idx]; } protected createReplicas(cb: (c: ConnectionOptions) => C): C[] { const replicas = this.config.get('replicas', []) as ConnectionOptions[]; const ret: C[] = []; const props = [ 'dbName', 'clientUrl', 'host', 'port', 'user', 'password', 'multipleStatements', 'pool', 'name', 'driverOptions', ] as const; for (const conf of replicas) { const replicaConfig = Utils.copy(conf) as Dictionary; for (const prop of props) { if (conf[prop]) { continue; } // do not copy options that can be inferred from explicitly provided `clientUrl` if (conf.clientUrl && ['clientUrl', 'host', 'port', 'user', 'password'].includes(prop)) { continue; } if (conf.clientUrl && prop === 'dbName' && new URL(conf.clientUrl).pathname) { continue; } replicaConfig[prop] = this.config.get(prop); } ret.push(cb(replicaConfig as ConnectionOptions)); } return ret; } /** Acquires a pessimistic lock on the given entity. */ async lockPessimistic(entity: T, options: LockOptions): Promise { throw new Error(`Pessimistic locks are not supported by ${this.constructor.name} driver`); } abstract stream( entityName: EntityName, where: FilterQuery, options: StreamOptions, ): AsyncIterableIterator; /** * @inheritDoc */ convertException(exception: Error): DriverException { if (exception instanceof DriverException) { return exception; } return this.platform.getExceptionConverter().convertException(exception); } protected rethrow(promise: Promise): Promise { return promise.catch(e => { throw this.convertException(e); }); } /** * @internal */ getTableName(meta: EntityMetadata, options: NativeInsertUpdateManyOptions, quote = true): string { const schema = this.getSchemaName(meta, options); const tableName = schema && schema !== this.platform.getDefaultSchemaName() ? `${schema}.${meta.tableName}` : meta.tableName; if (quote) { return this.platform.quoteIdentifier(tableName); } return tableName; } /** * @internal */ getSchemaName(meta?: EntityMetadata, options?: { schema?: string; parentSchema?: 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.getSchema() : meta?.schema; return options?.schema ?? options?.parentSchema ?? schemaName ?? this.config.getSchema(); } /** @internal */ getORMClass(): Constructor { return MikroORM; } }