import { type AbortQueryOptions, ALIAS_REPLACEMENT_RE, type AnyEntity, type Collection, type Configuration, type ConnectionType, type Constructor, type CountOptions, DatabaseDriver, DateType, type DeleteOptions, type Dictionary, type DriverMethodOptions, type EntityData, type EntityDataValue, type EntityDictionary, type EntityField, type EntityKey, EntityManagerType, type EntityMetadata, type EntityName, type EntityProperty, type EntityValue, type FilterQuery, type FindByCursorOptions, type FindOneOptions, type FindOptions, type FormulaTable, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, type LockOptions, type LoggingOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type ObjectQuery, type Options, type OrderDefinition, parseJsonSafe, PolymorphicRef, type PopulateOptions, type Primary, QueryFlag, QueryHelper, QueryOrder, type QueryOrderMap, type QueryResult, raw, type Raw, RawQueryFragment, ReferenceKind, type RequiredEntityData, type StreamOptions, type Transaction, type UpsertManyOptions, type UpsertOptions, Utils, } from '@mikro-orm/core'; import type { AbstractSqlConnection } from './AbstractSqlConnection.js'; import type { AbstractSqlPlatform } from './AbstractSqlPlatform.js'; import { type AnyQueryBuilder, QueryBuilder } from './query/QueryBuilder.js'; import { type NativeQueryBuilder } from './query/NativeQueryBuilder.js'; import { JoinType, QueryType } from './query/enums.js'; import { SqlEntityManager } from './SqlEntityManager.js'; import type { InternalField } from './typings.js'; import { PivotCollectionPersister } from './PivotCollectionPersister.js'; /** Extracts cancellation controls from any options bag that extends `AbortQueryOptions`. */ function pickAbortOptions(options?: AbortQueryOptions): AbortQueryOptions | undefined { if (!options || (options.signal == null && options.inflightQueryAbortStrategy == null)) { return undefined; } return { signal: options.signal, inflightQueryAbortStrategy: options.inflightQueryAbortStrategy, }; } /** * Returns a `loggerContext` payload that carries the abort fields alongside any existing * context. The connection layer strips them before logging — this avoids widening the public * `Connection.execute()` signature. */ function withAbortContext( loggerContext: LoggingOptions | undefined, options?: AbortQueryOptions, ): LoggingOptions | undefined { const abort = pickAbortOptions(options); if (!abort) { return loggerContext; } return { ...(loggerContext as Dictionary), ...abort } as LoggingOptions; } /** Base class for SQL database drivers, implementing find/insert/update/delete using QueryBuilder. */ export abstract class AbstractSqlDriver< Connection extends AbstractSqlConnection = AbstractSqlConnection, Platform extends AbstractSqlPlatform = AbstractSqlPlatform, > extends DatabaseDriver { override [EntityManagerType]!: SqlEntityManager; protected override readonly connection: Connection; protected override readonly replicas: Connection[] = []; protected override readonly platform: Platform; protected constructor( config: Configuration, platform: Platform, connection: Constructor, connector: string[], ) { super(config, connector); this.connection = new connection(this.config); this.replicas = this.createReplicas(conf => new connection(this.config, conf, 'read')); this.platform = platform; } override getPlatform(): Platform { return this.platform; } /** Evaluates a formula callback, handling both string and Raw return values. */ evaluateFormula(formula: (...args: any[]) => string | Raw, columns: any, table: FormulaTable): string { const result = formula(columns, table); return isRaw(result) ? this.platform.quoteIdentifier(result) : result; } /** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */ protected getTableProps(meta: EntityMetadata): EntityProperty[] { return meta.inheritanceType === 'tpt' && meta.ownProps ? meta.ownProps : meta.props; } /** Columns reloaded by INSERT: generated/default columns any row leaves to the database, and explicit `returning` hints. */ protected getInsertReturningProperties( meta: EntityMetadata, data: EntityDictionary[], ): EntityProperty[] { return this.getTableProps(meta).filter( prop => prop.returning || (((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) && data.some(d => !(prop.name in d) || isRaw(d[prop.name]))), ); } /** Columns reloaded by UPDATE: raw values, PKs, generated/version columns and explicit `returning` hints. */ protected getUpdateReturningProperties( meta: EntityMetadata, data: EntityDictionary[], ): EntityProperty[] { const returning = new Set>(); for (const row of data) { for (const k of Utils.keys(row) as EntityKey[]) { if (isRaw(row[k])) { returning.add(meta.properties[k] ?? meta.root.properties[k]); } } } meta.getPrimaryProps().forEach(prop => returning.add(prop)); // a mixed STI batch shares one table, so the child columns live on the root this.getTableProps(meta.root.discriminatorColumn ? meta.root : meta) .filter(prop => prop.generated || prop.version || prop.returning) .forEach(prop => returning.add(prop)); return [...returning]; } /** Column expression for the `returning` clause of batch updates, applying `convertToJSValueSQL` of custom types. */ protected getReturningFieldSQL(prop: EntityProperty, fieldName: string, index: number): string { const quoted = this.platform.quoteIdentifier(fieldName); const customType = prop.customTypes?.[index] ?? prop.customType; if (prop.hasConvertToJSValueSQL && customType?.convertToJSValueSQL) { return `${customType.convertToJSValueSQL(quoted, this.platform)} as ${quoted}`; } return quoted; } /** Creates a FormulaTable object for use in formula callbacks. */ private createFormulaTable(alias: string, meta: EntityMetadata, schema?: string): FormulaTable { const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined); const qualifiedName = effectiveSchema ? `${effectiveSchema}.${meta.tableName}` : meta.tableName; return { alias, name: meta.tableName, schema: effectiveSchema, qualifiedName, toString: () => alias }; } private validateSqlOptions(options: { collation?: any; indexHint?: any; using?: any }): void { if (options.using && !options.indexHint) { const names = Utils.asArray(options.using); const hint = this.platform.formatIndexHint(names); if (hint) { options.indexHint = hint; } } if (options.collation != null && typeof options.collation !== 'string') { throw new Error( 'Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.', ); } if (options.indexHint != null && typeof options.indexHint !== 'string') { throw new Error( "indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.", ); } } override createEntityManager(useContext?: boolean): this[typeof EntityManagerType] { const EntityManagerClass = this.config.get('entityManager', SqlEntityManager); return new EntityManagerClass(this.config, this, this.metadata, useContext); } private async createQueryBuilderFromOptions( meta: EntityMetadata, where: FilterQuery, options: FindOptions = {}, ): Promise> { const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType }); const populate = this.autoJoinOneToOneOwner( meta, options.populate as unknown as PopulateOptions[], options.fields, ); const joinedProps = this.joinedProps(meta, populate, options); const schema = this.getSchemaName(meta, options); const qb = this.createQueryBuilder( meta.class, options.ctx, connectionType, false, options.logging, undefined, options.em as any, ) .withSchema(schema) .cache(false); qb.setAbortOptions(pickAbortOptions(options)); const fields = this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, schema); const orderBy = this.buildOrderBy(qb, meta, populate, options); const populateWhere = this.buildPopulateWhere(meta, joinedProps, options); Utils.asArray(options.flags).forEach(flag => qb.setFlag(flag)); if (Utils.isPrimaryKey(where, meta.compositePK)) { where = { [Utils.getPrimaryKeyHash(meta.primaryKeys)]: where } as ObjectQuery; } this.validateSqlOptions(options); const { first, last, before, after } = options as FindByCursorOptions; const isCursorPagination = [first, last, before, after].some(v => v != null); qb.state.resolvedPopulateWhere = (options as Dictionary)._populateWhere; qb.select(fields as any) // only add populateWhere if we are populate-joining, as this will be used to add `on` conditions .populate( populate, joinedProps.length > 0 ? populateWhere : undefined, joinedProps.length > 0 ? options.populateFilter : undefined, ) .where(where as any) .groupBy(options.groupBy as any) .having(options.having as any) .indexHint(options.indexHint as string) .collation(options.collation as string) .comment(options.comments) .hintComment(options.hintComments); if (isCursorPagination) { const { orderBy: newOrderBy, where } = this.processCursorOptions(meta, options, orderBy); (qb.andWhere as any)(where).orderBy(newOrderBy); } else { qb.orderBy(orderBy); } if (options.limit != null || options.offset != null) { qb.limit(options.limit, options.offset); } if (options.lockMode) { qb.setLockMode(options.lockMode, options.lockTableAliases); } if (options.em) { await qb.applyJoinedFilters(options.em, options.filters); } if ((options as Dictionary)._partitionLimit) { qb.setPartitionLimit((options as Dictionary)._partitionLimit); } return qb; } async find( entityName: EntityName, where: ObjectQuery, options: FindOptions = {}, ): Promise[]> { options = { populate: [], orderBy: [], ...options }; const meta = this.metadata.get(entityName); if (meta.virtual) { return this.findVirtual(entityName, where, options); } if (options.unionWhere?.length) { where = await this.applyUnionWhere(meta, where, options); } const qb = await this.createQueryBuilderFromOptions(meta, where, options); const result = await this.rethrow(qb.execute('all')); if (options.last && !options.first) { result.reverse(); } return result; } async findOne( entityName: EntityName, where: ObjectQuery, options?: FindOneOptions, ): Promise | null> { const opts = { populate: [], ...options } as FindOptions; const meta = this.metadata.find(entityName)!; const populate = this.autoJoinOneToOneOwner(meta, opts.populate as unknown as PopulateOptions[], opts.fields); const joinedProps = this.joinedProps(meta, populate, options); const hasToManyJoins = joinedProps.some(hint => this.hasToManyJoins(hint, meta)); if (joinedProps.length === 0 || !hasToManyJoins) { opts.limit = 1; } if (opts.limit! > 0 && !opts.flags?.includes(QueryFlag.DISABLE_PAGINATE)) { opts.flags ??= []; opts.flags.push(QueryFlag.DISABLE_PAGINATE); } const res = await this.find(entityName, where, opts); return res[0] || null; } protected hasToManyJoins(hint: PopulateOptions, meta: EntityMetadata): boolean { const [propName] = hint.field.split(':', 2) as [EntityKey]; const prop = meta.properties[propName]; if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) { return true; } if (hint.children && prop.targetMeta) { return hint.children.some(hint => this.hasToManyJoins(hint as any, prop.targetMeta as any)); } return false; } override async findVirtual( entityName: EntityName, where: ObjectQuery, options: FindOptions, ): Promise[]> { return this.findFromVirtual(entityName, where, options, QueryType.SELECT) as Promise[]>; } override async countVirtual( entityName: EntityName, where: ObjectQuery, options: CountOptions, ): Promise { return this.findFromVirtual(entityName, where, options, QueryType.COUNT) as Promise; } protected async findFromVirtual( entityName: EntityName, where: ObjectQuery, options: FindOptions | CountOptions, type: QueryType, ): Promise[] | number> { const meta = this.metadata.get(entityName); /* v8 ignore next */ if (!meta.expression) { return type === QueryType.SELECT ? [] : 0; } if (typeof meta.expression === 'string') { return this.wrapVirtualExpressionInSubquery(meta, meta.expression, where, options as FindOptions, type); } // fork the caller EM so the callback inherits its filters, filter params and session context — a fork never // resolves back to the ambient RequestContext EM, which would ignore the transaction/session context set below const em = (options.em?.fork() ?? this.createEntityManager(false)) as this[typeof EntityManagerType]; em.setTransactionContext(options.ctx); const res = meta.expression(em, where, options as FindOptions); if (typeof res === 'string') { return this.wrapVirtualExpressionInSubquery(meta, res, where, options as FindOptions, type); } if (res instanceof QueryBuilder) { return this.wrapVirtualExpressionInSubquery( meta, this.platform.quoteIdentifier(res.toRaw()), where, options as FindOptions, type, ); } if (isRaw(res)) { const expr = this.platform.quoteIdentifier(res); return this.wrapVirtualExpressionInSubquery(meta, expr, where, options as FindOptions, type); } /* v8 ignore next */ return res as EntityData[]; } protected async *streamFromVirtual( entityName: EntityName, where: FilterQuery, options: StreamOptions, ): AsyncIterableIterator> { const meta = this.metadata.get(entityName); /* v8 ignore next */ if (!meta.expression) { return; } if (typeof meta.expression === 'string') { yield* this.wrapVirtualExpressionInSubqueryStream(meta, meta.expression, where, options, QueryType.SELECT); return; } // fork the caller EM for the same reason as in `findFromVirtual` const em = (options.em?.fork() ?? this.createEntityManager(false)) as this[typeof EntityManagerType]; em.setTransactionContext(options.ctx); const res = meta.expression(em, where as any, options as FindOptions, true); if (typeof res === 'string') { yield* this.wrapVirtualExpressionInSubqueryStream(meta, res, where, options, QueryType.SELECT); return; } if (res instanceof QueryBuilder) { yield* this.wrapVirtualExpressionInSubqueryStream( meta, this.platform.quoteIdentifier(res.toRaw()), where, options, QueryType.SELECT, ); return; } if (isRaw(res)) { const expr = this.platform.quoteIdentifier(res); yield* this.wrapVirtualExpressionInSubqueryStream(meta, expr, where, options, QueryType.SELECT); return; } /* v8 ignore next */ yield* res as EntityData[]; } protected async wrapVirtualExpressionInSubquery( meta: EntityMetadata, expression: string, where: FilterQuery, options: FindOptions, type: QueryType, ): Promise { const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options)); qb.setFlag(QueryFlag.DISABLE_PAGINATE); const isCursorPagination = [options.first, options.last, options.before, options.after].some(v => v != null); const native = qb.getNativeQuery(false); if (type === QueryType.COUNT) { native.clear('select').clear('limit').clear('offset').count(); } const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' '; native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`)); const loggerContext = withAbortContext(options.loggerContext, options); // virtual entities execute directly (not via QueryBuilder), so wrap in a short implicit transaction outside an // existing one when a session context (row level security) needs to apply — mirrors the QueryBuilder wrap const sessionContext = options.ctx ? undefined : options.em?.getTransactionSessionContext(); const conn = this.getConnection(this.resolveConnectionType(options)); const res = await (sessionContext ? conn.transactional(trx => this.execute(native, [], 'all', trx, loggerContext), { sessionContext, loggerContext, }) : this.execute(native, [], 'all', options.ctx, loggerContext)); if (type === QueryType.COUNT) { return (res[0] as Dictionary).count; } if (isCursorPagination && !options.first && !!options.last) { res.reverse(); } return res.map(row => this.mapResult(row, meta) as T); } protected async *wrapVirtualExpressionInSubqueryStream( meta: EntityMetadata, expression: string, where: FilterQuery, options: StreamOptions, type: QueryType.SELECT, ): AsyncIterableIterator { const qb = await this.createQueryBuilderFromOptions(meta, where, this.forceBalancedStrategy(options)); qb.unsetFlag(QueryFlag.DISABLE_PAGINATE); const native = qb.getNativeQuery(false); const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' '; native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`)); const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType }); const res = this.getConnection(connectionType).stream( native, [], options.ctx, withAbortContext(options.loggerContext, options), options.chunkSize, ); for await (const row of res) { yield this.mapResult(row, meta) as T; } } /** * Virtual entities have no PKs, so to-many populate joins can't be deduplicated. * Force balanced strategy to load to-many relations via separate queries. */ private forceBalancedStrategy( options: FindOptions, ): FindOptions { const clearStrategy = (hints: PopulateOptions[]): PopulateOptions[] => { return hints.map(hint => ({ ...hint, strategy: undefined, children: hint.children ? clearStrategy(hint.children) : undefined, })); }; const opts = { ...options, strategy: 'balanced' as const }; if (Array.isArray(opts.populate)) { opts.populate = clearStrategy(opts.populate as PopulateOptions[]) as any; } return opts; } override mapResult( result: EntityData, meta: EntityMetadata, populate: PopulateOptions[] = [], qb?: AnyQueryBuilder, map: Dictionary = {}, ): EntityData | null { // For TPT inheritance, map aliased parent table columns back to their field names if (qb && meta.inheritanceType === 'tpt' && meta.tptParent) { this.mapTPTColumns(result, meta, qb); } // For TPT polymorphic queries (querying a base class), map child table fields if (qb && meta.inheritanceType === 'tpt' && meta.allTPTDescendants?.length) { const mainAlias = (qb as any).mainAlias?.aliasName ?? 'e0'; this.mapTPTChildFields(result, meta, mainAlias, qb, result); } const ret = super.mapResult(result, meta); /* v8 ignore next */ if (!ret) { return null; } if (qb) { // here we map the aliased results (cartesian product) to an object graph this.mapJoinedProps(ret, meta, populate, qb, ret, map); // copy without the consumed aliased columns, deleting them would leave the row in slow dictionary mode if (populate.length > 0) { const clean = {} as Dictionary; const consumed = map.consumedKeys as Set | undefined; for (const key in ret) { if (!consumed?.has(key)) { clean[key] = ret[key as EntityKey]; } } return clean as EntityData; } } return ret; } /** * Maps aliased columns from TPT parent tables back to their original field names. * TPT parent columns are selected with aliases like `parent_alias__column_name`, * and need to be renamed back to `column_name` for the result mapper to work. */ private mapTPTColumns( result: EntityData, meta: EntityMetadata, qb: AnyQueryBuilder, ): void { const tptAliases = qb.state.tptAlias; // Walk up the TPT hierarchy let parentMeta: EntityMetadata | undefined = meta.tptParent; while (parentMeta) { const parentAlias = tptAliases[parentMeta.className]; if (parentAlias) { // Rename columns from this parent table for (const prop of parentMeta.ownProps!) { if (!prop.fieldNames) { continue; } for (const fieldName of prop.fieldNames) { const aliasedKey = `${parentAlias}__${fieldName}` as EntityKey; if (aliasedKey in result) { // Copy the value to the unaliased field name and remove the aliased key (result as Dictionary)[fieldName] = result[aliasedKey]; delete result[aliasedKey]; } } } } parentMeta = parentMeta.tptParent; } } private mapJoinedProps( result: EntityData, meta: EntityMetadata, populate: PopulateOptions[], qb: AnyQueryBuilder, root: EntityData, map: Dictionary, parentJoinPath?: string, ) { const joinedProps = this.joinedProps(meta, populate); joinedProps.forEach(hint => { const [propName, ref] = hint.field.split(':', 2) as [EntityKey, string | undefined]; const prop = meta.properties[propName]; /* v8 ignore next */ if (!prop) { return; } // A condition can join the target without selecting its columns. Keep the FK // already mapped from the root row for reference-only owning to-one relations. if ( ref && !hint.filter && (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner)) ) { return; } // Polymorphic to-one: iterate targets, find the matching one, build entity from its columns. // Skip :ref hints — no JOINs were created, so the FK reference is already set by the result mapper. if ( prop.polymorphic && prop.polymorphTargets?.length && !ref && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ) { const basePath = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`; const pathPrefix = !parentJoinPath ? '[populate]' : ''; let matched = false; for (const targetMeta of prop.polymorphTargets) { const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`; const relationAlias = qb.getAliasForJoinPath(targetPath, { matchPopulateJoins: true })!; const meta2 = targetMeta as EntityMetadata; const targetProps = meta2.props.filter(p => this.platform.shouldHaveColumn(p, (hint.children as any) || [])); const hasPK = meta2 .getPrimaryProps() .every(pk => pk.fieldNames.every(name => root[`${relationAlias}__${name}` as EntityKey] != null)); if (hasPK && !matched) { matched = true; const relationPojo: EntityData = {}; const tz = this.platform.getTimezone(); for (const p of targetProps) { this.mapJoinedProp(relationPojo, p, this.aliasedKeys(p, relationAlias), root, tz, meta2); } // For TPT base targets, map child-specific fields and resolve the // concrete class so the factory creates the correct subtype. const concreteMeta = this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root); Object.defineProperty(relationPojo, 'constructor', { value: concreteMeta?.class ?? meta2.class, enumerable: false, configurable: true, }); result[prop.name] = relationPojo as EntityDataValue; const populateChildren = (hint.children as any) || []; this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath); } // Clean up aliased columns for ALL targets (even non-matching ones) const consumed = ((map.consumedKeys as Set) ??= new Set()); for (const p of targetProps) { for (const name of p.fieldNames) { consumed.add(`${relationAlias}__${name}`); } } } if (!matched) { result[prop.name] = null; } return; } const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref && !hint.filter; const meta2 = prop.targetMeta as EntityMetadata; let path = parentJoinPath ? `${parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`; if (!parentJoinPath) { path = '[populate]' + path; } if (pivotRefJoin) { path += '[pivot]'; } const relationAlias = qb.getAliasForJoinPath(path, { matchPopulateJoins: true }); /* v8 ignore next */ if (!relationAlias) { return; } // pivot ref joins via joined strategy need to be handled separately here, as they dont join the target entity if (pivotRefJoin) { let item; if (prop.inverseJoinColumns.length > 1) { // composite keys item = prop.inverseJoinColumns.map( name => root[`${relationAlias}__${name}` as EntityKey], ) as EntityValue; } else { const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}` as EntityKey; item = root[alias] as EntityValue; } const consumed = ((map.consumedKeys as Set) ??= new Set()); prop.joinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`)); prop.inverseJoinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`)); result[prop.name] ??= [] as EntityDataValue; if (item) { (result[prop.name] as EntityData[]).push(item); } return; } const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk); // all rows of a result share their columns, so resolve the mapped props once per join path const joinedTargets = ((map.joinedTargets as Dictionary) ??= {}); joinedTargets[path] ??= this.resolveJoinedTargets(meta2, hint, mapToPk, !!ref, relationAlias, root, map); const targets = joinedTargets[path] as { targetProps: EntityProperty[]; targetKeys: string[][]; pkKeys: string[]; virtualProps: EntityProperty[]; childrenResolved?: boolean; }; const { targetProps, targetKeys, pkKeys, virtualProps } = targets; // If the primary key value for the relation is null, we know we haven't joined to anything // and therefore we don't return any record (since all values would be null) const hasPK = pkKeys.every(key => root[key as EntityKey] != null); if (!hasPK) { if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) { result[prop.name] = [] as EntityDataValue; } if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) { result[prop.name] = null; } // resolve nested join paths once, so their columns are dropped even when no row has this relation if (hint.children?.length && !targets.childrenResolved) { this.mapJoinedProps({}, meta2, hint.children as any, qb, root, map, path); targets.childrenResolved = true; } return; } let relationPojo: EntityData = {}; virtualProps.forEach(prop => { /* v8 ignore next */ if (prop.fieldNames.length > 1) { // composite keys relationPojo[prop.name as EntityKey] = prop.fieldNames.map( name => root[`${relationAlias}__${name}` as EntityKey], ) as EntityDataValue; } else { const alias = `${relationAlias}__${prop.fieldNames[0]}` as EntityKey; relationPojo[prop.name] = root[alias] as EntityDataValue; } }); const tz = this.platform.getTimezone(); for (let i = 0; i < targetProps.length; i++) { this.mapJoinedProp(relationPojo, targetProps[i], targetKeys[i], root, tz, meta2); } // Handle TPT polymorphic child fields - map fields from child table aliases this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root); if (mapToPk) { const tmp = Object.values(relationPojo); /* v8 ignore next */ relationPojo = (meta2.compositePK ? tmp : tmp[0]) as EntityData; } if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) { result[prop.name] ??= [] as EntityDataValue; (result[prop.name] as EntityData[]).push(relationPojo); } else { result[prop.name] = relationPojo as EntityDataValue; } const populateChildren = (hint.children as any) || []; this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path); targets.childrenResolved = true; }); } /** Keys are marked consumed, not deleted per row: deletes are slow and shared FK columns must stay readable. */ private resolveJoinedTargets( meta: EntityMetadata, hint: PopulateOptions, mapToPk: boolean, ref: boolean, relationAlias: string, root: EntityData, map: Dictionary, ) { const targetProps = ( mapToPk ? meta.getPrimaryProps() : meta.props.filter(prop => this.platform.shouldHaveColumn(prop, (hint.children as any) || [])) ).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}` as EntityKey] !== 'undefined'), ); const targetKeys = targetProps.map(prop => this.aliasedKeys(prop, relationAlias)); const consumed = ((map.consumedKeys as Set) ??= new Set()); targetKeys.forEach(keys => keys.forEach(key => consumed.add(key))); return { targetProps, targetKeys, pkKeys: meta.getPrimaryProps().flatMap(pk => this.aliasedKeys(pk, relationAlias)), virtualProps: meta.props.filter(prop => !ref && prop.persist === false && prop.fieldNames), }; } private aliasedKeys(prop: EntityProperty, relationAlias: string): string[] { return prop.fieldNames.map(name => `${relationAlias}__${name}`); } /** * Maps a single property from a joined result row into the relation pojo. * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects. */ private mapJoinedProp( relationPojo: EntityData, prop: EntityProperty, keys: string[], root: EntityData, tz: string | undefined, meta: EntityMetadata, options?: { deleteFromRoot?: boolean }, ): void { const row = root as Dictionary; if (keys.every(key => typeof row[key] === 'undefined')) { return; } // inline embeddables are mapped via their flattened child props; mapping the embedded root prop // here would leak a raw column value into the snapshot and produce a phantom changeset if (prop.kind === ReferenceKind.EMBEDDED && !prop.object && !meta.embeddable) { return; } if (prop.polymorphic && prop.kind !== ReferenceKind.EMBEDDED) { const discriminatorValue = row[keys[0]] as string; const pkValues = keys.slice(1).map(key => row[key]); const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues; if (discriminatorValue != null && pkValue != null) { relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue) as EntityDataValue; } else { relationPojo[prop.name] = null; } } else if (prop.fieldNames.length > 1) { // composite keys const fk = keys.map(key => row[key]) as Primary[]; // `mapFlatCompositePrimaryKey` collapses to a scalar when the target PK is a single prop // (e.g. a relation referencing a composite unique key on a single-PK target). const pk = Utils.mapFlatCompositePrimaryKey(fk, prop); const valid = Array.isArray(pk) ? pk.every(val => val != null) : pk != null; relationPojo[prop.name] = valid ? (pk as EntityDataValue) : null; } else if (prop.runtimeType === 'Date') { const value = row[keys[0]] as unknown; if ( tz && tz !== 'local' && typeof value === 'string' && !value.includes('+') && value.lastIndexOf('-') < 11 && !value.endsWith('Z') ) { relationPojo[prop.name] = this.platform.parseDate(value + tz) as EntityDataValue; } else if (['string', 'number'].includes(typeof value)) { relationPojo[prop.name] = this.platform.parseDate(value as string) as EntityDataValue; } else { relationPojo[prop.name] = value as EntityDataValue; } } else if (prop.customType instanceof DateType) { // tedious returns DATE columns as `Date`, map them to the string the entity holds, so the snapshot matches it const value = row[keys[0]]; relationPojo[prop.name] = ( value instanceof Date ? this.platform.convertDateToJSValue(value) : value ) as EntityDataValue; } else { relationPojo[prop.name] = row[keys[0]]; if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) { const item = parseJsonSafe(relationPojo[prop.name]); if (Array.isArray(item)) { relationPojo[prop.name] = item.map(row => row == null ? row : this.comparator.mapResult(prop.targetMeta!, row), ) as EntityDataValue; } else { relationPojo[prop.name] = item == null ? item : (this.comparator.mapResult(prop.targetMeta!, item) as EntityDataValue); } } } if (options?.deleteFromRoot) { for (const key of keys) { delete row[key]; } } } async count(entityName: EntityName, where: any, options: CountOptions = {}): Promise { const meta = this.metadata.get(entityName); if (meta.virtual) { return this.countVirtual(entityName, where, options); } if (options.unionWhere?.length) { where = await this.applyUnionWhere(meta, where, options); } options = { populate: [], ...options }; const populate = options.populate as unknown as PopulateOptions[]; const joinedProps = this.joinedProps(meta, populate, options as FindOptions); const schema = this.getSchemaName(meta, options); const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false, options.logging); qb.setAbortOptions(pickAbortOptions(options)); const populateWhere = this.buildPopulateWhere(meta, joinedProps, options); if (meta && !Utils.isEmpty(populate)) { this.buildFields(meta, populate, joinedProps, qb, qb.alias, options as FindOptions, schema); } this.validateSqlOptions(options); qb.state.resolvedPopulateWhere = (options as Dictionary)._populateWhere; qb.indexHint(options.indexHint as string) .collation(options.collation as string) .comment(options.comments) .hintComment(options.hintComments) .groupBy(options.groupBy as any) .having(options.having as any) .populate( populate, joinedProps.length > 0 ? populateWhere : undefined, joinedProps.length > 0 ? options.populateFilter : undefined, ) .withSchema(schema) .where(where); if (options.em) { await qb.applyJoinedFilters(options.em, options.filters); } return this.rethrow(qb.getCount()); } async nativeInsert( entityName: EntityName, data: EntityDictionary, options: NativeInsertUpdateOptions = {}, ): Promise> { options.convertCustomTypes ??= true; const meta = this.metadata.get(entityName); const collections = this.extractManyToMany(meta, data); const qb = this.createQueryBuilder( entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(meta, options)); qb.setAbortOptions(pickAbortOptions(options)); const res = await this.rethrow(qb.insert(data as unknown as RequiredEntityData).execute('run', false)); res.row = res.row || {}; let pk: any; if (meta.primaryKeys.length > 1) { // owner has composite pk pk = Utils.getOrderedPrimaryKeys(data as Record>, meta); } else { /* v8 ignore next */ res.insertId = data[meta.primaryKeys[0]] ?? res.insertId ?? res.row[meta.primaryKeys[0]]; if (options.convertCustomTypes && meta?.getPrimaryProp().customType) { pk = [meta!.getPrimaryProp().customType!.convertToDatabaseValue(res.insertId, this.platform)]; } else { pk = [res.insertId]; } } await this.processManyToMany(meta, pk, collections, false, options); return res; } override async nativeClone( entityName: EntityName, where: FilterQuery, overrides?: EntityData, options: NativeInsertUpdateOptions = {}, ): Promise> { options.convertCustomTypes ??= true; const meta = this.metadata.get(entityName); if (meta.inheritanceType === 'tpt' || meta.tptParent) { return this.nativeCloneTPT(meta, where, overrides, options); } return this.nativeCloneSimple(meta, where, overrides, options); } private async nativeCloneSimple( meta: EntityMetadata, where: FilterQuery, overrides?: EntityData, options: NativeInsertUpdateOptions = {}, ): Promise> { const props = this.getCloneableProps(meta); const mappedOverrides = this.mapCloneOverrides(overrides, meta, options); const { selectFields, insertColumns } = this.buildCloneFields(props, mappedOverrides, meta); const abort = pickAbortOptions(options); const selectQb = this.createQueryBuilder( meta.class, options.ctx, 'read', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(meta, options)); selectQb.select(selectFields as any).where(where as any); selectQb.setAbortOptions(abort); const insertQb = this.createQueryBuilder( meta.class, options.ctx, 'write', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(meta, options)); insertQb.setAbortOptions(abort); return this.rethrow( (insertQb as AnyQueryBuilder) .insertFrom(selectQb as AnyQueryBuilder, { columns: insertColumns as any }) .execute('run', false), ); } private async nativeCloneTPT( leafMeta: EntityMetadata, where: FilterQuery, overrides?: EntityData, options: NativeInsertUpdateOptions = {}, ): Promise> { const hierarchy: EntityMetadata[] = []; let current: EntityMetadata | undefined = leafMeta; while (current) { hierarchy.unshift(current); current = current.tptParent; } const rootMeta = hierarchy[0]; let newPk: any; let rootResult: QueryResult | undefined; for (const tableMeta of hierarchy) { const props = this.getCloneableProps(tableMeta as EntityMetadata, true); const mappedOverrides = this.mapCloneOverrides(overrides, tableMeta as EntityMetadata, options); const { selectFields, insertColumns } = this.buildCloneFields( props, mappedOverrides, tableMeta as EntityMetadata, ); // For child tables, prepend the new PK value if (tableMeta !== rootMeta && newPk != null) { for (const pkName of tableMeta.primaryKeys) { const prop = tableMeta.properties[pkName as EntityKey] as EntityProperty; for (const fieldName of prop.fieldNames) { insertColumns.unshift(fieldName); selectFields.unshift(raw('? as ??', [newPk, fieldName])); } } } const sourceWhere = tableMeta === rootMeta ? where : ((Utils.extractPK(where as any, tableMeta) as FilterQuery) ?? where); const abort = pickAbortOptions(options); const selectQb = this.createQueryBuilder( tableMeta.class as any, options.ctx, 'read', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(tableMeta as EntityMetadata, options)); selectQb.select(selectFields as any).where(sourceWhere as any); selectQb.setAbortOptions(abort); const insertQb = this.createQueryBuilder( tableMeta.class as any, options.ctx, 'write', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(tableMeta as EntityMetadata, options)); insertQb.setAbortOptions(abort); const res = await this.rethrow( (insertQb as AnyQueryBuilder) .insertFrom(selectQb as AnyQueryBuilder, { columns: insertColumns as any }) .execute('run', false), ); if (tableMeta === rootMeta) { rootResult = res; newPk = res.insertId ?? res.row?.[rootMeta.primaryKeys[0]]; } } return rootResult!; } private mapCloneOverrides( overrides: EntityData | undefined, meta: EntityMetadata, options: NativeInsertUpdateOptions, ): Dictionary | undefined { if (!overrides) { return undefined; } return super.mapDataToFieldNames(overrides as Dictionary, true, meta.properties as any, options.convertCustomTypes); } private buildCloneFields( props: EntityProperty[], mappedOverrides: Dictionary | undefined, meta: EntityMetadata, ): { selectFields: (string | RawQueryFragment)[]; insertColumns: string[] } { const selectFields: (string | RawQueryFragment)[] = []; const insertColumns: string[] = []; for (const prop of props) { for (const fieldName of prop.fieldNames) { insertColumns.push(fieldName); if (mappedOverrides && fieldName in mappedOverrides) { selectFields.push(raw('? as ??', [mappedOverrides[fieldName], fieldName])); } else if (meta.versionProperty === prop.name) { const initial = prop.runtimeType === 'Date' ? new Date() : 1; selectFields.push(raw('? as ??', [initial, fieldName])); } else { selectFields.push(fieldName); } } } return { selectFields, insertColumns }; } /** * Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas). * @internal */ getCloneableProps(meta: EntityMetadata, ownProps?: boolean): EntityProperty[] { return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter( prop => !prop.primary && !prop.generated && this.platform.shouldHaveColumn(prop, true, undefined, false, false), ); } async nativeInsertMany( entityName: EntityName, data: EntityDictionary[], options: NativeInsertUpdateManyOptions = {}, transform?: (sql: string) => string, ): Promise> { options.processCollections ??= true; options.convertCustomTypes ??= true; const entityMeta = this.metadata.get(entityName); const meta = entityMeta.inheritanceType === 'tpt' ? entityMeta : entityMeta.root; const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : []; const pks = this.getPrimaryKeyFields(meta); const set = new Set>(); data.forEach(row => Utils.keys(row).forEach(k => set.add(k))); const props = [...set].map(name => meta.properties[name] ?? { name, fieldNames: [name] }) as EntityProperty[]; // For STI with conflicting fieldNames, include all alternative columns let fields = Utils.flatten(props.map(prop => prop.stiFieldNames ?? prop.fieldNames)); const duplicates = Utils.findDuplicates(fields); const params: unknown[] = []; if (duplicates.length) { fields = Utils.unique(fields); } const tableName = this.getTableName(meta, options); let sql = `insert into ${tableName} `; sql += fields.length > 0 ? '(' + fields.map(k => this.platform.quoteIdentifier(k)).join(', ') + ')' : `(${this.platform.quoteIdentifier(pks[0])})`; if (this.platform.usesOutputStatement()) { const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames)); sql += returningFields.length > 0 ? ` output ${returningFields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}` : ''; } if (fields.length > 0 || this.platform.usesDefaultKeyword()) { sql += ' values '; } else { sql += ' ' + data.map(() => `select null as ${this.platform.quoteIdentifier(pks[0])}`).join(' union all '); } const addParams = (prop: EntityProperty, row: Dictionary) => { const rowValue = row[prop.name]; if (prop.nullable && rowValue === null) { params.push(null); return; } let value = rowValue ?? prop.default; if (prop.kind === ReferenceKind.EMBEDDED && prop.object) { if (prop.array && value) { value = this.platform.cloneEmbeddable(value); for (let i = 0; i < (value as Dictionary[]).length; i++) { const item = (value as Dictionary[])[i]; value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes); } } else { value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes); } } if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) { params.push(raw('default')); return; } if (options.convertCustomTypes && prop.customType) { params.push( prop.customType.convertToDatabaseValue(value, this.platform, { key: prop.name, mode: 'query-data' }), ); return; } params.push(value); }; if (fields.length > 0 || this.platform.usesDefaultKeyword()) { sql += data .map(row => { const keys: string[] = []; const usedDups: string[] = []; props.forEach(prop => { // For STI with conflicting fieldNames, use discriminator to determine which field gets value if (prop.stiFieldNames && prop.stiFieldNameMap && meta.discriminatorColumn) { // the map misses subtypes whose props were not initialized yet during discovery (root column owner, grandchildren) const discriminator = row[meta.discriminatorColumn]; const childClass = meta.discriminatorMap?.[discriminator]; const childProp = childClass && this.metadata.find(childClass)?.properties[prop.name]; const activeField = prop.stiFieldNameMap[discriminator] ?? childProp?.fieldNames[0]; for (const field of prop.stiFieldNames) { // the subtype's own property, as siblings can declare it with a different type or embeddable if (field === activeField) { addParams(childProp ?? prop, row); } else { params.push(null); } keys.push('?'); } return; } if (prop.fieldNames.length > 1) { const newFields: string[] = []; let rawParam: unknown[]; const target = row[prop.name] as unknown; if (prop.polymorphic && target instanceof PolymorphicRef) { rawParam = target.toTuple(); } else { rawParam = target == null ? prop.fieldNames.map(() => null) : Utils.asArray(target); } // Deep flatten nested arrays when needed (for deeply nested composite keys like Tag -> Comment -> Post -> User) const needsFlatten = rawParam.length !== prop.fieldNames.length && rawParam.some(v => Array.isArray(v)); const allParam = needsFlatten ? Utils.flatten(rawParam as unknown[][], true) : rawParam; // TODO(v7): instead of making this conditional here, the entity snapshot should respect `ownColumns`, // but that means changing the compiled PK getters, which might be seen as breaking const columns = allParam.length > 1 ? prop.fieldNames : prop.ownColumns; const param: unknown[] = []; columns.forEach((field, idx) => { if (usedDups.includes(field)) { return; } newFields.push(field); param.push(allParam[idx]); }); newFields.forEach((field, idx) => { if (!duplicates.includes(field) || !usedDups.includes(field)) { params.push(param[idx]); keys.push('?'); usedDups.push(field); } }); } else { const field = prop.fieldNames[0]; if (!duplicates.includes(field) || !usedDups.includes(field)) { const rowValue = row[prop.name]; const rowValueIsRaw = isRaw(rowValue); if ( prop.customType && !prop.object && 'convertToDatabaseValueSQL' in prop.customType && rowValue != null && !rowValueIsRaw ) { keys.push(prop.customType.convertToDatabaseValueSQL!('?', this.platform)); } else if (rowValueIsRaw && /^\s*(?:with|select)\b/i.test(rowValue.sql)) { // raw subqueries must be parenthesized when inlined as a VALUES position keys.push('(?)'); } else { keys.push('?'); } addParams(prop, row); usedDups.push(field); } } }); return '(' + (keys.join(', ') || 'default') + ')'; }) .join(', '); } if (meta && this.platform.usesReturningStatement()) { const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames)); /* v8 ignore next */ sql += returningFields.length > 0 ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}` : ''; } if (transform) { sql = transform(sql); } const res = await this.execute>( raw(sql, params), [], 'run', options.ctx, withAbortContext(options.loggerContext, options), ); const pk = this.resolveInsertedPrimaryKeys(meta, data, res); for (let i = 0; i < collections.length; i++) { await this.processManyToMany(meta, pk[i], collections[i], false, options); } return res; } /** Resolves the primary key of every inserted row from the supplied data or the returned rows, and reports them via `insertedIds` when all are known. */ protected resolveInsertedPrimaryKeys( meta: EntityMetadata, data: EntityDictionary[], res: QueryResult, ): any[][] { const pks = this.getPrimaryKeyFields(meta); if (pks.length > 1) { // owner has composite pk const pk = data.map(d => Utils.getOrderedPrimaryKeys(d as Record>, meta)); res.insertedIds = pk as Primary[]; return pk; } res.row ??= {}; res.rows ??= []; const ids: any[] = data.map((d, i) => { // a raw pk expression is resolved by the database, its value only exists in the returned row const supplied = d[meta.primaryKeys[0]] ?? d[pks[0]]; return supplied == null || isRaw(supplied) ? res.rows![i]?.[pks[0]] : supplied; }); res.insertId = res.insertId || res.row[pks[0]]; // drivers without `returning` leave the ids unknown here, keep the `insertId` fallback for them if (ids.every(id => id != null)) { res.insertedIds = ids; } return ids.map(id => [id]); } async nativeUpdate( entityName: EntityName, where: FilterQuery, data: EntityDictionary, options: NativeInsertUpdateOptions & UpsertOptions = {}, ): Promise> { options.convertCustomTypes ??= true; const meta = this.metadata.get(entityName); const pks = this.getPrimaryKeyFields(meta); const collections = this.extractManyToMany(meta, data); let res = { affectedRows: 0, insertId: 0, row: {} } as QueryResult; if (Utils.isPrimaryKey(where) && pks.length === 1) { /* v8 ignore next */ where = { [meta.primaryKeys[0] ?? pks[0]]: where } as FilterQuery; } if (!options.upsert && options.unionWhere?.length) { where = (await this.applyUnionWhere(meta, where as ObjectQuery, options, true)) as FilterQuery; } if (options.upsert && meta.tptParent) { res = await this.nativeUpdateMany(entityName, [where], [data], options); } else if (Utils.hasObjectKeys(data) || (meta.inheritanceType === 'tpt' && meta.ownsVersionProperty())) { // a TPT table declaring the version property is bumped even when only other tables of the hierarchy changed const qb = this.createQueryBuilder( entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(meta, options)); qb.setAbortOptions(pickAbortOptions(options)); if (options.upsert) { /* v8 ignore next */ const uniqueFields = options.onConflictFields ?? ((Utils.isPlainObject(where) ? (Utils.keys(where) as EntityKey[]) : meta.primaryKeys) as (keyof T)[]); const returning = getOnConflictReturningFields(meta, data, uniqueFields, options, this.platform); qb.insert(data as T) .onConflict(uniqueFields as any) .returning(returning as any); if (!options.onConflictAction || options.onConflictAction === 'merge') { const fields = getOnConflictFields(meta, data, uniqueFields, options); qb.merge(fields as any); } if (options.onConflictAction === 'ignore') { qb.ignore(); } if (options.onConflictWhere) { qb.where(options.onConflictWhere as any); } } else { qb.update(data).where(where as any); const returning: string[] = []; this.getTableProps(meta) .filter(prop => (prop.generated && !prop.primary) || prop.version || prop.returning || isRaw(data[prop.name])) .forEach(prop => returning.push(...prop.fieldNames)); qb.returning(returning as any); } res = await this.rethrow(qb.execute('run', false)); } const pk = Utils.getOrderedPrimaryKeys({ ...(where as Dictionary), ...data } as Record>, meta); await this.processManyToMany(meta, pk, collections, true, options); return res; } override async nativeUpdateMany( entityName: EntityName, where: FilterQuery[], data: EntityDictionary[], options: NativeInsertUpdateManyOptions & UpsertManyOptions = {}, transform?: (sql: string, params: any[]) => string, ): Promise> { options.processCollections ??= true; options.convertCustomTypes ??= true; const meta = this.metadata.get(entityName); if (options.upsert) { if (meta.tptParent) { // the parent table reports a single insertId per batch, the EM sends such rows one by one if (where.filter(cond => Utils.isEmpty(cond)).length > 1) { throw new Error(`Cannot upsert more than one ${meta.className} row without a unique value in one batch`); } // TPT parent tables go first, the PK they provide is the conflict target of this table const res = await this.nativeUpdateMany(meta.tptParent.class, where, data, options); for (const [i, row] of data.entries()) { if (meta.primaryKeys.some(pk => row[pk] == null)) { // a row without a condition cannot conflict, only the insert knows its PK const found = Utils.isEmpty(where[i]) ? ({ [meta.primaryKeys[0]]: res.insertId } as EntityData) : await this.findOne(meta.tptParent.class as EntityName, where[i] as ObjectQuery, { fields: meta.primaryKeys as any[], ctx: options.ctx, connectionType: 'write', schema: options.schema, }); meta.primaryKeys.forEach(pk => (row[pk] = found?.[pk] as never)); } } options = { ...options, onConflictFields: meta.primaryKeys, onConflictWhere: undefined }; } const uniqueFields = options.onConflictFields ?? ((Utils.isPlainObject(where[0]) ? Object.keys(where[0]).flatMap(key => Utils.splitPrimaryKeys(key)) : meta.primaryKeys) as (keyof T)[]); const qb = this.createQueryBuilder( entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext, ).withSchema(this.getSchemaName(meta, options)); qb.setAbortOptions(pickAbortOptions(options)); let returning = getOnConflictReturningFields(meta, data[0], uniqueFields, options, this.platform); if (meta.inheritanceType === 'tpt') { // each TPT table only carries its own columns, the entity is reloaded instead of mapping the returned rows const own = (key: string) => meta.primaryKeys.includes(key as EntityKey) || this.getTableProps(meta).some(prop => prop.name === key.split('.')[0]); data = data.map( row => Object.fromEntries(Object.entries(row).filter(([key]) => own(key))) as EntityDictionary, ); options.onConflictMergeFields = options.onConflictMergeFields?.filter(f => own(f as string)); options.onConflictExcludeFields = options.onConflictExcludeFields?.filter(f => own(f as string)); returning = this.getPrimaryKeyFields(meta) as (keyof T)[]; } qb.insert(data as T[]) .onConflict(uniqueFields as any) .returning(returning as any); if (!options.onConflictAction || options.onConflictAction === 'merge') { const fields = getOnConflictFields(meta, data[0], uniqueFields, options); qb.merge(fields as any); } if (options.onConflictAction === 'ignore') { qb.ignore(); } if (options.onConflictWhere) { qb.where(options.onConflictWhere as any); } const res = await this.rethrow(qb.execute('run', false)); if (meta.inheritanceType === 'tpt') { // child tables do not generate the PK, so every table of the hierarchy reports the one of its first row const insertId = data[0][meta.primaryKeys[0]] ?? res.insertId ?? res.row?.[returning[0] as string]; return { ...res, insertId, row: undefined, rows: [] }; } return res; } const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : []; const keys = new Set>(); const fields = new Set(); const returning = this.getUpdateReturningProperties(meta, data); for (const row of data) { for (const k of Utils.keys(row)) { keys.add(k as EntityKey); } } const pkCond = Utils.flatten(meta.primaryKeys.map(pk => meta.properties[pk].fieldNames)) .map(pk => `${this.platform.quoteIdentifier(pk)} = ?`) .join(' and '); const params: any[] = []; let sql = `update ${this.getTableName(meta, options)} set `; const addParams = (prop: EntityProperty, value: Dictionary) => { if (prop.kind === ReferenceKind.EMBEDDED && prop.object) { if (prop.array && value) { for (let i = 0; i < (value as Dictionary[]).length; i++) { const item = (value as Dictionary[])[i]; value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes); } } else { value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes); } } params.push(value ?? null); }; for (const key of keys) { const prop = meta.properties[key] ?? meta.root.properties[key]; if (prop.polymorphic && prop.fieldNames.length > 1) { for (let idx = 0; idx < data.length; idx++) { const rowValue = data[idx][key] as Record | null; if (rowValue instanceof PolymorphicRef) { data[idx][key] = rowValue.toTuple(); } } } const scalarColumn = prop.fieldNames.length > 1 && !prop.polymorphic ? this.getScalarFieldName(prop) : undefined; prop.fieldNames.forEach((fieldName: string, fieldNameIdx: number) => { if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) { return; } fields.add(fieldName); sql += `${this.platform.quoteIdentifier(fieldName)} = case`; where.forEach((cond, idx) => { if (key in data[idx]) { const pks = Utils.getOrderedPrimaryKeys(cond as Dictionary, meta); sql += ` when (${pkCond}) then `; if ( prop.customType && !prop.object && 'convertToDatabaseValueSQL' in prop.customType && data[idx][prop.name] != null && !isRaw(data[idx][key]) ) { sql += prop.customType.convertToDatabaseValueSQL!('?', this.platform); } else { sql += '?'; } params.push(...pks); const value = data[idx][key]; const scalar = Array.isArray(value) && value.length === 1 ? value[0] : value; // a composite FK given as a scalar holds only the target PK, written to the column that references it if (scalarColumn && !isRaw(scalar) && Utils.isPrimaryKey(scalar)) { addParams(prop, (fieldName === scalarColumn ? scalar : null) as Dictionary); } else { addParams(prop, prop.fieldNames.length > 1 ? value?.[fieldNameIdx] : value); } } }); sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `; return sql; }); } if (meta.ownsVersionProperty()) { const versionProperty = meta.properties[meta.versionProperty]; const quotedFieldName = this.platform.quoteIdentifier(versionProperty.fieldNames[0]); sql += `${quotedFieldName} = `; if (versionProperty.runtimeType === 'Date') { sql += this.platform.getCurrentTimestampSQL(versionProperty.length); } else { sql += `${quotedFieldName} + 1`; } sql += `, `; } sql = sql.substring(0, sql.length - 2); if (this.platform.usesOutputStatement() && returning.length > 0) { const fields = returning.flatMap(prop => prop.fieldNames); sql += ` output ${fields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}`; } sql += ' where '; const pkProps = meta.primaryKeys.concat(...meta.getOwnConcurrencyCheckKeys()); // an optimistically locked batch carries the version in every condition if ( meta.versionProperty && where.every(cond => Utils.isPlainObject(cond) && meta.versionProperty in (cond as Dictionary)) ) { pkProps.push(meta.versionProperty); } const pks = Utils.flatten(pkProps.map(pk => meta.properties[pk].fieldNames)); const useTupleIn = pks.length <= 1 || this.platform.allowsComparingTuples(); const condTemplate = useTupleIn ? `(${pks.map(() => '?').join(', ')})` : `(${pks.map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ')})`; const conds = where.flatMap(cond => { // with multiple PK columns the condition is looked up by property name, so it needs to stay an object if (pks.length === 1 && Utils.isPlainObject(cond) && Utils.getObjectKeysSize(cond) === 1) { cond = Object.values(cond)[0] as object; } if (pks.length > 1) { // a date version in sqlite matches either of its storage formats (see `convertVersionValue()`) const version = (cond as Dictionary)[meta.versionProperty]; const versions: unknown[] = version?.$in ?? [version]; return versions.map(v => { pkProps.forEach(pk => { const value = pk === meta.versionProperty ? v : cond[pk as keyof FilterQuery]; params.push(...(Array.isArray(value) ? Utils.flatten(value as any) : [value])); }); return condTemplate; }); } params.push(cond); return '?'; }); if (useTupleIn) { sql += pks.length > 1 ? `(${pks.map(pk => this.platform.quoteIdentifier(pk)).join(', ')})` : this.platform.quoteIdentifier(pks[0]); sql += ` in (${conds.join(', ')})`; } else { sql += conds.join(' or '); } if (this.platform.usesReturningStatement() && returning.length > 0) { const returningFields = returning.flatMap(prop => prop.fieldNames.map((field, idx) => this.getReturningFieldSQL(prop, field, idx)), ); sql += ` returning ${returningFields.join(', ')}`; } if (transform) { sql = transform(sql, params); } const res = await this.rethrow( this.execute>(sql, params, 'run', options.ctx, withAbortContext(options.loggerContext, options)), ); for (let i = 0; i < collections.length; i++) { const pk = Utils.getOrderedPrimaryKeys(where[i] as Record>, meta); await this.processManyToMany(meta, pk, collections[i], false, options); } return res; } async nativeDelete( entityName: EntityName, where: FilterQuery | string | any, options: DeleteOptions = {}, ): Promise> { const meta = this.metadata.get(entityName); const pks = this.getPrimaryKeyFields(meta); if (Utils.isPrimaryKey(where) && pks.length === 1) { where = { [pks[0]]: where }; } if (options.unionWhere?.length) { where = await this.applyUnionWhere(meta, where as ObjectQuery, options, true); } const qb = this.createQueryBuilder(entityName, options.ctx, 'write', false, options.loggerContext) .delete(where) .withSchema(this.getSchemaName(meta, options)); qb.setAbortOptions(pickAbortOptions(options)); return this.rethrow(qb.execute('run', false)); } /** * Fast comparison for collection snapshots that are represented by PK arrays. * Compares scalars via `===` and fallbacks to Utils.equals()` for more complex types like Buffer. * Always expects the same length of the arrays, since we only compare PKs of the same entity type. */ private comparePrimaryKeyArrays(a: unknown[], b: unknown[]) { for (let i = a.length; i-- !== 0;) { if (['number', 'string', 'bigint', 'boolean'].includes(typeof a[i])) { if (a[i] !== b[i]) { return false; } } else { if (!Utils.equals(a[i], b[i])) { return false; } } } return true; } override async syncCollections( collections: Iterable>, options?: DriverMethodOptions, ): Promise { const groups = {} as Dictionary>; for (const coll of collections) { const wrapped = helper(coll.owner); const meta = wrapped.__meta; const pks = wrapped.getPrimaryKeys(true)!; const snap = coll.getSnapshot(); const includes = (arr: T[][], item: T[]) => !!arr.find(i => this.comparePrimaryKeyArrays(i, item)); // For union-target polymorphic M:N, prepend the per-row discriminator value so the pivot // persister can write it alongside the FK id. Memoized per sync-run because a collection can // hold hundreds of items of the same few types, and findDiscriminatorValue walks the prototype // chain + re-scans Object.entries each call. const isUnionTargetMN = QueryHelper.isUnionTargetPolymorphic(coll.property); const classToDisc = new Map>(); const toDiff = (item: AnyEntity) => { const keys = helper(item).getPrimaryKeys(true)!; if (!isUnionTargetMN) { return keys; } let disc = classToDisc.get(item.constructor); if (!classToDisc.has(item.constructor)) { disc = QueryHelper.findDiscriminatorValue(coll.property.discriminatorMap!, item.constructor) as Primary; if (disc === undefined) { throw new Error( `Cannot resolve discriminator value for ${item.constructor.name} in ${coll.property.name}; the class is not part of the union target list.`, ); } classToDisc.set(item.constructor, disc); } return [disc as Primary, ...keys]; }; const snapshot = snap ? snap.map(toDiff) : []; const current = coll.getItems(false).map(toDiff); const deleteDiff = snap ? snapshot.filter(item => !includes(current, item)) : true; const insertDiff = current.filter(item => !includes(snapshot, item)); const target = snapshot.filter(item => includes(current, item)).concat(...insertDiff); const equals = Utils.equals(current, target); // wrong order if we just delete and insert to the end (only owning sides can have fixed order) if (coll.property.owner && coll.property.fixedOrder && !equals && Array.isArray(deleteDiff)) { deleteDiff.length = insertDiff.length = 0; for (const item of snapshot) { deleteDiff.push(item); } for (const item of current) { insertDiff.push(item); } } if (coll.property.kind === ReferenceKind.ONE_TO_MANY) { const cols = coll.property.referencedColumnNames; const qb = this.createQueryBuilder(coll.property.targetMeta!.class, options?.ctx, 'write').withSchema( this.getSchemaName(meta, options), ); qb.setAbortOptions(pickAbortOptions(options)); if (coll.getSnapshot() === undefined) { if (coll.property.orphanRemoval) { const query = qb .delete({ [coll.property.mappedBy]: pks }) .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } }); await this.rethrow(query.execute()); continue; } const query = qb .update({ [coll.property.mappedBy]: null }) .where({ [coll.property.mappedBy]: pks }) .andWhere({ [cols.join(Utils.PK_SEPARATOR)]: { $nin: insertDiff } }); await this.rethrow(query.execute()); continue; } /* v8 ignore next */ const query = qb .update({ [coll.property.mappedBy]: pks }) .where({ [cols.join(Utils.PK_SEPARATOR)]: { $in: insertDiff } }); await this.rethrow(query.execute()); continue; } const pivotMeta = this.metadata.find(coll.property.pivotEntity)!; let schema = pivotMeta.schema; if (schema === '*') { if (coll.property.owner) { schema = wrapped.getSchema() === '*' ? (options?.schema ?? this.config.get('schema')) : wrapped.getSchema(); } else { const targetMeta = coll.property.targetMeta!; const targetSchema = (coll[0] ?? snap?.[0]) && helper(coll[0] ?? snap?.[0]).getSchema(); schema = targetMeta.schema === '*' ? (options?.schema ?? targetSchema ?? this.config.get('schema')) : targetMeta.schema; } } else if (schema == null) { schema = this.config.get('schema'); } const tableName = `${schema ?? '_'}.${pivotMeta.tableName}`; const persister = (groups[tableName] ??= new PivotCollectionPersister( pivotMeta, this, options?.ctx, schema, options?.loggerContext, pickAbortOptions(options), )); persister.enqueueUpdate(coll.property, insertDiff, deleteDiff, pks, coll.isInitialized()); } for (const persister of Utils.values(groups)) { await this.rethrow(persister.execute()); } } override async loadFromPivotTable( prop: EntityProperty, owners: Primary[][], where: FilterQuery = {} as FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, pivotJoin?: boolean, ): Promise> { /* v8 ignore next */ if (owners.length === 0) { return {}; } // The pivot order is recomputed via `getPivotOrderBy`, so the parent `populateOrderBy` must not leak // into the pivot subquery — its keys reference the parent entity, not the pivot (GH #7910). if (options?.populateOrderBy != null) { options = { ...options, populateOrderBy: undefined }; } const pivotMeta = this.metadata.get(prop.pivotEntity); if (prop.discriminatorColumn && QueryHelper.isUnionTargetPolymorphic(prop)) { return this.loadFromUnionTargetPolymorphicPivotTable(prop, owners, where, orderBy, ctx, options, pivotJoin); } if (prop.polymorphic && prop.discriminatorColumn && prop.discriminatorValue) { return this.loadFromPolymorphicPivotTable(prop, owners, where, orderBy, ctx, options, pivotJoin); } const pivotProp1 = pivotMeta.relations[prop.owner ? 1 : 0]; const pivotProp2 = pivotMeta.relations[prop.owner ? 0 : 1]; const ownerMeta = pivotProp2.targetMeta as EntityMetadata; const { ownerPks, needsConversion, pkProp } = this.convertOwnerPksForPivotQuery(owners, ownerMeta); const cond = { [pivotProp2.name]: { $in: ownerPks }, }; if (!Utils.isEmpty(where)) { cond[pivotProp1.name] = { ...where }; } where = cond as FilterQuery; const populateField = pivotJoin ? `${pivotProp1.name}:ref` : (pivotProp1.name as EntityKey); const populate = this.autoJoinOneToOneOwner( prop.targetMeta!, (options?.populate as PopulateOptions[]) ?? [], options?.fields, ); const childFields = !Utils.isEmpty(options?.fields) ? options!.fields!.map(f => `${pivotProp1.name}.${f}`) : []; const childExclude = !Utils.isEmpty(options?.exclude) ? options!.exclude!.map(f => `${pivotProp1.name}.${f}`) : []; const fields = pivotJoin ? ([pivotProp1.name, pivotProp2.name] as any[]) : [pivotProp1.name, pivotProp2.name, ...childFields]; const pivotFindOptions: Dictionary = { ctx, ...options, fields, exclude: childExclude as any[], orderBy: this.getPivotOrderBy(prop, pivotProp1, orderBy, options?.orderBy), populate: [ { field: populateField, strategy: LoadStrategy.JOINED, joinType: JoinType.innerJoin, children: populate, dataOnly: pivotProp1.mapToPk && !pivotJoin, } as any, ], populateWhere: undefined, _populateWhere: 'infer', populateFilter: this.wrapPopulateFilter(options, pivotProp1.name), }; if (pivotFindOptions._partitionLimit) { pivotFindOptions._partitionLimit.partitionBy = pivotProp2.name; } const res = await this.find(pivotMeta.class, where, pivotFindOptions); // Convert result FK values back to JS format so key hashing // in buildPivotResultMap is consistent with the owner keys. if (needsConversion) { for (const item of res) { const fk = (item as any)[pivotProp2.name]; if (fk != null) { (item as any)[pivotProp2.name] = pkProp.customType!.convertToJSValue(fk, this.platform); } } } return this.buildPivotResultMap(owners, res, pivotProp2.name, pivotProp1.name, ownerMeta); } /** * Load from a polymorphic M:N pivot table. */ protected async loadFromPolymorphicPivotTable( prop: EntityProperty, owners: Primary[][], where: FilterQuery = {} as FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, pivotJoin?: boolean, ): Promise> { const pivotMeta = this.metadata.get(prop.pivotEntity); // Find the M:1 relation on the pivot pointing to the target entity. // We exclude virtual polymorphic owner relations (persist: false) and non-M:1 relations. const inverseProp = pivotMeta.relations.find( r => r.kind === ReferenceKind.MANY_TO_ONE && r.persist !== false && r.targetMeta === prop.targetMeta, ); if (inverseProp) { return this.loadPolymorphicPivotOwnerSide(prop, owners, where, orderBy, ctx, options, pivotJoin, inverseProp); } return this.loadPolymorphicPivotInverseSide(prop, owners, where, orderBy, ctx, options); } /** * Load from owner side of polymorphic M:N (e.g., Post -> Tags) */ protected async loadPolymorphicPivotOwnerSide( prop: EntityProperty, owners: Primary[][], where: FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, pivotJoin?: boolean, inverseProp?: EntityProperty, ): Promise> { const pivotMeta = this.metadata.get(prop.pivotEntity); const targetMeta = prop.targetMeta!; // `prop.discriminator` spans all owner FK columns but carries no target metadata, so a composite // owner PK neither expands to a tuple condition nor gets mapped back; the virtual M:1 relation // to this discriminator's owner describes the same columns as an actual relation const ownerMeta = this.metadata.get(pivotMeta.polymorphicDiscriminatorMap![prop.discriminatorValue!]); const ownerProp = pivotMeta.properties[`${prop.discriminator}_${ownerMeta.tableName}`]; // Build condition: discriminator = 'post' AND {owner} IN (...) const cond: Dictionary = { [prop.discriminatorColumn!]: prop.discriminatorValue, [ownerProp.name]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners }, }; if (!Utils.isEmpty(where)) { cond[inverseProp!.name] = { ...where }; } const populateField = pivotJoin ? `${inverseProp!.name}:ref` : (inverseProp!.name as EntityKey); const populate = this.autoJoinOneToOneOwner( targetMeta, (options?.populate as PopulateOptions[]) ?? [], options?.fields, ); const childFields = !Utils.isEmpty(options?.fields) ? options!.fields!.map(f => `${inverseProp!.name}.${f}`) : []; const childExclude = !Utils.isEmpty(options?.exclude) ? options!.exclude!.map(f => `${inverseProp!.name}.${f}`) : []; // the owner relation is virtual, so its FK columns have to be selected via the pivot props that // cover them; only the first owner of a shared pivot gets the flat prop named after the // discriminator, and it keeps that owner's columns, so later owners get per-column props instead const ownerFields = Utils.unique( prop.joinColumns.map(col => (pivotMeta.properties[col] ? col : prop.discriminator!)), ); const fields = pivotJoin ? ([inverseProp!.name, ...ownerFields, prop.discriminatorColumn!] as any[]) : [inverseProp!.name, ...ownerFields, prop.discriminatorColumn!, ...childFields]; const res = await this.find(pivotMeta.class, cond as FilterQuery, { ctx, ...options, fields, exclude: childExclude as any[], orderBy: this.getPivotOrderBy(prop, inverseProp!, orderBy, options?.orderBy), populate: [ { field: populateField, strategy: LoadStrategy.JOINED, joinType: JoinType.innerJoin, children: populate, dataOnly: inverseProp!.mapToPk && !pivotJoin, } as any, ], populateWhere: undefined, // @ts-ignore _populateWhere: 'infer', populateFilter: this.wrapPopulateFilter(options, inverseProp!.name), }); return this.buildPivotResultMap(owners, res, ownerProp.name, inverseProp!.name, ownerMeta); } /** * Load from inverse side of polymorphic M:N (e.g., Tag -> Posts) * Uses single query with join via virtual relation on pivot. */ protected async loadPolymorphicPivotInverseSide( prop: EntityProperty, owners: Primary[][], where: FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, ): Promise> { const pivotMeta = this.metadata.get(prop.pivotEntity); const targetMeta = prop.targetMeta!; // Find the relation to the entity we're starting from (e.g., Tag_inverse -> Tag) // Exclude virtual polymorphic owner relations (persist: false) - we want the actual M:N inverse relation const tagProp = pivotMeta.relations.find(r => r.persist !== false && r.targetMeta !== targetMeta)!; // Find the virtual relation to the polymorphic owner (e.g., taggable_Post -> Post) const ownerRelationName = `${prop.discriminator}_${targetMeta.tableName}`; const ownerProp = pivotMeta.properties[ownerRelationName]; // Build condition: discriminator = 'post' AND Tag_inverse IN (tagIds) const cond: Dictionary = { [prop.discriminatorColumn!]: prop.discriminatorValue, [tagProp.name]: { $in: owners.length === 1 && owners[0].length === 1 ? owners.map(o => o[0]) : owners }, }; if (!Utils.isEmpty(where)) { cond[ownerRelationName] = { ...where }; } const populateField = ownerRelationName as EntityKey; const populate = this.autoJoinOneToOneOwner( targetMeta, (options?.populate as PopulateOptions[]) ?? [], options?.fields, ); const childFields = !Utils.isEmpty(options?.fields) ? options!.fields!.map(f => `${ownerRelationName}.${f}`) : []; const childExclude = !Utils.isEmpty(options?.exclude) ? options!.exclude!.map(f => `${ownerRelationName}.${f}`) : []; const fields = [ownerRelationName, tagProp.name, prop.discriminatorColumn!, ...childFields] as any[]; const res = await this.find(pivotMeta.class, cond as FilterQuery, { ctx, ...options, fields, exclude: childExclude as any[], orderBy: this.getPivotOrderBy(prop, ownerProp, orderBy, options?.orderBy), populate: [ { field: populateField, strategy: LoadStrategy.JOINED, joinType: JoinType.innerJoin, children: populate, } as any, ], populateWhere: undefined, // @ts-ignore _populateWhere: 'infer', populateFilter: this.wrapPopulateFilter(options, ownerRelationName), }); return this.buildPivotResultMap(owners, res, tagProp.name, ownerRelationName, tagProp.targetMeta); } /** * Load a union-target polymorphic M:N pivot (e.g. Post.attachments -> Image | Video). * Each pivot row's discriminator column selects which target table to hydrate. */ protected async loadFromUnionTargetPolymorphicPivotTable( prop: EntityProperty, owners: Primary[][], where: FilterQuery = {} as FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options: FindOptions = {} as FindOptions, pivotJoin?: boolean, ): Promise> { // :ref hints cannot be honored for union-target — EntityLoader.getReference needs a concrete // class per item, but the ref-mode map only carries flat PK values and would hydrate every // row as the first polymorph target. Fail loudly instead of silently corrupting the collection. if (pivotJoin) { throw new Error( `The ':ref' populate hint is not supported for union-target polymorphic M:N on ${prop.name}. Use a regular populate hint instead.`, ); } const pivotMeta = this.metadata.get(prop.pivotEntity); const targets = prop.polymorphTargets!; const ownerProp = pivotMeta.relations.find(r => r.persist !== false && !r.polymorphic)!; const discriminatorColumn = prop.discriminatorColumn!; const ownerMeta = ownerProp.targetMeta as EntityMetadata; const { ownerPks, needsConversion, pkProp } = this.convertOwnerPksForPivotQuery(owners, ownerMeta); const pivotRows = (await this.find(pivotMeta.class, { [ownerProp.name]: { $in: ownerPks } } as any, { ctx, orderBy: this.getPivotOrderBy(prop, ownerProp, orderBy, options?.orderBy), fields: [ownerProp.name, discriminatorColumn, prop.discriminator!] as any[], populateWhere: undefined, // @ts-ignore _populateWhere: 'infer', })) as EntityData[]; /* v8 ignore next 7 - custom-type PK conversion, tested via loadFromPivotTable path */ if (needsConversion) { for (const item of pivotRows) { const fk = (item as any)[ownerProp.name]; if (fk != null) { (item as any)[ownerProp.name] = pkProp.customType!.convertToJSValue(fk, this.platform); } } } const classMeta = new Map(targets.map(t => [t.class, t])); const rowsByTarget = new Map[]>(); for (const row of pivotRows) { const discValue = (row as Dictionary)[discriminatorColumn] as string; const targetClass = prop.discriminatorMap![discValue]; const targetMeta = classMeta.get(targetClass as any); /* v8 ignore next 3 - defensive: unknown discriminator value */ if (!targetMeta) { continue; } const list = rowsByTarget.get(targetMeta) ?? []; list.push(row); rowsByTarget.set(targetMeta, list); } // Strip the outer find's orderBy/fields/exclude before bulk-loading targets by PK — those apply // to the owner query, not each polymorph target (Image and Video wouldn't share an orderBy field). // populateFilter is a filter on the populated collection; since union-target splits the pivot // and target queries, we merge it into the target-level `where` instead of wrapping it on the // pivot query (where joins to target tables aren't available). // Hoisted above the loop since `options` doesn't change per target. const { orderBy: _o, fields: _f, exclude: _e, populateFilter, ...childOptions } = options as Dictionary; const populate = (options.populate as PopulateOptions[]) ?? []; const orphanedRows = new Set>(); for (const [targetMeta, rows] of rowsByTarget) { const targetIds = rows.map(r => (r as Dictionary)[prop.discriminator!]); // Union-target pivot stores one scalar FK per row; composite-PK targets are rejected at // metadata validation time, so a single primary key column is guaranteed here. const pkCol = targetMeta.primaryKeys[0]; let cond: Dictionary = { [pkCol]: { $in: targetIds } }; if (!Utils.isEmpty(where)) { cond = { $and: [cond, where] }; } if (!Utils.isEmpty(populateFilter)) { cond = { $and: [cond, populateFilter] }; } const results = (await this.find(targetMeta.class, cond as FilterQuery, { ctx, ...childOptions, populate: populate as any, })) as EntityData[]; const byPk = new Map>(); for (const row of results) { Object.defineProperty(row, 'constructor', { value: targetMeta.class, enumerable: false, configurable: true, }); byPk.set(Utils.getPrimaryKeyHash([(row as Dictionary)[pkCol]] as string[]), row); } for (const row of rows) { const pkHash = Utils.getPrimaryKeyHash([(row as Dictionary)[prop.discriminator!]] as string[]); const entity = byPk.get(pkHash); if (entity == null) { orphanedRows.add(row); continue; } (row as Dictionary)[prop.discriminator!] = entity; } } const result = orphanedRows.size > 0 ? pivotRows.filter(r => !orphanedRows.has(r)) : pivotRows; return this.buildPivotResultMap(owners, result, ownerProp.name, prop.discriminator!, ownerMeta); } /** * Build a map from owner PKs to their related entities from pivot table results. */ private buildPivotResultMap( owners: Primary[][], results: object[], keyProp: string, valueProp: string, ownerMeta?: EntityMetadata, ): Dictionary { const map: Dictionary = {}; for (const owner of owners) { const key = Utils.getPrimaryKeyHash(owner as string[]); map[key] = []; } for (const item of results) { const fk = (item as any)[keyProp]; // the owner PKs are always flat, while the pivot FK follows the owner PK structure, // so a PK built from a relation to another composite PK entity needs flattening too const pks = ownerMeta && fk != null ? Utils.getOrderedPrimaryKeys(fk, ownerMeta) : Utils.asArray(fk); const key = Utils.getPrimaryKeyHash(pks as string[]); const entity = (item as any)[valueProp] as T; if (map[key]) { map[key].push(entity); } } return map; } private wrapPopulateFilter(options: FindOptions | undefined, propName: string): any { if (!Utils.isEmpty(options?.populateFilter) || RawQueryFragment.hasObjectFragments(options?.populateFilter)) { return { [propName]: options?.populateFilter } as any; } return undefined; } /** * The pivot query builder doesn't convert custom types — manually convert owner PKs to the DB * representation. Returns `needsConversion` + `pkProp` so the caller can convert result FKs back * to JS format for consistent key hashing in `buildPivotResultMap`. */ private convertOwnerPksForPivotQuery( owners: Primary[][], ownerMeta: EntityMetadata, ): { ownerPks: Primary[] | Primary[][]; needsConversion: boolean; pkProp: EntityProperty } { const pkProp = ownerMeta.properties[ownerMeta.primaryKeys[0]]; const needsConversion = !!pkProp?.customType?.ensureComparable(ownerMeta, pkProp) && !ownerMeta.compositePK; let ownerPks: Primary[] | Primary[][] = ownerMeta.compositePK ? owners : owners.map(o => o[0]); /* v8 ignore next 4 - custom-type PK conversion, tested via loadFromPivotTable path */ if (needsConversion) { ownerPks = (ownerPks as Primary[]).map(v => pkProp.customType!.convertToDatabaseValue(v, this.platform, { mode: 'query' }), ); } return { ownerPks, needsConversion, pkProp }; } private getPivotOrderBy( prop: EntityProperty, pivotProp: EntityProperty, orderBy?: OrderDefinition, parentOrderBy?: OrderDefinition, ): QueryOrderMap[] { if (!Utils.isEmpty(orderBy) || RawQueryFragment.hasObjectFragments(orderBy)) { return Utils.asArray(orderBy).map(o => ({ [pivotProp.name]: o }) as QueryOrderMap); } if ( prop.kind === ReferenceKind.MANY_TO_MANY && Utils.asArray(parentOrderBy).some(o => !Utils.isEmpty(o[prop.name])) ) { return Utils.asArray(parentOrderBy) .filter(o => !Utils.isEmpty(o[prop.name])) .map(o => ({ [pivotProp.name]: o[prop.name] }) as QueryOrderMap); } if (!Utils.isEmpty(prop.orderBy) || RawQueryFragment.hasObjectFragments(prop.orderBy)) { return Utils.asArray(prop.orderBy).map(o => ({ [pivotProp.name]: o }) as QueryOrderMap); } if (prop.fixedOrder) { return [{ [prop.fixedOrderColumn!]: QueryOrder.ASC } as QueryOrderMap]; } return []; } async execute | EntityData[] = EntityData[]>( query: string | NativeQueryBuilder | RawQueryFragment, params: any[] | Dictionary = [], method: 'all' | 'get' | 'run' = 'all', ctx?: Transaction, loggerContext?: LoggingOptions, connection: AbstractSqlConnection = this.connection, ): Promise { return this.rethrow(connection.execute(query, params, method, ctx, loggerContext)); } async *stream( entityName: EntityName, where: FilterQuery, options: StreamOptions, ): AsyncIterableIterator { options = { populate: [], orderBy: [], ...options }; const meta = this.metadata.get(entityName); if (meta.virtual) { yield* this.streamFromVirtual(entityName, where, options as any) as AsyncIterableIterator; return; } const qb = await this.createQueryBuilderFromOptions(meta, where, options); try { const result = qb.stream(options); for await (const item of result) { yield item as T; } } catch (e) { throw this.convertException(e as Error); } } /** * 1:1 owner side needs to be marked for population so QB auto-joins the owner id */ protected autoJoinOneToOneOwner( meta: EntityMetadata, populate: PopulateOptions[], fields: readonly EntityField[] = [], ): PopulateOptions[] { if (!this.config.get('autoJoinOneToOneOwner')) { return populate; } const relationsToPopulate = populate.map(({ field }) => field.split(':')[0]); const toPopulate: PopulateOptions[] = meta.relations .filter( prop => prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner && !prop.lazy && !relationsToPopulate.includes(prop.name), ) .filter(prop => fields.length === 0 || fields.some(f => prop.name === f || prop.name.startsWith(`${String(f)}.`))) .map(prop => ({ field: `${prop.name}:ref` as any, strategy: LoadStrategy.JOINED })); return [...populate, ...toPopulate]; } /** * @internal */ joinedProps( meta: EntityMetadata, populate: readonly PopulateOptions[], options?: { strategy?: Options['loadStrategy'] }, ): PopulateOptions[] { return populate.filter(hint => { const [propName, ref] = hint.field.split(':', 2); const prop = meta.properties[propName] || {}; const strategy = getLoadingStrategy( hint.strategy || prop.strategy || options?.strategy || this.config.get('loadStrategy'), prop.kind, ); if (ref && [ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) { return true; } // Union-target polymorphic M:N cannot be loaded via a single JOIN because rows span multiple // target tables; fall through to SELECT_IN which dispatches through `loadFromPivotTable`. // Polymorphic M:1 (to-one with target_type discriminator) is handled via LEFT JOINs elsewhere. if (prop.kind === ReferenceKind.MANY_TO_MANY && QueryHelper.isUnionTargetPolymorphic(prop) && prop.owner) { return false; } // skip redundant joins for 1:1 owner population hints when using `mapToPk` if (prop.kind === ReferenceKind.ONE_TO_ONE && prop.mapToPk && prop.owner) { return false; } // Polymorphic to-one flattened from an object embeddable lives inside a JSON column, so the join // conditions would need JSON extraction for both the discriminator and the FK; fall back to SELECT_IN. if (prop.polymorphic && prop.object && prop.embedded) { return false; } if (strategy !== LoadStrategy.JOINED) { // force joined strategy for explicit 1:1 owner populate hint as it would require a join anyway return prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner; } return ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind); }); } /** * @internal */ mergeJoinedResult( rawResults: EntityData[], meta: EntityMetadata, joinedProps: PopulateOptions[], ): EntityData[] { if (rawResults.length <= 1) { return rawResults; } const res: EntityData[] = []; const map: Dictionary> = {}; const collectionsToMerge: Dictionary[]>> = {}; const hints = joinedProps.map(hint => { const [propName, ref] = hint.field.split(':', 2) as [EntityKey, string | undefined]; return { propName, ref, children: hint.children }; }); // with `fixedOrder` the pivot PK is the order column, which is not guaranteed to be unique when the // pivot table is managed externally, so we disambiguate the rows by their FKs on top of the PK // (including virtual ones, as the owner FK of a polymorphic pivot is only mapped via non-persisted relations) const pivotRelations = meta.pivotTable && !meta.compositePK ? meta.relations.filter(p => p.kind === ReferenceKind.MANY_TO_ONE) : []; for (const item of rawResults) { // flat hash, so nested composite PK values keep their own separators and cannot collide let pk = Utils.getCompositeKeyHash(item, meta, false, undefined, true); if (pivotRelations.length > 0) { pk = Utils.getPrimaryKeyHash([ pk, ...pivotRelations.flatMap(p => { const value = item[p.name as EntityKey]; // composite FKs are mapped to an array of values, which `extractPK` does not accept return (Array.isArray(value) ? Utils.flatten(value, true) : Utils.extractPK(value, p.targetMeta)) as | string | string[]; }), ]); } if (map[pk]) { for (const { propName } of hints) { if (!item[propName]) { continue; } collectionsToMerge[pk] ??= {}; collectionsToMerge[pk][propName] ??= [map[pk][propName] as EntityData]; collectionsToMerge[pk][propName].push(item[propName] as EntityData); } } else { map[pk] = item; res.push(item); } } for (const pk in collectionsToMerge) { const entity = map[pk]; const collections = collectionsToMerge[pk]; for (const { propName, ref, children } of hints) { if (!collections[propName]) { continue; } const prop = meta.properties[propName]; const items = collections[propName].flat() as EntityData[]; if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && ref) { entity[propName] = items as EntityDataValue; continue; } switch (prop.kind) { case ReferenceKind.ONE_TO_MANY: case ReferenceKind.MANY_TO_MANY: entity[propName] = this.mergeJoinedResult( items, prop.targetMeta!, (children as any) ?? [], ) as EntityDataValue; break; case ReferenceKind.MANY_TO_ONE: case ReferenceKind.ONE_TO_ONE: entity[propName] = this.mergeJoinedResult( items, prop.targetMeta!, (children as any) ?? [], )[0] as EntityDataValue; break; } } } return res; } protected shouldHaveColumn( meta: EntityMetadata, prop: EntityProperty, populate: readonly PopulateOptions[], fields?: readonly InternalField[], exclude?: readonly InternalField[], ): boolean { if (!this.platform.shouldHaveColumn(prop, populate, exclude as string[])) { return false; } if ( !fields || fields.includes('*') || prop.primary || meta.root.discriminatorColumn === prop.name || meta.root.targetKeys?.includes(prop.name as EntityKey) ) { return true; } return fields.some(f => f === prop.name || f.toString().startsWith(prop.name + '.')); } protected getFieldsForJoinedLoad( qb: AnyQueryBuilder, meta: EntityMetadata, options: FieldsForJoinedLoadOptions, ): InternalField[] { const fields: InternalField[] = []; const populate = options.populate ?? []; const joinedProps = this.joinedProps(meta, populate, options); const populateWhereAll = (options as Dictionary)?._populateWhere === 'all' || Utils.isEmpty((options as Dictionary)?._populateWhere); // Ensure TPT joins are applied early so that _tptAlias is available for join resolution // This is needed when populating relations that are inherited from TPT parent entities if (!options.parentJoinPath) { qb.ensureTPTJoins(); } // root entity is already handled, skip that if (options.parentJoinPath) { // alias all fields in the primary table meta.props // flattened children of inline embeddables are expanded via their parent, iterating them too would select the columns twice .filter(prop => !prop.embedded) .filter(prop => this.shouldHaveColumn(meta, prop, populate, options.explicitFields, options.exclude)) .forEach(prop => fields.push( ...this.mapPropToFieldNames( qb, prop, options.parentTableAlias, meta, options.schema, options.explicitFields, ), ), ); } for (const hint of joinedProps) { const [propName, ref] = hint.field.split(':', 2) as [EntityKey, string | undefined]; const prop = meta.properties[propName]; // Polymorphic to-one: create a LEFT JOIN per target type // Skip regular :ref hints — polymorphic to-one already has FK + discriminator in the row // But allow filter :ref hints through to create per-target LEFT JOINs with filter checks if ( prop.polymorphic && prop.polymorphTargets?.length && (!ref || hint.filter) && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) ) { const basePath = options.parentJoinPath ? `${options.parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`; const pathPrefix = !options.parentJoinPath && populateWhereAll && !basePath.startsWith('[populate]') ? '[populate]' : ''; for (const targetMeta of prop.polymorphTargets) { const tableAlias = qb.getNextAlias(targetMeta.className); const targetPath = `${pathPrefix}${basePath}[${targetMeta.className}]`; const schema = targetMeta.schema === '*' ? (options?.schema ?? this.config.get('schema')) : targetMeta.schema; qb.addPolymorphicJoin( prop, targetMeta as EntityMetadata, options.parentTableAlias, tableAlias, JoinType.leftJoin, targetPath, schema, ); // For polymorphic targets that are TPT child entities, INNER JOIN parent tables so that // filter conditions referencing parent-table columns resolve to the correct alias. The // INNER JOINs get nested inside the polymorphic LEFT JOIN by processNestedJoins, which // keeps the resulting query valid for rows pointing to other polymorphic targets. if (targetMeta.inheritanceType === 'tpt' && targetMeta.tptParent) { qb.addTPTParentJoins(targetMeta, tableAlias, targetPath); } // For polymorphic targets that are TPT base classes, also LEFT JOIN // all descendant tables so child-specific fields can be selected. if (targetMeta.inheritanceType === 'tpt' && targetMeta.tptChildren?.length && !ref) { const tptMeta = this.metadata.get(targetMeta.class); this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields); } // target filters apply per target, both for filter :ref hints and populated relations qb.scheduleFilterCheck(targetPath); if (!ref) { // Select fields from each target table fields.push( ...this.getFieldsForJoinedLoad(qb, targetMeta as EntityMetadata, { ...options, populate: hint.children as any, parentTableAlias: tableAlias, parentJoinPath: targetPath, }), ); } } continue; } // ignore ref joins of known FKs unless it's a filter hint if ( ref && !hint.filter && (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner)) ) { continue; } const meta2 = prop.targetMeta as EntityMetadata; const pivotRefJoin = prop.kind === ReferenceKind.MANY_TO_MANY && ref && !hint.filter; const tableAlias = qb.getNextAlias(prop.name); const field = `${options.parentTableAlias}.${prop.name}`; let path = options.parentJoinPath ? `${options.parentJoinPath}.${prop.name}` : `${meta.name}.${prop.name}`; if (!options.parentJoinPath && populateWhereAll && !hint.filter && !path.startsWith('[populate]')) { path = '[populate]' + path; } const mandatoryToOneProperty = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.nullable; const joinType = pivotRefJoin ? JoinType.pivotJoin : hint.joinType ? (hint.joinType as JoinType) : (hint.filter && !prop.nullable && prop.kind !== ReferenceKind.MANY_TO_MANY) || mandatoryToOneProperty ? JoinType.innerJoin : JoinType.leftJoin; const schema = prop.targetMeta!.schema === '*' ? (options?.schema ?? this.config.get('schema')) : prop.targetMeta!.schema; qb.join(field as any, tableAlias, {}, joinType, path, schema); // For relations to TPT base classes, add LEFT JOINs for all child tables (polymorphic loading) if (meta2.inheritanceType === 'tpt' && meta2.tptChildren?.length && !ref) { // Use the registry metadata to ensure allTPTDescendants is available const tptMeta = this.metadata.get(meta2.class); this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields); } if (pivotRefJoin) { fields.push( ...prop.joinColumns.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`), ), ...prop.inverseJoinColumns.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`), ), ); } if (prop.kind === ReferenceKind.ONE_TO_MANY && ref) { fields.push( ...this.getFieldsForJoinedLoad(qb, meta2, { ...options, explicitFields: prop.referencedColumnNames, exclude: undefined, populate: hint.children as any, parentTableAlias: tableAlias, parentJoinPath: path, }), ); } const childExplicitFields = options.explicitFields?.filter(f => Utils.isPlainObject(f)).map(o => (o as Dictionary)[prop.name])[0] || []; options.explicitFields?.forEach(f => { if (typeof f === 'string' && f.startsWith(`${prop.name}.`)) { childExplicitFields.push(f.substring(prop.name.length + 1)); } }); const childExclude = options.exclude ? Utils.extractChildElements(options.exclude as string[], prop.name) : options.exclude; if (!ref && (!prop.mapToPk || hint.dataOnly)) { fields.push( ...this.getFieldsForJoinedLoad(qb, meta2, { ...options, explicitFields: childExplicitFields.length === 0 ? undefined : childExplicitFields, exclude: childExclude, populate: hint.children as any, parentTableAlias: tableAlias, parentJoinPath: path, }), ); } else if ( hint.filter || (prop.mapToPk && !hint.dataOnly) || (ref && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) ) { fields.push( ...prop.referencedColumnNames.map(col => qb.helper.mapper(`${tableAlias}.${col}`, qb.type, undefined, `${tableAlias}__${col}`), ), ); } } return fields; } /** * Adds LEFT JOINs and fields for TPT polymorphic loading when populating a relation to a TPT base class. * @internal */ protected addTPTPolymorphicJoinsForRelation( qb: AnyQueryBuilder, meta: EntityMetadata, baseAlias: string, fields: InternalField[], ): void { // allTPTDescendants is pre-computed during discovery, sorted by depth (deepest first) const descendants = meta.allTPTDescendants!; const childAliases: Dictionary = {}; // LEFT JOIN each descendant table for (const childMeta of descendants) { const childAlias = qb.getNextAlias(childMeta.className); qb.createAlias(childMeta.class, childAlias); childAliases[childMeta.className] = childAlias; qb.addPropertyJoin(childMeta.tptInverseProp!, baseAlias, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`); } this.registerTPTAncestorAliases(qb, meta, baseAlias, childAliases); for (const childMeta of descendants) { const childAlias = childAliases[childMeta.className]; // Add fields from this child (only ownProps, skip PKs) const schema = childMeta.schema === '*' ? '*' : this.getSchemaName(childMeta); childMeta .ownProps!.filter(p => !p.primary && !p.embedded && this.platform.shouldHaveColumn(p, [])) .forEach(prop => fields.push(...(this.mapPropToFieldNames(qb, prop, childAlias, childMeta, schema) as InternalField[])), ); } // Add computed discriminator (descendants already sorted by depth) if (meta.root.tptDiscriminatorColumn) { fields.push(this.buildTPTDiscriminatorExpression(meta, descendants, childAliases, baseAlias)); } } /** * Registers the ancestor table aliases of each polymorphically joined TPT descendant, * so formulas on descendants resolve inherited columns to the table that owns them. * @internal */ registerTPTAncestorAliases( qb: AnyQueryBuilder, meta: EntityMetadata, baseAlias: string, childAliases: Dictionary, ): void { const tptAlias = qb.state.tptAlias; for (const childMeta of meta.allTPTDescendants!) { for (let parent = childMeta.tptParent; parent; parent = parent.tptParent) { tptAlias[`${childAliases[childMeta.className]}:${parent.className}`] = childAliases[parent.className] ?? (parent === meta ? baseAlias : tptAlias[`${baseAlias}:${parent.className}`]); } } } /** * Find the alias for a TPT child table in the query builder. * @internal */ protected findTPTChildAlias(qb: AnyQueryBuilder, childMeta: EntityMetadata): string | undefined { const joins = qb.state.joins as Dictionary; for (const key of Object.keys(joins)) { if (joins[key].table === childMeta.tableName && key.includes('[tpt]')) { return joins[key].alias; } } return undefined; } /** * Builds a CASE WHEN expression for TPT discriminator. * Determines concrete entity type based on which child table has a non-null PK. * @internal */ buildTPTDiscriminatorExpression( meta: EntityMetadata, descendants: EntityMetadata[], aliasMap: Dictionary, baseAlias: string, ): Raw { const cases = descendants.map(child => { const childAlias = aliasMap[child.className]; const pkFieldName = child.properties[child.primaryKeys[0]].fieldNames[0]; return `when ${this.platform.quoteIdentifier(`${childAlias}.${pkFieldName}`)} is not null then '${child.discriminatorValue}'`; }); const defaultValue = meta.abstract ? 'null' : `'${meta.discriminatorValue}'`; const caseExpr = `case ${cases.join(' ')} else ${defaultValue} end`; const aliased = this.platform.quoteIdentifier(`${baseAlias}__${meta.root.tptDiscriminatorColumn}`); return raw(`${caseExpr} as ${aliased}`); } /** * Maps TPT child-specific fields during hydration. * When a relation points to a TPT base class, the actual entity might be a child class. * This method reads the discriminator to determine the concrete type and maps child-specific fields. * @internal */ protected mapTPTChildFields( relationPojo: EntityData, meta: EntityMetadata, relationAlias: string, qb: AnyQueryBuilder, root: EntityData, ): EntityMetadata | undefined { if (meta.inheritanceType !== 'tpt' || !meta.root.tptDiscriminatorColumn) { return; } const discriminatorAlias = `${relationAlias}__${meta.root.tptDiscriminatorColumn}` as EntityKey; const discriminatorValue = root[discriminatorAlias] as string; if (!discriminatorValue) { return; } relationPojo[meta.root.tptDiscriminatorColumn as EntityKey] = discriminatorValue as EntityDataValue; const concreteClass = meta.root.discriminatorMap?.[discriminatorValue]; /* v8 ignore next 3 - defensive check for invalid discriminator values */ if (!concreteClass) { return; } const concreteMeta = this.metadata.get(concreteClass); delete root[discriminatorAlias]; if (concreteMeta === meta) { return concreteMeta; } // Traverse up from concrete type and map fields from each level's table const tz = this.platform.getTimezone(); let currentMeta: EntityMetadata | undefined = concreteMeta; while (currentMeta && currentMeta !== meta) { const childAlias = this.findTPTChildAlias(qb, currentMeta); if (childAlias) { // Map fields using same filtering as joined loading, plus skip PKs for (const prop of currentMeta.ownProps!.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) { this.mapJoinedProp( relationPojo, prop, this.aliasedKeys(prop, childAlias), root, tz, currentMeta as EntityMetadata, { deleteFromRoot: true, }, ); } } currentMeta = currentMeta.tptParent; } return concreteMeta; } /** * @internal */ mapPropToFieldNames( qb: AnyQueryBuilder, prop: EntityProperty, tableAlias: string, meta: EntityMetadata, schema?: string, explicitFields?: readonly InternalField[], ): InternalField[] { if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) { return Object.entries(prop.embeddedProps).flatMap(([name, childProp]) => { const childFields = explicitFields ? Utils.extractChildElements(explicitFields as string[], prop.name) : []; if ( !this.shouldHaveColumn( prop.targetMeta!, { ...childProp, name }, [], childFields.length > 0 ? childFields : undefined, ) ) { return []; } return this.mapPropToFieldNames(qb, childProp, tableAlias, meta, schema, childFields); }); } const aliased = this.platform.quoteIdentifier(`${tableAlias}__${prop.fieldNames[0]}`); const sourceAlias = qb.helper.getTPTAliasForProperty(prop.name, tableAlias); if (prop.formula) { const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString(); const table = this.createFormulaTable(quotedAlias, meta, schema); const columns = meta.createColumnMappingObject( p => qb.helper.getTPTAliasForProperty(p.name, tableAlias), quotedAlias, ); return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)]; } if (prop.customTypes?.some(type => !!type?.convertToJSValueSQL)) { return prop.fieldNames.map((col, idx) => { if (!prop.customTypes[idx]?.convertToJSValueSQL) { return col; } const prefixed = this.platform.quoteIdentifier(`${sourceAlias}.${col}`); const aliased = this.platform.quoteIdentifier(`${tableAlias}__${col}`); return raw(`${prop.customTypes[idx].convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`); }); } if (prop.customType?.convertToJSValueSQL) { const prefixed = this.platform.quoteIdentifier(`${sourceAlias}.${prop.fieldNames[0]}`); return [raw(`${prop.customType.convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`)]; } return prop.fieldNames.map(fieldName => { return raw('?? as ??', [`${sourceAlias}.${fieldName}`, `${tableAlias}__${fieldName}`]); }); } /** @internal */ createQueryBuilder( entityName: EntityName | AnyQueryBuilder, ctx?: Transaction, preferredConnectionType?: ConnectionType, convertCustomTypes?: boolean, loggerContext?: LoggingOptions, alias?: string, em?: SqlEntityManager, ): AnyQueryBuilder { // do not compute the connectionType if EM is provided as it will be computed from it in the QB later on const connectionType = em ? preferredConnectionType : this.resolveConnectionType({ ctx, connectionType: preferredConnectionType }); const qb = new QueryBuilder( entityName, this.metadata, this, ctx, alias, connectionType, em, loggerContext, ) as AnyQueryBuilder; if (!convertCustomTypes) { qb.unsetFlag(QueryFlag.CONVERT_CUSTOM_TYPES); } return qb; } /** * Renders a `FilterQuery` predicate into a SQL fragment (without the `WHERE` keyword and * without table-alias prefixes) suitable for inlining into a partial-index DDL statement. * Used by `DatabaseTable.addIndex` when the user passes an object `where` on `@Index` / * `@Unique`. Strings are returned unchanged. */ renderPartialIndexWhere(entityName: EntityName, where: string | FilterQuery): string { if (typeof where === 'string') { return where; } const name = Utils.className(entityName); if (where == null || (Utils.isPlainObject(where) && Object.keys(where as Dictionary).length === 0)) { throw new Error(`Cannot render partial-index predicate for entity '${name}': \`where\` is empty.`); } const alias = '__p'; const qb = this.createQueryBuilder(entityName, undefined, undefined, undefined, undefined, alias); // Select a constant instead of the default `*` — otherwise non-lazy `@Formula` properties // (and their embedded subqueries, which may contain their own `where`/cross-table refs) // leak into the SQL and corrupt the predicate extracted below. Only `from ... where` matters here. qb.select(raw('1')); qb.where(where as any); const sql = qb.getFormattedQuery(); // Relation traversal produces join clauses whose aliased identifiers can't be inlined // into a CREATE INDEX ... WHERE clause — reject with a clear error rather than emitting broken DDL. if (/\bjoin\b/i.test(sql.split(/\bwhere\b/i)[0])) { throw new Error( `Cannot render partial-index predicate for entity '${name}': \`where\` may not traverse relations.`, ); } // Anchor at end-of-string only — the synthetic QB has no top-level order by / limit / // group by / having / offset, so any such keyword inside the captured predicate is // inside a subquery and must not terminate the match. const match = /\bwhere\s+([\s\S]+)$/i.exec(sql); if (!match) { throw new Error(`Failed to render partial-index predicate for entity '${name}': ${sql}`); } const quote = (s: string) => this.platform.quoteIdentifier(s); const aliasPrefix = new RegExp(`${quote(alias).replace(/[[\]]/g, '\\$&')}\\.`, 'g'); const stripped = match[1].replace(aliasPrefix, '').trim(); // Any qualified column reference remaining after the alias strip points at another table or // subquery and can't be inlined into a CREATE INDEX ... WHERE predicate. Covers both // QB-generated sub-aliases (quoted, e.g. `"e0"."col"`) and raw fragments with bare refs // (e.g. `raw('other_table.col = 1')`). String literals are erased first so dots inside // them (e.g. JSON path operands like `'$.path'`) don't trip the guard. // Both patterns use a `(?!\s*\()` lookahead so schema-qualified function calls // (`pg_catalog.lower(name)`, `"public".my_func(col)`) are accepted — only `.` not // followed by `(` is treated as a cross-table column reference. const withoutStrings = stripped.replace(/'(?:[^']|'')*'/g, "''"); const quotedIdent = String.raw`(?:"(?:[^"]|"")+"|\`(?:[^\`]|\`\`)+\`|\[(?:[^\]]|\]\])+\])`; const anyIdent = `(?:${quotedIdent}|[A-Za-z_]\\w*)`; const quotedCrossRef = new RegExp(`${quotedIdent}\\s*\\.\\s*${anyIdent}(?!\\s*\\()`); const bareCrossRef = /\b[A-Za-z_]\w*\s*\.\s*[A-Za-z_]\w*\b(?!\s*\()/; if (quotedCrossRef.test(withoutStrings) || bareCrossRef.test(withoutStrings)) { throw new Error( `Cannot render partial-index predicate for entity '${name}': \`where\` references another table or subquery which cannot be inlined into a CREATE INDEX ... WHERE clause.`, ); } return stripped; } protected resolveConnectionType(args: { ctx?: Transaction; connectionType?: ConnectionType }): ConnectionType { if (args.ctx) { return 'write'; } if (args.connectionType) { return args.connectionType; } if (this.config.get('preferReadReplicas')) { return 'read'; } return 'write'; } protected extractManyToMany(meta: EntityMetadata, data: EntityDictionary): EntityData { const ret: EntityData = {}; for (const prop of meta.relations) { if (prop.kind === ReferenceKind.MANY_TO_MANY && data[prop.name]) { // union targets are validated to have a single PK column, so a pivot row is always keyed // by exactly `[discriminator, pk]` - anything else cannot address a target table const discriminators = QueryHelper.isUnionTargetPolymorphic(prop) ? Object.keys(prop.discriminatorMap!) : undefined; ret[prop.name] = data[prop.name].map((item: Primary) => { const values = Utils.asArray(item); if (discriminators && !(values.length === 2 && discriminators.includes('' + values[0]))) { throw new Error( `Cannot resolve the discriminator value of ${meta.className}.${prop.name} from '${values.join(', ')}', ` + `as the same primary key can exist in any of the target tables. ` + `Pass the target as a [discriminator, ...primaryKey] tuple, e.g. ${JSON.stringify([discriminators[0], ...values])}.`, ); } return values; }); delete data[prop.name]; } } return ret; } protected async processManyToMany( meta: EntityMetadata, pks: Primary[], collections: EntityData, clear: boolean, options?: DriverMethodOptions, ) { for (const prop of meta.relations) { if (collections[prop.name]) { const pivotMeta = this.metadata.get(prop.pivotEntity); const persister = new PivotCollectionPersister( pivotMeta, this, options?.ctx, options?.schema, options?.loggerContext, pickAbortOptions(options), ); persister.enqueueUpdate(prop, collections[prop.name] as Primary[][], clear, pks); await this.rethrow(persister.execute()); } } } override async lockPessimistic(entity: T, options: LockOptions): Promise { const meta = helper(entity).__meta; const qb = this.createQueryBuilder(meta.class, options.ctx, undefined, undefined, options.logging).withSchema( options.schema ?? meta.schema, ); qb.setAbortOptions(pickAbortOptions(options)); const cond = Utils.getPrimaryKeyCond(entity, meta.primaryKeys); qb.select(raw('1')) .where(cond as any) .setLockMode(options.lockMode, options.lockTableAliases); await this.rethrow(qb.execute()); } protected buildPopulateWhere( meta: EntityMetadata, joinedProps: PopulateOptions[], options: Pick, 'populateWhere' | 'strategy'>, ): ObjectQuery { const where = {} as ObjectQuery; for (const hint of joinedProps) { const [propName] = hint.field.split(':', 2) as [EntityKey]; const prop = meta.properties[propName]; if (!Utils.isEmpty(prop.where) || RawQueryFragment.hasObjectFragments(prop.where)) { where[prop.name] = Utils.copy(prop.where); } if (hint.children) { const targetMeta = prop.targetMeta; if (targetMeta) { // only joined children contribute to the ON conditions, the rest is handled by the entity loader const children = this.joinedProps(targetMeta, hint.children as any, options); const inner = this.buildPopulateWhere(targetMeta, children, { strategy: options.strategy }); if (!Utils.isEmpty(inner) || RawQueryFragment.hasObjectFragments(inner)) { where[prop.name] ??= {} as any; Object.assign(where[prop.name] as object, inner); } } } } if (Utils.isEmpty(options.populateWhere) && !RawQueryFragment.hasObjectFragments(options.populateWhere)) { return where; } if (Utils.isEmpty(where) && !RawQueryFragment.hasObjectFragments(where)) { return options.populateWhere as ObjectQuery; } /* v8 ignore next */ return { $and: [options.populateWhere, where] } as unknown as ObjectQuery; } /** * Builds a UNION ALL (or UNION) subquery from `unionWhere` branches and merges it * into the main WHERE as `pk IN (branch_1 UNION ALL branch_2 ...)`. * Each branch is planned independently by the database, enabling per-table index usage. */ protected async applyUnionWhere( meta: EntityMetadata, where: ObjectQuery, options: FindOptions | CountOptions | NativeInsertUpdateOptions | DeleteOptions, forDml = false, ): Promise> { const unionWhere = (options as FindOptions).unionWhere!; const strategy = (options as FindOptions).unionWhereStrategy ?? 'union-all'; const schema = this.getSchemaName(meta, options); const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: (options as FindOptions).connectionType, }); const branchQbs: QueryBuilder[] = []; for (const branch of unionWhere) { const qb = this.createQueryBuilder( meta.class, options.ctx, connectionType, false, (options as FindOptions).logging, ).withSchema(schema); const pkFields = meta.primaryKeys.map(pk => { const prop = meta.properties[pk]; return `${qb.alias}.${prop.fieldNames[0]}`; }); qb.select(pkFields as any).where(branch as any); if (options.em) { await qb.applyJoinedFilters(options.em, options.filters); } branchQbs.push(qb); } const [first, ...rest] = branchQbs; const unionQb = strategy === 'union' ? first.union(...rest) : first.unionAll(...rest); const pkHash = Utils.getPrimaryKeyHash(meta.primaryKeys); // MySQL does not allow referencing the target table in a subquery // for UPDATE/DELETE, so we wrap the union in a derived table. if (forDml) { const { sql, params } = unionQb.toQuery(); return { $and: [where, { [pkHash]: { $in: raw(`select * from (${sql}) as __u`, params) } }], } as ObjectQuery; } return { $and: [where, { [pkHash]: { $in: unionQb.toRaw() } }], } as ObjectQuery; } protected buildOrderBy( qb: AnyQueryBuilder, meta: EntityMetadata, populate: PopulateOptions[], options: Pick, 'strategy' | 'orderBy' | 'populateOrderBy'>, ): QueryOrderMap[] { const joinedProps = this.joinedProps(meta, populate, options); // `options._populateWhere` is a copy of the value provided by user with a fallback to the global config option // as `options.populateWhere` will be always recomputed to respect filters const populateWhereAll = (options as Dictionary)._populateWhere !== 'infer' && !Utils.isEmpty((options as Dictionary)._populateWhere); const path = (populateWhereAll ? '[populate]' : '') + meta.className; const optionsOrderBy = Utils.asArray(options.orderBy); const populateOrderBy = this.buildPopulateOrderBy( qb, meta, Utils.asArray>(options.populateOrderBy ?? options.orderBy), path, !!options.populateOrderBy, ); const joinedPropsOrderBy = this.buildJoinedPropsOrderBy(qb, meta, joinedProps, options, path); return [...optionsOrderBy, ...populateOrderBy, ...joinedPropsOrderBy] as QueryOrderMap[]; } protected buildPopulateOrderBy( qb: AnyQueryBuilder, meta: EntityMetadata, populateOrderBy: QueryOrderMap[], parentPath: string, explicit: boolean, parentAlias = qb.alias, ): QueryOrderMap[] { const orderBy: QueryOrderMap[] = []; for (let i = 0; i < populateOrderBy.length; i++) { const orderHint = populateOrderBy[i]; for (const field of Utils.getObjectQueryKeys(orderHint)) { const childOrder = orderHint[field as keyof typeof orderHint]; if (RawQueryFragment.isKnownFragmentSymbol(field)) { const { sql, params } = RawQueryFragment.getKnownFragment(field)!; const key = raw(sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), parentAlias), params); orderBy.push({ [key]: childOrder } as QueryOrderMap); continue; } const prop = meta.properties[field]; if (!prop) { throw new Error(`Trying to order by not existing property ${meta.className}.${field}`); } let path = parentPath; const meta2 = prop.targetMeta!; if ( prop.kind !== ReferenceKind.SCALAR && (![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) || !prop.owner || Utils.isPlainObject(childOrder)) ) { path += `.${field}`; } if (prop.kind === ReferenceKind.MANY_TO_MANY && typeof childOrder !== 'object') { path += '[pivot]'; } const join = qb.getJoinForPath(path, { matchPopulateJoins: true }); const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true }) ?? parentAlias; if (!join) { // an owner to-one relation that is not joined (e.g. ordering a populated collection by such // a relation's primary key) can be ordered by its local FK columns, matching the `select-in` // and `balanced` strategies instead of silently dropping the clause if ( prop.owner && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils.isPlainObject(childOrder) ) { for (const childField of Utils.getObjectQueryKeys(childOrder as Dictionary)) { const idx = prop.referencedPKs.indexOf(childField as EntityKey); const order = (childOrder as Dictionary)[childField as string]; if (idx !== -1 && order) { orderBy.push({ [`${parentAlias}.${prop.joinColumns[idx]}` as EntityKey]: order } as QueryOrderMap); } } } continue; } if ( join && ![ReferenceKind.SCALAR, ReferenceKind.EMBEDDED].includes(prop.kind) && typeof childOrder === 'object' ) { const children = this.buildPopulateOrderBy( qb, meta2, Utils.asArray(childOrder as QueryOrderMap), path, explicit, propAlias, ); orderBy.push(...children); continue; } if (prop.kind === ReferenceKind.MANY_TO_MANY && join) { if (prop.fixedOrderColumn) { orderBy.push({ [`${join.alias}.${prop.fixedOrderColumn}`]: childOrder } as QueryOrderMap); } else { for (const col of prop.inverseJoinColumns) { orderBy.push({ [`${join.ownerAlias}.${col}`]: childOrder } as QueryOrderMap); } } continue; } const order = typeof childOrder === 'object' ? childOrder[field as EntityKey] : childOrder; if (order) { orderBy.push({ [`${propAlias}.${field}` as EntityKey]: order } as QueryOrderMap); } } } return orderBy; } protected buildJoinedPropsOrderBy( qb: AnyQueryBuilder, meta: EntityMetadata, populate: PopulateOptions[], options?: Pick, 'strategy' | 'orderBy' | 'populateOrderBy'>, parentPath?: string, ): QueryOrderMap[] { const orderBy: QueryOrderMap[] = []; const joinedProps = this.joinedProps(meta, populate, options); for (const hint of joinedProps) { const [propName, ref] = hint.field.split(':', 2) as [EntityKey, string | undefined]; const prop = meta.properties[propName]; let path = `${parentPath}.${propName}`; if (prop.kind === ReferenceKind.MANY_TO_MANY && ref) { path += '[pivot]'; } if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) { this.buildToManyOrderBy(qb, prop, path, ref, orderBy); } if (hint.children) { orderBy.push(...this.buildJoinedPropsOrderBy(qb, prop.targetMeta!, hint.children as any, options, path)); } } return orderBy; } private buildToManyOrderBy( qb: AnyQueryBuilder, prop: EntityProperty, path: string, ref: string | undefined, orderBy: QueryOrderMap[], ): void { const join = qb.getJoinForPath(path, { matchPopulateJoins: true }); const propAlias = qb.getAliasForJoinPath(join ?? path, { matchPopulateJoins: true }); if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.fixedOrder && join) { const alias = ref ? propAlias : join.ownerAlias; orderBy.push({ [`${alias}.${prop.fixedOrderColumn}`]: QueryOrder.ASC } as QueryOrderMap); } const effectiveOrderBy = QueryHelper.mergeOrderBy(prop.orderBy, prop.targetMeta?.orderBy); for (const item of effectiveOrderBy) { for (const field of Utils.getObjectQueryKeys(item)) { const order = item[field as keyof typeof item]; if (RawQueryFragment.isKnownFragmentSymbol(field)) { const { sql, params } = RawQueryFragment.getKnownFragment(field)!; const sql2 = propAlias ? sql.replace(new RegExp(ALIAS_REPLACEMENT_RE, 'g'), propAlias) : sql; const key = raw(sql2, params); orderBy.push({ [key]: order } as QueryOrderMap); continue; } orderBy.push({ [`${propAlias}.${field}` as EntityKey]: order } as QueryOrderMap); } } } protected normalizeFields(fields: InternalField[], prefix = ''): string[] { const ret: string[] = []; for (const field of fields) { if (typeof field === 'string') { ret.push(prefix + field); continue; } if (Utils.isPlainObject(field)) { for (const key of Object.keys(field)) { ret.push(...this.normalizeFields((field as Dictionary)[key], key + '.')); } } } return ret; } protected processField( meta: EntityMetadata, prop: EntityProperty | undefined, field: string, ret: InternalField[], ): void { if (!prop || (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner)) { return; } if (prop.kind === ReferenceKind.EMBEDDED) { if (prop.object) { ret.push(prop.name); return; } const parts = field.split('.'); const top = parts.shift(); for (const key of Object.keys(prop.embeddedProps)) { if (!top || key === top) { this.processField(meta, prop.embeddedProps[key], parts.join('.'), ret); } } return; } if (prop.persist === false && !prop.embedded && !prop.formula) { return; } ret.push(prop.name); } protected buildFields( meta: EntityMetadata, populate: PopulateOptions[], joinedProps: PopulateOptions[], qb: AnyQueryBuilder, alias: string, options: Pick, 'strategy' | 'fields' | 'exclude'>, schema?: string, ): InternalField[] { const lazyProps = meta.props.filter(prop => prop.lazy && !populate.some(p => this.isPopulated(meta, prop, p))); const hasLazyFormulas = meta.props.some(p => p.lazy && p.formula); const requiresSQLConversion = meta.props.some(p => p.customType?.convertToJSValueSQL && p.persist !== false); const hasExplicitFields = !!options.fields; const ret: InternalField[] = []; let addFormulas = false; // handle root entity properties first, this is used for both strategies in the same way if (options.fields) { for (const field of this.normalizeFields(options.fields as string[])) { if (field === '*') { ret.push('*'); continue; } const parts = field.split('.'); const rootPropName = parts.shift()!; // first one is the `prop` const prop = QueryHelper.findProperty(rootPropName, { metadata: this.metadata, platform: this.platform, entityName: meta.class, where: {} as FilterQuery, aliasMap: qb.getAliasMap(), }); this.processField(meta, prop, parts.join('.'), ret); } if (!options.fields.includes('*') && !options.fields.includes(`${qb.alias}.*`)) { ret.unshift(...meta.primaryKeys.filter(pk => !options.fields!.includes(pk))); // `targetKey` values identify the entity like its PK, references resolve it by them ret.push(...(meta.root.targetKeys ?? []).filter(key => meta.properties[key] && !options.fields!.includes(key))); } if ( meta.root.inheritanceType === 'sti' && !options.fields.includes(`${qb.alias}.${meta.root.discriminatorColumn!}`) ) { ret.push(meta.root.discriminatorColumn!); } } else if (!Utils.isEmpty(options.exclude) || lazyProps.some(p => !p.formula && (p.kind !== '1:1' || p.owner))) { const props = meta.props.filter(prop => this.platform.shouldHaveColumn(prop, populate, options.exclude as string[], false, false), ); ret.push(...props.filter(p => !lazyProps.includes(p)).map(p => p.name)); addFormulas = true; } else if (hasLazyFormulas || requiresSQLConversion) { ret.push('*'); addFormulas = true; } else { ret.push('*'); } if (ret.length > 0 && !hasExplicitFields && addFormulas) { // `toString()` must yield the quoted alias like `QueryBuilder.finalize()`, which dedupes formulas by rendered SQL const quotedAlias = this.platform.quoteIdentifier(alias); // TPT parent aliases are only known once the parent joins exist qb.ensureTPTJoins(); const columns = meta.createColumnMappingObject( p => qb.helper.getTPTAliasForProperty(p.name, alias), quotedAlias.toString(), ); const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined); for (const prop of meta.props) { if (lazyProps.includes(prop)) { continue; } if (prop.formula) { const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]); const table = this.createFormulaTable(quotedAlias.toString(), meta, effectiveSchema); ret.push(raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)); } if (!prop.object && !prop.formula && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) { ret.push(prop.name); } } } // add joined relations after the root entity fields if (joinedProps.length > 0) { ret.push( ...this.getFieldsForJoinedLoad(qb, meta, { explicitFields: options.fields as string[], exclude: options.exclude as string[], populate, parentTableAlias: alias, ...options, }), ); } return Utils.unique(ret); } } interface FieldsForJoinedLoadOptions { explicitFields?: readonly InternalField[]; exclude?: readonly InternalField[]; populate?: readonly PopulateOptions[]; strategy?: Options['loadStrategy']; populateWhere?: FindOptions['populateWhere']; populateFilter?: FindOptions['populateFilter']; parentTableAlias: string; parentJoinPath?: string; count?: boolean; schema?: string; }