@mikro-orm/sql 7.0.0-dev.99 → 7.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AbstractSqlConnection.d.ts +2 -4
  2. package/AbstractSqlConnection.js +3 -7
  3. package/AbstractSqlDriver.d.ts +89 -23
  4. package/AbstractSqlDriver.js +630 -197
  5. package/AbstractSqlPlatform.d.ts +11 -5
  6. package/AbstractSqlPlatform.js +18 -5
  7. package/PivotCollectionPersister.d.ts +5 -0
  8. package/PivotCollectionPersister.js +30 -12
  9. package/SqlEntityManager.d.ts +2 -2
  10. package/dialects/mysql/{MySqlPlatform.d.ts → BaseMySqlPlatform.d.ts} +4 -3
  11. package/dialects/mysql/{MySqlPlatform.js → BaseMySqlPlatform.js} +9 -4
  12. package/dialects/mysql/MySqlSchemaHelper.d.ts +12 -1
  13. package/dialects/mysql/MySqlSchemaHelper.js +97 -6
  14. package/dialects/mysql/index.d.ts +1 -2
  15. package/dialects/mysql/index.js +1 -2
  16. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +106 -0
  17. package/dialects/postgresql/BasePostgreSqlPlatform.js +350 -0
  18. package/dialects/postgresql/FullTextType.d.ts +14 -0
  19. package/dialects/postgresql/FullTextType.js +59 -0
  20. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +8 -0
  21. package/dialects/postgresql/PostgreSqlExceptionConverter.js +47 -0
  22. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +90 -0
  23. package/dialects/postgresql/PostgreSqlSchemaHelper.js +732 -0
  24. package/dialects/postgresql/index.d.ts +3 -0
  25. package/dialects/postgresql/index.js +3 -0
  26. package/dialects/sqlite/BaseSqliteConnection.d.ts +1 -0
  27. package/dialects/sqlite/BaseSqliteConnection.js +13 -0
  28. package/dialects/sqlite/BaseSqlitePlatform.d.ts +6 -0
  29. package/dialects/sqlite/BaseSqlitePlatform.js +12 -0
  30. package/dialects/sqlite/SqliteSchemaHelper.d.ts +25 -0
  31. package/dialects/sqlite/SqliteSchemaHelper.js +145 -19
  32. package/dialects/sqlite/index.d.ts +0 -1
  33. package/dialects/sqlite/index.js +0 -1
  34. package/package.json +5 -6
  35. package/plugin/transformer.d.ts +1 -1
  36. package/plugin/transformer.js +1 -1
  37. package/query/CriteriaNode.d.ts +9 -5
  38. package/query/CriteriaNode.js +16 -15
  39. package/query/CriteriaNodeFactory.d.ts +6 -6
  40. package/query/CriteriaNodeFactory.js +33 -31
  41. package/query/NativeQueryBuilder.d.ts +3 -2
  42. package/query/NativeQueryBuilder.js +1 -2
  43. package/query/ObjectCriteriaNode.js +51 -36
  44. package/query/QueryBuilder.d.ts +569 -79
  45. package/query/QueryBuilder.js +614 -171
  46. package/query/QueryBuilderHelper.d.ts +24 -16
  47. package/query/QueryBuilderHelper.js +167 -78
  48. package/query/ScalarCriteriaNode.js +2 -2
  49. package/query/raw.d.ts +11 -3
  50. package/query/raw.js +1 -2
  51. package/schema/DatabaseSchema.d.ts +15 -2
  52. package/schema/DatabaseSchema.js +143 -15
  53. package/schema/DatabaseTable.d.ts +12 -0
  54. package/schema/DatabaseTable.js +91 -31
  55. package/schema/SchemaComparator.d.ts +8 -0
  56. package/schema/SchemaComparator.js +127 -3
  57. package/schema/SchemaHelper.d.ts +26 -3
  58. package/schema/SchemaHelper.js +98 -11
  59. package/schema/SqlSchemaGenerator.d.ts +10 -0
  60. package/schema/SqlSchemaGenerator.js +137 -9
  61. package/tsconfig.build.tsbuildinfo +1 -0
  62. package/typings.d.ts +78 -38
  63. package/dialects/postgresql/PostgreSqlTableCompiler.d.ts +0 -1
  64. package/dialects/postgresql/PostgreSqlTableCompiler.js +0 -1
@@ -1,9 +1,9 @@
1
- import { type AnyEntity, type ConnectionType, type Dictionary, type EntityData, type EntityKey, type EntityManager, type EntityMetadata, type EntityName, type EntityProperty, type ExpandProperty, type FilterOptions, type FlushMode, type GroupOperator, type Loaded, LockMode, type LoggingOptions, type MetadataStorage, type ObjectQuery, PopulateHint, type PopulateOptions, type QBFilterQuery, type QBQueryOrderMap, QueryFlag, type QueryOrderMap, type QueryResult, RawQueryFragment, type RequiredEntityData, type Transaction } from '@mikro-orm/core';
1
+ import { type AnyEntity, type AutoPath, type ConnectionType, type Dictionary, type EntityData, type EntityKey, type EntityManager, type EntityMetadata, type EntityName, type EntityProperty, type ExpandProperty, type FilterObject, type FilterOptions, type FilterValue, type FlushMode, type GroupOperator, type Loaded, LockMode, type LoggingOptions, type MetadataStorage, type ObjectQuery, PopulateHint, type PopulateOptions, type PopulatePath, QueryFlag, type QueryOrderKeysFlat, type QueryOrderMap, type QueryResult, RawQueryFragment, type Raw, type RequiredEntityData, type Scalar, type Subquery, type Transaction } from '@mikro-orm/core';
2
2
  import { JoinType, QueryType } from './enums.js';
3
3
  import type { AbstractSqlDriver } from '../AbstractSqlDriver.js';
4
4
  import { type Alias, type OnConflictClause, QueryBuilderHelper } from './QueryBuilderHelper.js';
5
5
  import type { SqlEntityManager } from '../SqlEntityManager.js';
6
- import type { Field, ICriteriaNodeProcessOptions, JoinOptions } from '../typings.js';
6
+ import type { ICriteriaNodeProcessOptions, InternalField, JoinOptions } from '../typings.js';
7
7
  import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
8
8
  import { NativeQueryBuilder } from './NativeQueryBuilder.js';
9
9
  export interface ExecuteOptions {
@@ -34,26 +34,111 @@ export interface QBStreamOptions {
34
34
  */
35
35
  rawResults?: boolean;
36
36
  }
37
- type AnyString = string & {};
38
- type Compute<T> = {
39
- [K in keyof T]: T[K];
40
- } & {};
41
37
  type IsNever<T, True = true, False = false> = [T] extends [never] ? True : False;
42
38
  type GetAlias<T extends string> = T extends `${infer A}.${string}` ? A : never;
43
39
  type GetPropName<T extends string> = T extends `${string}.${infer P}` ? P : T;
44
40
  type AppendToHint<Parent extends string, Child extends string> = `${Parent}.${Child}`;
41
+ /**
42
+ * Context tuple format: [Path, Alias, Type, Select]
43
+ * - Path: The relation path from root entity (e.g., 'books', 'books.author')
44
+ * - Alias: The SQL alias used in the query (e.g., 'b', 'a1')
45
+ * - Type: The entity type of the joined relation
46
+ * - Select: Whether this join was created via joinAndSelect (affects Fields tracking)
47
+ *
48
+ * Example: After `qb.leftJoin('a.books', 'b')`, Context becomes:
49
+ * { b: ['books', 'b', Book, false] }
50
+ */
45
51
  type AddToContext<Type extends object, Context, Field extends string, Alias extends string, Select extends boolean> = {
46
52
  [K in Alias]: [GetPath<Context, Field>, K, ExpandProperty<Type[GetPropName<Field> & keyof Type]>, Select];
47
53
  };
48
54
  type GetPath<Context, Field extends string> = GetAlias<Field> extends infer Alias ? IsNever<Alias> extends true ? GetPropName<Field> : Alias extends keyof Context ? Context[Alias] extends [infer Path, ...any[]] ? AppendToHint<Path & string, GetPropName<Field>> : GetPropName<Field> : GetPropName<Field> : GetPropName<Field>;
49
- type GetType<Type extends object, Context, Field extends string> = GetAlias<Field> extends infer Alias ? IsNever<Alias> extends true ? Type : Alias extends keyof Context ? Context[Alias] extends [string, string, infer PropType] ? PropType & object : Type : Type : Type;
55
+ type GetType<Type extends object, Context, Field extends string> = GetAlias<Field> extends infer Alias ? IsNever<Alias> extends true ? Type : [Context] extends [never] ? Type : Alias extends keyof Context ? Context[Alias] extends [string, string, infer PropType, any] ? PropType & object : Type : Type : Type;
50
56
  type AddToHint<RootAlias, Context, Field extends string, Select extends boolean = false> = Select extends true ? GetAlias<Field> extends infer Alias ? IsNever<Alias> extends true ? GetPropName<Field> : Alias extends RootAlias ? GetPropName<Field> : Alias extends keyof Context ? Context[Alias] extends [infer Path, ...any[]] ? AppendToHint<Path & string, GetPropName<Field>> : GetPropName<Field> : GetPropName<Field> : GetPropName<Field> : never;
51
57
  export type ModifyHint<RootAlias, Context, Hint extends string, Field extends string, Select extends boolean = false> = Hint | AddToHint<RootAlias, Context, Field, Select>;
52
- export type ModifyContext<Entity extends object, Context, Field extends string, Alias extends string, Select extends boolean = false> = Compute<IsNever<Context> extends true ? AddToContext<GetType<Entity, object, Field>, object, Field, Alias, Select> : Context & AddToContext<GetType<Entity, Context, Field>, Context, Field, Alias, Select>>;
58
+ export type ModifyContext<Entity extends object, Context, Field extends string, Alias extends string, Select extends boolean = false> = IsNever<Context> extends true ? AddToContext<GetType<Entity, object, Field>, object, Field, Alias, Select> : Context & AddToContext<GetType<Entity, Context, Field>, Context, Field, Alias, Select>;
59
+ type StripRootAlias<F extends string, RootAlias extends string, Context = never> = F extends `${RootAlias}.${infer Field}` ? Field : F extends `${infer Alias}.${string}` ? Alias extends AliasNames<Context> ? never : F : F;
60
+ type StripFieldAlias<F extends string> = F extends `${infer Path} as ${string}` ? Path : F;
61
+ type ExtractRootFields<Fields, RootAlias extends string, Context = never> = [Fields] extends ['*'] ? '*' : Fields extends `${RootAlias}.*` ? '*' : Fields extends string ? StripRootAlias<StripFieldAlias<Fields>, RootAlias, Context> : never;
62
+ type PrefixWithPath<Path extends string, Field extends string> = `${Path}.${Field}`;
63
+ type StripJoinAlias<F extends string, Alias extends string> = F extends `${Alias}.${infer Field}` ? Field : F;
64
+ export type JoinSelectField<JoinedEntity, Alias extends string> = (keyof JoinedEntity & string) | `${Alias}.${keyof JoinedEntity & string}`;
65
+ type AddJoinFields<RootAlias, Context, Field extends string, Alias extends string, JoinFields extends readonly string[]> = JoinFields extends readonly (infer F)[] ? F extends string ? PrefixWithPath<AddToHint<RootAlias, Context, Field, true> & string, StripJoinAlias<F, Alias>> : never : never;
66
+ export type ModifyFields<CurrentFields extends string, RootAlias, Context, Field extends string, Alias extends string, JoinFields extends readonly string[] | undefined> = JoinFields extends readonly string[] ? CurrentFields | AddJoinFields<RootAlias, Context, Field, Alias, JoinFields> : CurrentFields;
53
67
  type EntityRelations<T> = EntityKey<T, true>;
54
- type AddAliasesFromContext<Context> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, infer Type, any] ? `${Alias & string}.${EntityRelations<Type & {}>}` : never : never : never;
55
- export type QBField<Entity, RootAlias extends string, Context> = (EntityRelations<Entity> | `${RootAlias}.${EntityRelations<Entity>}` | AddAliasesFromContext<Context>) & {} | AnyString;
56
- type EntityKeyOrString<Entity extends object = AnyEntity> = AnyString | keyof Entity;
68
+ type JoinedEntityType<Entity extends object, Context, Field extends string> = ExpandProperty<GetType<Entity, Context, Field>[GetPropName<Field> & keyof GetType<Entity, Context, Field>]>;
69
+ type AliasNames<Context> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, any, any] ? Alias & string : never : never : never;
70
+ type ContextRelationKeys<Context> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, infer Type, any] ? `${Alias & string}.${EntityRelations<Type & object>}` : never : never : never;
71
+ export type QBField<Entity, RootAlias extends string, Context> = EntityRelations<Entity> | `${RootAlias}.${EntityRelations<Entity>}` | ([Context] extends [never] ? never : ContextRelationKeys<Context>);
72
+ type ContextFieldKeys<Context> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, infer Type, any] ? `${Alias & string}.${keyof Type & string}` : never : never : never;
73
+ type WithAlias<T extends string> = T | `${T} as ${string}`;
74
+ export type Field<Entity, RootAlias extends string = never, Context = never> = WithAlias<EntityKey<Entity>> | (IsNever<RootAlias> extends true ? never : WithAlias<`${RootAlias}.${EntityKey<Entity>}`> | `${RootAlias}.*`) | ([Context] extends [never] ? never : WithAlias<ContextFieldKeys<Context>> | `${AliasNames<Context>}.*`) | '*' | QueryBuilder<any> | NativeQueryBuilder | RawQueryFragment<any> | (RawQueryFragment & symbol);
75
+ type RootAliasOrderKeys<RootAlias extends string, Entity> = {
76
+ [K in `${RootAlias}.${EntityKey<Entity>}`]?: QueryOrderKeysFlat;
77
+ };
78
+ type ContextOrderKeys<Context> = {
79
+ [K in ContextFieldKeys<Context>]?: QueryOrderKeysFlat;
80
+ };
81
+ type RawOrderKeys<RawAliases extends string> = {
82
+ [K in RawAliases]?: QueryOrderKeysFlat;
83
+ };
84
+ export type ContextOrderByMap<Entity, RootAlias extends string = never, Context = never, RawAliases extends string = never> = QueryOrderMap<Entity> | ((IsNever<RootAlias> extends true ? {} : RootAliasOrderKeys<RootAlias, Entity>) & ([Context] extends [never] ? {} : ContextOrderKeys<Context>) & (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawOrderKeys<RawAliases>));
85
+ type AliasedPath<Alias extends string, Type, P extends string> = P extends `${Alias}.*` ? P : P extends `${Alias}.${infer Rest}` ? `${Alias}.${AutoPath<Type & object, Rest, `${PopulatePath.ALL}`>}` : never;
86
+ type ContextAliasedPath<Context, P extends string> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, infer Type, any] ? AliasedPath<Alias & string, Type, P> : never : never : never;
87
+ type NestedAutoPath<Entity, RootAlias extends string, Context, P extends string> = P extends `${string}:ref` ? never : P extends `${infer Path} as ${string}` ? (AliasedPath<RootAlias, Entity, Path> | ContextAliasedPath<Context, Path> | AutoPath<Entity, Path, `${PopulatePath.ALL}`>) extends never ? never : P : AliasedPath<RootAlias, Entity, P> | ContextAliasedPath<Context, P> | AutoPath<Entity, P, `${PopulatePath.ALL}`>;
88
+ type AliasedObjectQuery<Entity extends object, Alias extends string> = {
89
+ [K in EntityKey<Entity> as `${Alias}.${K}`]?: ObjectQuery<Entity>[K];
90
+ };
91
+ type JoinCondition<JoinedEntity extends object, Alias extends string> = (ObjectQuery<JoinedEntity> | AliasedObjectQuery<JoinedEntity, Alias>) & {
92
+ $not?: JoinCondition<JoinedEntity, Alias>;
93
+ $or?: JoinCondition<JoinedEntity, Alias>[];
94
+ $and?: JoinCondition<JoinedEntity, Alias>[];
95
+ };
96
+ type RawJoinCondition = {
97
+ [key: string]: FilterValue<Scalar> | RawQueryFragment;
98
+ };
99
+ type ExtractRawAliasFromField<F> = F extends RawQueryFragment<infer A> ? (A extends string ? A : never) : F extends `${string} as ${infer A}` ? A : never;
100
+ type ExtractRawAliasesFromTuple<T extends readonly unknown[]> = T extends readonly [infer Head, ...infer Tail] ? ExtractRawAliasFromField<Head> | ExtractRawAliasesFromTuple<Tail> : never;
101
+ type ExtractRawAliases<Fields> = Fields extends readonly unknown[] ? ExtractRawAliasesFromTuple<Fields> : ExtractRawAliasFromField<Fields>;
102
+ type FlatOperatorMap = {
103
+ $eq?: Scalar | readonly Scalar[] | Subquery | null;
104
+ $ne?: Scalar | readonly Scalar[] | Subquery | null;
105
+ $in?: readonly Scalar[] | Raw | Subquery;
106
+ $nin?: readonly Scalar[] | Raw | Subquery;
107
+ $gt?: Scalar | Subquery;
108
+ $gte?: Scalar | Subquery;
109
+ $lt?: Scalar | Subquery;
110
+ $lte?: Scalar | Subquery;
111
+ $like?: string;
112
+ $re?: string;
113
+ $ilike?: string;
114
+ $fulltext?: string;
115
+ $overlap?: readonly string[] | string | object;
116
+ $contains?: readonly string[] | string | object;
117
+ $contained?: readonly string[] | string | object;
118
+ $exists?: boolean;
119
+ $hasKey?: string;
120
+ $hasKeys?: readonly string[];
121
+ $hasSomeKeys?: readonly string[];
122
+ };
123
+ type AliasedFilterValue = Scalar | FlatOperatorMap | readonly Scalar[] | null | QueryBuilder<any> | NativeQueryBuilder;
124
+ type TypedAliasedFilterValue<T> = FilterValue<ExpandProperty<T>> | QueryBuilder<any> | NativeQueryBuilder;
125
+ type RootAliasFilterKeys<RootAlias extends string, Entity> = {
126
+ [K in EntityKey<Entity> as `${RootAlias}.${K}`]?: TypedAliasedFilterValue<Entity[K]>;
127
+ };
128
+ type ContextFilterKeys<Context> = {
129
+ [K in ContextFieldKeys<Context>]?: AliasedFilterValue;
130
+ };
131
+ type RawFilterKeys<RawAliases extends string> = {
132
+ [K in RawAliases]?: AliasedFilterValue;
133
+ };
134
+ type NestedFilterCondition<Entity, RootAlias extends string, Context, RawAliases extends string> = ObjectQuery<Entity> & (IsNever<RootAlias> extends true ? {} : string extends RootAlias ? {} : RootAliasFilterKeys<RootAlias, Entity>) & ([Context] extends [never] ? {} : ContextFilterKeys<Context>) & (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawFilterKeys<RawAliases>);
135
+ type GroupOperators<RootAlias extends string, Context, Entity, RawAliases extends string> = {
136
+ $and?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
137
+ $or?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
138
+ $not?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>;
139
+ };
140
+ export type AliasedFilterCondition<RootAlias extends string, Context, Entity, RawAliases extends string = never> = (IsNever<RootAlias> extends true ? {} : string extends RootAlias ? {} : RootAliasFilterKeys<RootAlias, Entity>) & ([Context] extends [never] ? {} : ContextFilterKeys<Context>) & (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawFilterKeys<RawAliases>) & GroupOperators<RootAlias, Context, Entity, RawAliases>;
141
+ export type QBFilterQuery<Entity, RootAlias extends string = never, Context = never, RawAliases extends string = never> = FilterObject<Entity> & AliasedFilterCondition<RootAlias, Context, Entity, RawAliases>;
57
142
  /**
58
143
  * SQL query builder with fluent interface.
59
144
  *
@@ -73,13 +158,14 @@ type EntityKeyOrString<Entity extends object = AnyEntity> = AnyString | keyof En
73
158
  * const publisher = await qb.getSingleResult();
74
159
  * ```
75
160
  */
76
- export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias extends string = never, Hint extends string = never, Context extends object = never> {
161
+ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias extends string = never, Hint extends string = never, Context extends object = never, RawAliases extends string = never, Fields extends string = '*'> implements Subquery {
77
162
  protected readonly metadata: MetadataStorage;
78
163
  protected readonly driver: AbstractSqlDriver;
79
164
  protected readonly context?: Transaction | undefined;
80
165
  protected connectionType?: ConnectionType | undefined;
81
166
  protected em?: SqlEntityManager | undefined;
82
167
  protected loggerContext?: (LoggingOptions & Dictionary) | undefined;
168
+ readonly __subquery: true;
83
169
  get mainAlias(): Alias<Entity>;
84
170
  get alias(): string;
85
171
  get helper(): QueryBuilderHelper;
@@ -87,7 +173,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
87
173
  /** @internal */
88
174
  _type?: QueryType;
89
175
  /** @internal */
90
- _fields?: Field<Entity>[];
176
+ _fields?: InternalField<Entity>[];
91
177
  /** @internal */
92
178
  _populate: PopulateOptions<Entity>[];
93
179
  /** @internal */
@@ -98,8 +184,6 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
98
184
  __populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
99
185
  /** @internal */
100
186
  _populateMap: Dictionary<string>;
101
- /** @internal */
102
- readonly rawFragments: Set<string>;
103
187
  protected aliasCounter: number;
104
188
  protected flags: Set<QueryFlag>;
105
189
  protected finalized: boolean;
@@ -110,9 +194,9 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
110
194
  protected _cond: Dictionary;
111
195
  protected _data: Dictionary;
112
196
  protected _orderBy: QueryOrderMap<Entity>[];
113
- protected _groupBy: Field<Entity>[];
197
+ protected _groupBy: InternalField<Entity>[];
114
198
  protected _having: Dictionary;
115
- protected _returning?: Field<Entity>[];
199
+ protected _returning?: InternalField<Entity>[];
116
200
  protected _onConflict?: OnConflictClause<Entity>[];
117
201
  protected _limit?: number;
118
202
  protected _offset?: number;
@@ -120,6 +204,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
120
204
  protected _joinedProps: Map<string, PopulateOptions<any>>;
121
205
  protected _cache?: boolean | number | [string, number];
122
206
  protected _indexHint?: string;
207
+ protected _collation?: string;
123
208
  protected _comments: string[];
124
209
  protected _hintComments: string[];
125
210
  protected flushMode?: FlushMode;
@@ -128,6 +213,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
128
213
  protected subQueries: Dictionary<string>;
129
214
  protected _mainAlias?: Alias<Entity>;
130
215
  protected _aliases: Dictionary<Alias<any>>;
216
+ protected _tptAlias: Dictionary<string>;
131
217
  protected _helper?: QueryBuilderHelper;
132
218
  protected _query?: {
133
219
  sql?: string;
@@ -135,36 +221,206 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
135
221
  qb: NativeQueryBuilder;
136
222
  };
137
223
  protected readonly platform: AbstractSqlPlatform;
224
+ private tptJoinsApplied;
225
+ private readonly autoJoinedPaths;
138
226
  /**
139
227
  * @internal
140
228
  */
141
- constructor(entityName: EntityName<Entity> | QueryBuilder<Entity, any, any>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Transaction | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager | undefined, loggerContext?: (LoggingOptions & Dictionary) | undefined);
142
- select(fields: Field<Entity> | Field<Entity>[], distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
143
- addSelect(fields: Field<Entity> | Field<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
144
- distinct(): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
229
+ constructor(entityName: EntityName<Entity> | QueryBuilder<Entity, any, any, any>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Transaction | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager | undefined, loggerContext?: (LoggingOptions & Dictionary) | undefined);
230
+ /**
231
+ * Creates a SELECT query, specifying the fields to retrieve.
232
+ *
233
+ * @example
234
+ * ```ts
235
+ * // Select specific fields
236
+ * const qb = em.createQueryBuilder(User, 'u');
237
+ * qb.select(['u.id', 'u.name', 'u.email']);
238
+ *
239
+ * // Select with raw expressions
240
+ * qb.select([raw('count(*) as total')]);
241
+ *
242
+ * // Select with aliases (works for regular and formula properties)
243
+ * qb.select(['id', 'fullName as displayName']);
244
+ * qb.select(['id', sql.ref('fullName').as('displayName')]);
245
+ *
246
+ * // Select with distinct
247
+ * qb.select('*', true);
248
+ * ```
249
+ */
250
+ select<const F extends readonly Field<Entity, RootAlias, Context>[]>(fields: F, distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases | ExtractRawAliases<F>, ExtractRootFields<F[number] & string, RootAlias, Context>>;
251
+ /**
252
+ * Creates a SELECT query, specifying the fields to retrieve.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * // Select specific fields
257
+ * const qb = em.createQueryBuilder(User, 'u');
258
+ * qb.select(['u.id', 'u.name', 'u.email']);
259
+ *
260
+ * // Select with raw expressions
261
+ * qb.select([raw('count(*) as total')]);
262
+ *
263
+ * // Select with distinct
264
+ * qb.select('*', true);
265
+ * ```
266
+ */
267
+ select<const P extends string>(fields: readonly NestedAutoPath<Entity, RootAlias, Context, P>[], distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>>;
268
+ /**
269
+ * Creates a SELECT query, specifying the fields to retrieve.
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * // Select specific fields with nested paths (e.g., for embedded properties)
274
+ * const qb = em.createQueryBuilder(User, 'u');
275
+ * qb.select('address.city');
276
+ * ```
277
+ */
278
+ select<const P extends string>(fields: NestedAutoPath<Entity, RootAlias, Context, P>, distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>>;
279
+ /**
280
+ * Creates a SELECT query, specifying the fields to retrieve.
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * // Select specific fields
285
+ * const qb = em.createQueryBuilder(User, 'u');
286
+ * qb.select(['u.id', 'u.name', 'u.email']);
287
+ *
288
+ * // Select with raw expressions
289
+ * qb.select([raw('count(*) as total')]);
290
+ *
291
+ * // Select with distinct
292
+ * qb.select('*', true);
293
+ * ```
294
+ */
295
+ select<const F extends Field<Entity, RootAlias, Context>>(fields: F, distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases | ExtractRawAliases<readonly [F]>, ExtractRootFields<F & string, RootAlias, Context>>;
296
+ /**
297
+ * Adds fields to an existing SELECT query.
298
+ */
299
+ addSelect<const F extends Field<Entity, RootAlias, Context> | readonly Field<Entity, RootAlias, Context>[]>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases | ExtractRawAliases<F extends readonly unknown[] ? F : [F]>, Fields | ExtractRootFields<F extends readonly (infer U)[] ? U & string : F & string, RootAlias, Context>>;
300
+ distinct(): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
301
+ /** postgres only */
302
+ distinctOn<const F extends readonly Field<Entity, RootAlias, Context>[]>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
145
303
  /** postgres only */
146
- distinctOn(fields: EntityKeyOrString<Entity> | EntityKeyOrString<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
147
- insert(data: RequiredEntityData<Entity> | RequiredEntityData<Entity>[]): InsertQueryBuilder<Entity>;
148
- update(data: EntityData<Entity>): UpdateQueryBuilder<Entity>;
149
- delete(cond?: QBFilterQuery): DeleteQueryBuilder<Entity>;
304
+ distinctOn<F extends Field<Entity, RootAlias, Context>>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
305
+ /**
306
+ * Creates an INSERT query with the given data.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * await em.createQueryBuilder(User)
311
+ * .insert({ name: 'John', email: 'john@example.com' })
312
+ * .execute();
313
+ *
314
+ * // Bulk insert
315
+ * await em.createQueryBuilder(User)
316
+ * .insert([{ name: 'John' }, { name: 'Jane' }])
317
+ * .execute();
318
+ * ```
319
+ */
320
+ insert(data: RequiredEntityData<Entity> | RequiredEntityData<Entity>[]): InsertQueryBuilder<Entity, RootAlias, Context>;
321
+ /**
322
+ * Creates an UPDATE query with the given data.
323
+ * Use `where()` to specify which rows to update.
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * await em.createQueryBuilder(User)
328
+ * .update({ name: 'John Doe' })
329
+ * .where({ id: 1 })
330
+ * .execute();
331
+ * ```
332
+ */
333
+ update(data: EntityData<Entity>): UpdateQueryBuilder<Entity, RootAlias, Context>;
334
+ /**
335
+ * Creates a DELETE query.
336
+ * Use `where()` to specify which rows to delete.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * await em.createQueryBuilder(User)
341
+ * .delete()
342
+ * .where({ id: 1 })
343
+ * .execute();
344
+ *
345
+ * // Or pass the condition directly
346
+ * await em.createQueryBuilder(User)
347
+ * .delete({ isActive: false })
348
+ * .execute();
349
+ * ```
350
+ */
351
+ delete(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): DeleteQueryBuilder<Entity, RootAlias, Context>;
352
+ /**
353
+ * Creates a TRUNCATE query to remove all rows from the table.
354
+ */
150
355
  truncate(): TruncateQueryBuilder<Entity>;
151
- count(field?: EntityKeyOrString<Entity> | EntityKeyOrString<Entity>[], distinct?: boolean): CountQueryBuilder<Entity>;
152
- join<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: QBFilterQuery, type?: JoinType, path?: string, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>>;
153
- innerJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: QBFilterQuery, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>>;
154
- innerJoinLateral(field: RawQueryFragment | QueryBuilder<any>, alias: string, cond: QBFilterQuery, schema?: string): this;
155
- leftJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: QBFilterQuery, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>>;
156
- leftJoinLateral(field: RawQueryFragment | QueryBuilder<any>, alias: string, cond: QBFilterQuery, schema?: string): this;
157
- joinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | [field: Field, qb: RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: QBFilterQuery, type?: JoinType, path?: string, fields?: string[], schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>>;
158
- leftJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | [field: Field, qb: RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: QBFilterQuery, fields?: string[], schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>>;
159
- leftJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: [field: Field, qb: RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: QBFilterQuery, fields?: string[], schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>>;
160
- innerJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field | [field: Field, qb: RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: QBFilterQuery, fields?: string[], schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>>;
161
- innerJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: [field: Field, qb: RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: QBFilterQuery, fields?: string[], schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>>;
162
- protected getFieldsForJoinedLoad(prop: EntityProperty<Entity>, alias: string, explicitFields?: string[]): Field<Entity>[];
356
+ /**
357
+ * Creates a COUNT query to count matching rows.
358
+ *
359
+ * @example
360
+ * ```ts
361
+ * const count = await em.createQueryBuilder(User)
362
+ * .count()
363
+ * .where({ isActive: true })
364
+ * .execute('get');
365
+ * ```
366
+ */
367
+ count<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): CountQueryBuilder<Entity>;
368
+ /**
369
+ * Adds a JOIN clause to the query for an entity relation.
370
+ *
371
+ * @example
372
+ * ```ts
373
+ * const qb = em.createQueryBuilder(Book, 'b');
374
+ * qb.select('*')
375
+ * .join('b.author', 'a')
376
+ * .where({ 'a.name': 'John' });
377
+ * ```
378
+ */
379
+ join<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field, alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, type?: JoinType, path?: string, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>, RawAliases>;
380
+ /**
381
+ * Adds a JOIN clause to the query for a subquery.
382
+ */
383
+ join<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, type?: JoinType, path?: string, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases>;
384
+ /**
385
+ * Adds an INNER JOIN clause to the query for an entity relation.
386
+ */
387
+ innerJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field, alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>, RawAliases>;
388
+ /**
389
+ * Adds an INNER JOIN clause to the query for a subquery.
390
+ */
391
+ innerJoin<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases>;
392
+ innerJoinLateral<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases>;
393
+ /**
394
+ * Adds a LEFT JOIN clause to the query for an entity relation.
395
+ */
396
+ leftJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(field: Field, alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field> & {}, ModifyContext<Entity, Context, Field, Alias>, RawAliases>;
397
+ /**
398
+ * Adds a LEFT JOIN clause to the query for a subquery.
399
+ */
400
+ leftJoin<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases>;
401
+ leftJoinLateral<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases>;
402
+ /**
403
+ * Adds a JOIN clause and automatically selects the joined entity's fields.
404
+ * This is useful for eager loading related entities.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * const qb = em.createQueryBuilder(Book, 'b');
409
+ * qb.select('*')
410
+ * .joinAndSelect('b.author', 'a')
411
+ * .where({ 'a.name': 'John' });
412
+ * ```
413
+ */
414
+ joinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>, ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]] | undefined = undefined>(field: Field | [Field, RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, type?: JoinType, path?: string, fields?: JoinFields, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>, RawAliases, ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>>;
415
+ leftJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>, ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]] | undefined = undefined>(field: Field | [Field, RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, fields?: JoinFields, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>, RawAliases, ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>>;
416
+ leftJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>, ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]] | undefined = undefined>(field: [Field, RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, fields?: JoinFields, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>, RawAliases, ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>>;
417
+ innerJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>, ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]] | undefined = undefined>(field: Field | [Field, RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, fields?: JoinFields, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>, RawAliases, ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>>;
418
+ innerJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>, ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]] | undefined = undefined>(field: [Field, RawQueryFragment | QueryBuilder<any>], alias: Alias, cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>, fields?: JoinFields, schema?: string): SelectQueryBuilder<Entity, RootAlias, ModifyHint<RootAlias, Context, Hint, Field, true> & {}, ModifyContext<Entity, Context, Field, Alias, true>, RawAliases, ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>>;
419
+ protected getFieldsForJoinedLoad(prop: EntityProperty<Entity>, alias: string, explicitFields?: readonly string[]): InternalField<Entity>[];
163
420
  /**
164
421
  * Apply filters to the QB where condition.
165
422
  */
166
423
  applyFilters(filterOptions?: FilterOptions): Promise<void>;
167
- private readonly autoJoinedPaths;
168
424
  /**
169
425
  * @internal
170
426
  */
@@ -174,29 +430,193 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
174
430
  */
175
431
  applyJoinedFilters(em: EntityManager, filterOptions: FilterOptions | undefined): Promise<void>;
176
432
  withSubQuery(subQuery: RawQueryFragment | NativeQueryBuilder, alias: string): this;
177
- where(cond: QBFilterQuery<Entity>, operator?: keyof typeof GroupOperator): this;
178
- where(cond: string, params?: any[], operator?: keyof typeof GroupOperator): this;
179
- andWhere(cond: QBFilterQuery<Entity>): this;
180
- andWhere(cond: string, params?: any[]): this;
181
- orWhere(cond: QBFilterQuery<Entity>): this;
182
- orWhere(cond: string, params?: any[]): this;
183
- orderBy(orderBy: QBQueryOrderMap<Entity> | QBQueryOrderMap<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
184
- andOrderBy(orderBy: QBQueryOrderMap<Entity> | QBQueryOrderMap<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
433
+ /**
434
+ * Adds a WHERE clause to the query using an object condition.
435
+ *
436
+ * Supports filtering by:
437
+ * - Direct entity properties: `{ name: 'John' }`
438
+ * - Nested relations/embedded: `{ author: { name: 'John' } }`
439
+ * - Aliased properties after joins: `{ 'a.name': 'John' }` or `{ 'b.title': 'test' }`
440
+ * - Filter operators: `{ age: { $gte: 18 } }`
441
+ * - Logical operators: `{ $or: [{ name: 'John' }, { name: 'Jane' }] }`
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * // Filter by entity properties
446
+ * qb.where({ name: 'John', age: { $gte: 18 } });
447
+ *
448
+ * // Filter by nested relation
449
+ * qb.where({ author: { name: 'John' } });
450
+ *
451
+ * // Filter by aliased properties after join
452
+ * qb.leftJoin('a.books', 'b').where({ 'b.title': 'test' });
453
+ *
454
+ * // Combine with logical operators
455
+ * qb.where({ $or: [{ status: 'active' }, { role: 'admin' }] });
456
+ * ```
457
+ */
458
+ where(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>, operator?: keyof typeof GroupOperator): this;
459
+ /**
460
+ * Adds a WHERE clause to the query using a raw SQL string or fragment.
461
+ *
462
+ * @example
463
+ * ```ts
464
+ * // Raw SQL with parameters
465
+ * qb.where('name = ? AND age >= ?', ['John', 18]);
466
+ *
467
+ * // Using raw() helper
468
+ * qb.where(raw('lower(name) = ?', ['john']));
469
+ * ```
470
+ */
471
+ where(cond: string | RawQueryFragment, params?: any[], operator?: keyof typeof GroupOperator): this;
472
+ /**
473
+ * Adds an AND WHERE clause to the query using an object condition.
474
+ *
475
+ * @example
476
+ * ```ts
477
+ * qb.where({ status: 'active' }).andWhere({ role: 'admin' });
478
+ * qb.where({ name: 'John' }).andWhere({ 'b.title': 'test' });
479
+ * ```
480
+ */
481
+ andWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
482
+ /**
483
+ * Adds an AND WHERE clause to the query using a raw SQL string or fragment.
484
+ *
485
+ * @example
486
+ * ```ts
487
+ * qb.where({ status: 'active' }).andWhere('age >= ?', [18]);
488
+ * ```
489
+ */
490
+ andWhere(cond: string | RawQueryFragment, params?: any[]): this;
491
+ /**
492
+ * Adds an OR WHERE clause to the query using an object condition.
493
+ *
494
+ * @example
495
+ * ```ts
496
+ * qb.where({ status: 'active' }).orWhere({ role: 'admin' });
497
+ * qb.where({ name: 'John' }).orWhere({ name: 'Jane' });
498
+ * ```
499
+ */
500
+ orWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
501
+ /**
502
+ * Adds an OR WHERE clause to the query using a raw SQL string or fragment.
503
+ *
504
+ * @example
505
+ * ```ts
506
+ * qb.where({ status: 'active' }).orWhere('role = ?', ['admin']);
507
+ * ```
508
+ */
509
+ orWhere(cond: string | RawQueryFragment, params?: any[]): this;
510
+ /**
511
+ * Adds an ORDER BY clause to the query, replacing any existing order.
512
+ *
513
+ * @example
514
+ * ```ts
515
+ * qb.orderBy({ name: 'asc', createdAt: 'desc' });
516
+ * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
517
+ * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
518
+ * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
519
+ * ```
520
+ */
521
+ orderBy(orderBy: ContextOrderByMap<Entity, RootAlias, Context, RawAliases> | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
522
+ /**
523
+ * Adds an ORDER BY clause to the query, replacing any existing order.
524
+ *
525
+ * @example
526
+ * ```ts
527
+ * qb.orderBy({ name: 'asc', createdAt: 'desc' });
528
+ * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
529
+ * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
530
+ * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
531
+ * ```
532
+ */
533
+ orderBy<const T extends Record<string, QueryOrderKeysFlat>>(orderBy: T & {
534
+ [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string> ? T[K] : (K extends RawAliases ? T[K] : never);
535
+ }): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
536
+ /**
537
+ * Adds additional ORDER BY clause without replacing existing order.
538
+ */
539
+ andOrderBy(orderBy: ContextOrderByMap<Entity, RootAlias, Context, RawAliases> | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
540
+ /**
541
+ * Adds additional ORDER BY clause without replacing existing order.
542
+ */
543
+ andOrderBy<const T extends Record<string, QueryOrderKeysFlat>>(orderBy: T & {
544
+ [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string> ? T[K] : (K extends RawAliases ? T[K] : never);
545
+ }): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
185
546
  private processOrderBy;
186
- groupBy(fields: EntityKeyOrString<Entity> | readonly EntityKeyOrString<Entity>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
187
- having(cond?: QBFilterQuery | string, params?: any[], operator?: keyof typeof GroupOperator): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
188
- andHaving(cond?: QBFilterQuery | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
189
- orHaving(cond?: QBFilterQuery | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
190
- onConflict(fields?: Field<Entity> | Field<Entity>[]): InsertQueryBuilder<Entity>;
547
+ /** Collect custom aliases from select fields (stored as 'resolved as alias' strings by select()). */
548
+ private getSelectAliases;
549
+ /**
550
+ * Adds a GROUP BY clause to the query.
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * qb.select([raw('count(*) as count'), 'status'])
555
+ * .groupBy('status');
556
+ * ```
557
+ */
558
+ groupBy<const F extends readonly Field<Entity, RootAlias, Context>[]>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
559
+ /**
560
+ * Adds a GROUP BY clause to the query.
561
+ *
562
+ * @example
563
+ * ```ts
564
+ * qb.select([raw('count(*) as count'), 'status'])
565
+ * .groupBy('status');
566
+ * ```
567
+ */
568
+ groupBy<F extends Field<Entity, RootAlias, Context>>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
569
+ /**
570
+ * Adds a GROUP BY clause to the query.
571
+ *
572
+ * @example
573
+ * ```ts
574
+ * qb.select([raw('count(*) as count'), 'status'])
575
+ * .groupBy('status');
576
+ * ```
577
+ */
578
+ groupBy<const P extends string>(fields: NestedAutoPath<Entity, RootAlias, Context, P> | readonly NestedAutoPath<Entity, RootAlias, Context, P>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
579
+ /**
580
+ * Adds a HAVING clause to the query, typically used with GROUP BY.
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * qb.select([raw('count(*) as count'), 'status'])
585
+ * .groupBy('status')
586
+ * .having({ count: { $gt: 5 } });
587
+ * ```
588
+ */
589
+ having(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[], operator?: keyof typeof GroupOperator): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
590
+ andHaving(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
591
+ orHaving(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
592
+ onConflict<F extends Field<Entity, RootAlias, Context>>(fields?: F | F[] | RawQueryFragment): InsertQueryBuilder<Entity, RootAlias, Context>;
191
593
  ignore(): this;
192
- merge(data?: EntityData<Entity> | Field<Entity>[]): this;
193
- returning(fields?: Field<Entity> | Field<Entity>[]): this;
594
+ merge<const P extends string>(data: readonly NestedAutoPath<Entity, RootAlias, Context, P>[]): this;
595
+ merge<F extends Field<Entity, RootAlias, Context>>(data?: EntityData<Entity> | F[]): this;
596
+ returning<F extends Field<Entity, RootAlias, Context>>(fields?: F | F[]): this;
194
597
  /**
195
598
  * @internal
196
599
  */
197
600
  populate(populate: PopulateOptions<Entity>[], populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`, populateFilter?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`): this;
198
- limit(limit?: number, offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
199
- offset(offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
601
+ /**
602
+ * Sets a LIMIT clause to restrict the number of results.
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * qb.select('*').limit(10); // First 10 results
607
+ * qb.select('*').limit(10, 20); // 10 results starting from offset 20
608
+ * ```
609
+ */
610
+ limit(limit?: number, offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
611
+ /**
612
+ * Sets an OFFSET clause to skip a number of results.
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * qb.select('*').limit(10).offset(20); // Results 21-30
617
+ * ```
618
+ */
619
+ offset(offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
200
620
  withSchema(schema?: string): this;
201
621
  setLockMode(mode?: LockMode, tables?: string[]): this;
202
622
  setFlushMode(flushMode?: FlushMode): this;
@@ -208,6 +628,10 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
208
628
  * Adds index hint to the FROM clause.
209
629
  */
210
630
  indexHint(sql: string | undefined): this;
631
+ /**
632
+ * Adds COLLATE clause to ORDER BY expressions.
633
+ */
634
+ collation(collation: string | undefined): this;
211
635
  /**
212
636
  * Prepend comment to the sql query using the syntax `/* ... *&#8205;/`. Some characters are forbidden such as `/*, *&#8205;/` and `?`.
213
637
  */
@@ -222,13 +646,13 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
222
646
  * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
223
647
  * Allows setting a main string alias of the selection data.
224
648
  */
225
- from<Entity extends AnyEntity<Entity> = AnyEntity>(target: QueryBuilder<Entity>, aliasName?: string): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
226
- from<Entity extends AnyEntity<Entity> = AnyEntity>(target: EntityName<Entity>): SelectQueryBuilder<Entity, RootAlias, Hint, Context>;
227
- getNativeQuery(processVirtualEntity?: boolean): NativeQueryBuilder;
649
+ from<Entity extends object>(target: QueryBuilder<Entity>, aliasName?: string): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
228
650
  /**
229
- * @internal
651
+ * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
652
+ * Allows setting a main string alias of the selection data.
230
653
  */
231
- clearRawFragmentsCache(): void;
654
+ from<Entity extends object>(target: EntityName<Entity>): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
655
+ getNativeQuery(processVirtualEntity?: boolean): NativeQueryBuilder;
232
656
  /**
233
657
  * Returns the query with parameters as wildcards.
234
658
  */
@@ -260,11 +684,17 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
260
684
  /**
261
685
  * @internal
262
686
  */
263
- getNextAlias(entityName?: string): string;
687
+ getNextAlias(entityName?: string | EntityName): string;
688
+ /**
689
+ * Registers a join for a specific polymorphic target type.
690
+ * Used by the driver to create per-target LEFT JOINs for JOINED loading.
691
+ * @internal
692
+ */
693
+ addPolymorphicJoin(prop: EntityProperty, targetMeta: EntityMetadata, ownerAlias: string, alias: string, type: JoinType, path: string, schema?: string): void;
264
694
  /**
265
695
  * @internal
266
696
  */
267
- getAliasMap(): Dictionary<string>;
697
+ getAliasMap(): Dictionary<EntityName>;
268
698
  /**
269
699
  * Executes this QB and returns the raw results, mapped to the property names (unless disabled via last parameter).
270
700
  * Use `method` to specify what kind of result you want to get (array/single/meta).
@@ -287,36 +717,40 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
287
717
  * }
288
718
  * ```
289
719
  */
290
- stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint>>;
720
+ stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
291
721
  /**
292
722
  * Alias for `qb.getResultList()`
293
723
  */
294
- getResult(): Promise<Loaded<Entity, Hint>[]>;
724
+ getResult(): Promise<Loaded<Entity, Hint, Fields>[]>;
295
725
  /**
296
726
  * Executes the query, returning array of results mapped to entity instances.
297
727
  */
298
- getResultList(limit?: number): Promise<Loaded<Entity, Hint>[]>;
728
+ getResultList(limit?: number): Promise<Loaded<Entity, Hint, Fields>[]>;
299
729
  private propagatePopulateHint;
300
730
  private mapResult;
301
731
  private mapResults;
302
732
  /**
303
733
  * Executes the query, returning the first result or null
304
734
  */
305
- getSingleResult(): Promise<Entity | null>;
735
+ getSingleResult(): Promise<Loaded<Entity, Hint, Fields> | null>;
306
736
  /**
307
737
  * Executes count query (without offset and limit), returning total count of results
308
738
  */
309
- getCount(field?: EntityKeyOrString<Entity> | EntityKeyOrString<Entity>[], distinct?: boolean): Promise<number>;
739
+ getCount<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): Promise<number>;
310
740
  /**
311
741
  * Executes the query, returning both array of results and total count query (without offset and limit).
312
742
  */
313
- getResultAndCount(): Promise<[Entity[], number]>;
743
+ getResultAndCount(): Promise<[Loaded<Entity, Hint, Fields>[], number]>;
314
744
  /**
315
745
  * Returns native query builder instance with sub-query aliased with given alias.
316
- * You can provide `EntityName.propName` as alias, then the field name will be used based on the metadata
317
746
  */
318
747
  as(alias: string): NativeQueryBuilder;
319
- clone(reset?: boolean | string[]): QueryBuilder<Entity>;
748
+ /**
749
+ * Returns native query builder instance with sub-query aliased with given alias.
750
+ * You can provide the target entity name as the first parameter and use the second parameter to point to an existing property to infer its field name.
751
+ */
752
+ as<T>(targetEntity: EntityName<T>, alias: EntityKey<T>): NativeQueryBuilder;
753
+ clone(reset?: boolean | string[], preserve?: string[]): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields>;
320
754
  /**
321
755
  * Sets logger context for this query builder.
322
756
  */
@@ -326,11 +760,45 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
326
760
  */
327
761
  getLoggerContext<T extends Dictionary & LoggingOptions = Dictionary>(): T;
328
762
  private fromVirtual;
763
+ /**
764
+ * Adds a join from a property object. Used internally for TPT joins where the property
765
+ * is synthetic (not in entity.properties) but defined on metadata (e.g., tptParentProp).
766
+ * The caller must create the alias first via createAlias().
767
+ * @internal
768
+ */
769
+ addPropertyJoin(prop: EntityProperty, ownerAlias: string, alias: string, type: JoinType, path: string, schema?: string): string;
329
770
  private joinReference;
330
- protected prepareFields<T>(fields: Field<T>[], type?: 'where' | 'groupBy' | 'sub-query'): (string | RawQueryFragment)[];
771
+ protected prepareFields<T>(fields: InternalField<T>[], type?: 'where' | 'groupBy' | 'sub-query', schema?: string): (string | RawQueryFragment)[];
772
+ /**
773
+ * Resolves nested paths like `a.books.title` to their actual field references.
774
+ * Auto-joins relations as needed and returns `{alias}.{field}`.
775
+ * For embeddeds: navigates into flattened embeddeds to return the correct field name.
776
+ */
777
+ protected resolveNestedPath(field: string): string | string[];
331
778
  private init;
332
779
  private getQueryBase;
333
780
  private applyDiscriminatorCondition;
781
+ /**
782
+ * Ensures TPT joins are applied. Can be called early before finalize() to populate
783
+ * the _tptAlias map for use in join resolution. Safe to call multiple times.
784
+ * @internal
785
+ */
786
+ ensureTPTJoins(): void;
787
+ /**
788
+ * For TPT (Table-Per-Type) inheritance: INNER JOINs parent tables.
789
+ * When querying a child entity, we need to join all parent tables.
790
+ * Field selection is handled separately in addTPTParentFields().
791
+ */
792
+ private applyTPTJoins;
793
+ /**
794
+ * For TPT inheritance: adds field selections from parent tables.
795
+ */
796
+ private addTPTParentFields;
797
+ /**
798
+ * For TPT polymorphic queries: LEFT JOINs all child tables when querying a TPT base class.
799
+ * Adds discriminator and child fields to determine and load the concrete type.
800
+ */
801
+ private applyTPTPolymorphicJoins;
334
802
  private finalize;
335
803
  /** @internal */
336
804
  processPopulateHint(): void;
@@ -343,10 +811,32 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
343
811
  private processNestedJoins;
344
812
  private hasToManyJoins;
345
813
  protected wrapPaginateSubQuery(meta: EntityMetadata): void;
346
- private pruneExtraJoins;
814
+ /**
815
+ * Computes the set of populate paths from the _populate hints.
816
+ */
817
+ protected getPopulatePaths(): Set<string>;
818
+ protected normalizeJoinPath(join: JoinOptions, meta: EntityMetadata): string;
819
+ /**
820
+ * Transfers WHERE conditions to ORDER BY joins that are not used for population.
821
+ * This ensures the outer query's ORDER BY uses the same filtered rows as the subquery.
822
+ * GH #6160
823
+ */
824
+ protected transferConditionsForOrderByJoins(meta: EntityMetadata, cond: Dictionary | undefined, populatePaths: Set<string>): void;
825
+ /**
826
+ * Removes joins that are not used for population or ordering to improve performance.
827
+ */
828
+ protected pruneJoinsForPagination(meta: EntityMetadata, populatePaths: Set<string>): void;
829
+ /**
830
+ * Transfers WHERE conditions that reference a join alias to the join's ON clause.
831
+ * This is needed when a join is kept for ORDER BY after pagination wrapping,
832
+ * so the outer query orders by the same filtered rows as the subquery.
833
+ * @internal
834
+ */
835
+ protected transferConditionsToJoin(cond: Dictionary, join: JoinOptions, path?: string): void;
347
836
  private wrapModifySubQuery;
348
837
  private getSchema;
349
- private createAlias;
838
+ /** @internal */
839
+ createAlias<U = unknown>(entityName: EntityName<U>, aliasName: string, subQuery?: NativeQueryBuilder): Alias<U>;
350
840
  private createMainAlias;
351
841
  private fromSubQuery;
352
842
  private fromEntityName;
@@ -354,11 +844,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
354
844
  private ensureFromClause;
355
845
  private ensureNotFinalized;
356
846
  }
357
- export interface RunQueryBuilder<Entity extends object> extends Omit<QueryBuilder<Entity, any, any>, 'getResult' | 'getSingleResult' | 'getResultList' | 'where'> {
358
- where(cond: QBFilterQuery<Entity> | string, params?: keyof typeof GroupOperator | any[], operator?: keyof typeof GroupOperator): this;
847
+ export interface RunQueryBuilder<Entity extends object, RootAlias extends string = never, Context extends object = never, RawAliases extends string = never> extends Omit<QueryBuilder<Entity, RootAlias, never, Context, RawAliases, '*'>, 'getResult' | 'getSingleResult' | 'getResultList' | 'where'> {
848
+ where(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: keyof typeof GroupOperator | any[], operator?: keyof typeof GroupOperator): this;
359
849
  execute<Result = QueryResult<Entity>>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
360
850
  }
361
- export interface SelectQueryBuilder<Entity extends object = AnyEntity, RootAlias extends string = never, Hint extends string = never, Context extends object = never> extends QueryBuilder<Entity, RootAlias, Hint, Context> {
851
+ export interface SelectQueryBuilder<Entity extends object = AnyEntity, RootAlias extends string = never, Hint extends string = never, Context extends object = never, RawAliases extends string = never, Fields extends string = '*'> extends QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields> {
362
852
  execute<Result = Entity[]>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
363
853
  execute<Result = Entity[]>(method: 'all', mapResults?: boolean): Promise<Result>;
364
854
  execute<Result = Entity>(method: 'get', mapResults?: boolean): Promise<Result>;
@@ -378,11 +868,11 @@ export interface CountQueryBuilder<Entity extends object> extends QueryBuilder<E
378
868
  count: number;
379
869
  }>>(method: 'run', mapResults?: boolean): Promise<Result>;
380
870
  }
381
- export interface InsertQueryBuilder<T extends object> extends RunQueryBuilder<T> {
871
+ export interface InsertQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
382
872
  }
383
- export interface UpdateQueryBuilder<T extends object> extends RunQueryBuilder<T> {
873
+ export interface UpdateQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
384
874
  }
385
- export interface DeleteQueryBuilder<T extends object> extends RunQueryBuilder<T> {
875
+ export interface DeleteQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
386
876
  }
387
877
  export interface TruncateQueryBuilder<T extends object> extends RunQueryBuilder<T> {
388
878
  }