@mikro-orm/sql 7.0.4 → 7.0.5-dev.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 (87) hide show
  1. package/AbstractSqlConnection.d.ts +58 -94
  2. package/AbstractSqlConnection.js +238 -235
  3. package/AbstractSqlDriver.d.ts +155 -410
  4. package/AbstractSqlDriver.js +1941 -2064
  5. package/AbstractSqlPlatform.d.ts +73 -83
  6. package/AbstractSqlPlatform.js +158 -162
  7. package/PivotCollectionPersister.d.ts +15 -33
  8. package/PivotCollectionPersister.js +160 -158
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +22 -67
  11. package/SqlEntityManager.js +38 -54
  12. package/SqlEntityRepository.d.ts +14 -14
  13. package/SqlEntityRepository.js +23 -23
  14. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  15. package/dialects/mssql/MsSqlNativeQueryBuilder.js +194 -192
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +45 -64
  17. package/dialects/mysql/BaseMySqlPlatform.js +131 -134
  18. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  19. package/dialects/mysql/MySqlExceptionConverter.js +77 -91
  20. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  21. package/dialects/mysql/MySqlNativeQueryBuilder.js +69 -66
  22. package/dialects/mysql/MySqlSchemaHelper.d.ts +39 -39
  23. package/dialects/mysql/MySqlSchemaHelper.js +319 -327
  24. package/dialects/oracledb/OracleDialect.d.ts +52 -81
  25. package/dialects/oracledb/OracleDialect.js +149 -155
  26. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  27. package/dialects/oracledb/OracleNativeQueryBuilder.js +236 -232
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +106 -109
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +353 -354
  30. package/dialects/postgresql/FullTextType.d.ts +6 -10
  31. package/dialects/postgresql/FullTextType.js +51 -51
  32. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  33. package/dialects/postgresql/PostgreSqlExceptionConverter.js +43 -55
  34. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  35. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  36. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +82 -102
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +705 -733
  38. package/dialects/sqlite/BaseSqliteConnection.d.ts +5 -3
  39. package/dialects/sqlite/BaseSqliteConnection.js +19 -21
  40. package/dialects/sqlite/NodeSqliteDialect.d.ts +1 -1
  41. package/dialects/sqlite/NodeSqliteDialect.js +23 -23
  42. package/dialects/sqlite/SqliteDriver.d.ts +1 -1
  43. package/dialects/sqlite/SqliteDriver.js +3 -3
  44. package/dialects/sqlite/SqliteExceptionConverter.d.ts +6 -6
  45. package/dialects/sqlite/SqliteExceptionConverter.js +51 -67
  46. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  47. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  48. package/dialects/sqlite/SqlitePlatform.d.ts +72 -63
  49. package/dialects/sqlite/SqlitePlatform.js +139 -139
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +60 -70
  51. package/dialects/sqlite/SqliteSchemaHelper.js +520 -533
  52. package/package.json +2 -2
  53. package/plugin/index.d.ts +35 -42
  54. package/plugin/index.js +36 -43
  55. package/plugin/transformer.d.ts +94 -117
  56. package/plugin/transformer.js +881 -890
  57. package/query/ArrayCriteriaNode.d.ts +4 -4
  58. package/query/ArrayCriteriaNode.js +18 -18
  59. package/query/CriteriaNode.d.ts +25 -35
  60. package/query/CriteriaNode.js +123 -133
  61. package/query/CriteriaNodeFactory.d.ts +6 -49
  62. package/query/CriteriaNodeFactory.js +94 -97
  63. package/query/NativeQueryBuilder.d.ts +118 -118
  64. package/query/NativeQueryBuilder.js +480 -484
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +282 -298
  67. package/query/QueryBuilder.d.ts +905 -1557
  68. package/query/QueryBuilder.js +2192 -2322
  69. package/query/QueryBuilderHelper.d.ts +72 -153
  70. package/query/QueryBuilderHelper.js +1028 -1079
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +46 -53
  73. package/query/enums.d.ts +14 -14
  74. package/query/enums.js +14 -14
  75. package/query/raw.d.ts +6 -16
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +50 -73
  78. package/schema/DatabaseSchema.js +307 -331
  79. package/schema/DatabaseTable.d.ts +73 -96
  80. package/schema/DatabaseTable.js +927 -1012
  81. package/schema/SchemaComparator.d.ts +66 -70
  82. package/schema/SchemaComparator.js +740 -766
  83. package/schema/SchemaHelper.d.ts +95 -109
  84. package/schema/SchemaHelper.js +659 -675
  85. package/schema/SqlSchemaGenerator.d.ts +58 -78
  86. package/schema/SqlSchemaGenerator.js +501 -535
  87. package/typings.d.ts +266 -380
@@ -1,44 +1,4 @@
1
- import {
2
- type AnyEntity,
3
- type AutoPath,
4
- type Collection,
5
- type ConnectionType,
6
- type Dictionary,
7
- type EntityData,
8
- type EntityDTOFlat,
9
- type EntityDTOProp,
10
- type EntityKey,
11
- type EntityManager,
12
- EntityMetadata,
13
- type EntityName,
14
- type EntityProperty,
15
- type ExpandProperty,
16
- type FilterObject,
17
- type FilterOptions,
18
- type FilterValue,
19
- type FlushMode,
20
- type GroupOperator,
21
- type Loaded,
22
- LockMode,
23
- type LoggingOptions,
24
- type MetadataStorage,
25
- type PrimaryProperty,
26
- type ObjectQuery,
27
- PopulateHint,
28
- type PopulateOptions,
29
- type PopulatePath,
30
- QueryFlag,
31
- type QueryOrderKeysFlat,
32
- type QueryOrderMap,
33
- type QueryResult,
34
- RawQueryFragment,
35
- type Raw,
36
- type RequiredEntityData,
37
- type Scalar,
38
- type SerializeDTO,
39
- type Subquery,
40
- type Transaction,
41
- } from '@mikro-orm/core';
1
+ import { type AnyEntity, type AutoPath, type Collection, type ConnectionType, type Dictionary, type EntityData, type EntityDTOFlat, type EntityDTOProp, type EntityKey, type EntityManager, 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 PrimaryProperty, type ObjectQuery, PopulateHint, type PopulateOptions, type PopulatePath, QueryFlag, type QueryOrderKeysFlat, type QueryOrderMap, type QueryResult, RawQueryFragment, type Raw, type RequiredEntityData, type Scalar, type SerializeDTO, type Subquery, type Transaction } from '@mikro-orm/core';
42
2
  import { JoinType, QueryType } from './enums.js';
43
3
  import type { AbstractSqlDriver } from '../AbstractSqlDriver.js';
44
4
  import { type Alias, type OnConflictClause, QueryBuilderHelper } from './QueryBuilderHelper.js';
@@ -47,32 +7,32 @@ import type { ICriteriaNodeProcessOptions, InternalField, JoinOptions } from '..
47
7
  import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
48
8
  import { type CteOptions, NativeQueryBuilder } from './NativeQueryBuilder.js';
49
9
  export interface ExecuteOptions {
50
- mapResults?: boolean;
51
- mergeResults?: boolean;
10
+ mapResults?: boolean;
11
+ mergeResults?: boolean;
52
12
  }
53
13
  export interface QBStreamOptions {
54
- /**
55
- * Results are mapped to entities, if you set `mapResults: false` you will get POJOs instead.
56
- *
57
- * @default true
58
- */
59
- mapResults?: boolean;
60
- /**
61
- * When populating to-many relations, the ORM streams fully merged entities instead of yielding every row.
62
- * You can opt out of this behavior by specifying `mergeResults: false`. This will yield every row from
63
- * the SQL result, but still mapped to entities, meaning that to-many collections will contain at most
64
- * one item, and you will get duplicate root entities when they have multiple items in the populated
65
- * collection.
66
- *
67
- * @default true
68
- */
69
- mergeResults?: boolean;
70
- /**
71
- * When enabled, the driver will return the raw database results without renaming the fields to match the entity property names.
72
- *
73
- * @default false
74
- */
75
- rawResults?: boolean;
14
+ /**
15
+ * Results are mapped to entities, if you set `mapResults: false` you will get POJOs instead.
16
+ *
17
+ * @default true
18
+ */
19
+ mapResults?: boolean;
20
+ /**
21
+ * When populating to-many relations, the ORM streams fully merged entities instead of yielding every row.
22
+ * You can opt out of this behavior by specifying `mergeResults: false`. This will yield every row from
23
+ * the SQL result, but still mapped to entities, meaning that to-many collections will contain at most
24
+ * one item, and you will get duplicate root entities when they have multiple items in the populated
25
+ * collection.
26
+ *
27
+ * @default true
28
+ */
29
+ mergeResults?: boolean;
30
+ /**
31
+ * When enabled, the driver will return the raw database results without renaming the fields to match the entity property names.
32
+ *
33
+ * @default false
34
+ */
35
+ rawResults?: boolean;
76
36
  }
77
37
  type IsNever<T, True = true, False = false> = [T] extends [never] ? True : False;
78
38
  type GetAlias<T extends string> = T extends `${infer A}.${string}` ? A : never;
@@ -89,326 +49,147 @@ type AppendToHint<Parent extends string, Child extends string> = `${Parent}.${Ch
89
49
  * { b: ['books', 'b', Book, false] }
90
50
  */
91
51
  type AddToContext<Type extends object, Context, Field extends string, Alias extends string, Select extends boolean> = {
92
- [K in Alias]: [GetPath<Context, Field>, K, ExpandProperty<Type[GetPropName<Field> & keyof Type]>, Select];
52
+ [K in Alias]: [GetPath<Context, Field>, K, ExpandProperty<Type[GetPropName<Field> & keyof Type]>, Select];
93
53
  };
94
- type GetPath<Context, Field extends string> =
95
- GetAlias<Field> extends infer Alias
96
- ? IsNever<Alias> extends true
97
- ? GetPropName<Field>
98
- : Alias extends keyof Context
99
- ? Context[Alias] extends [infer Path, ...any[]]
100
- ? AppendToHint<Path & string, GetPropName<Field>>
101
- : GetPropName<Field>
102
- : GetPropName<Field>
103
- : GetPropName<Field>;
104
- type GetType<Type extends object, Context, Field extends string> =
105
- GetAlias<Field> extends infer Alias
106
- ? IsNever<Alias> extends true
107
- ? Type
108
- : [Context] extends [never]
109
- ? Type
110
- : Alias extends keyof Context
111
- ? Context[Alias] extends [string, string, infer PropType, any]
112
- ? PropType & object
113
- : Type
114
- : Type
115
- : Type;
116
- type AddToHint<RootAlias, Context, Field extends string, Select extends boolean = false> = Select extends true
117
- ? GetAlias<Field> extends infer Alias
118
- ? IsNever<Alias> extends true
119
- ? GetPropName<Field>
120
- : Alias extends RootAlias
121
- ? GetPropName<Field>
122
- : Alias extends keyof Context
123
- ? Context[Alias] extends [infer Path, ...any[]]
124
- ? AppendToHint<Path & string, GetPropName<Field>>
125
- : GetPropName<Field>
126
- : GetPropName<Field>
127
- : GetPropName<Field>
128
- : never;
129
- export type ModifyHint<RootAlias, Context, Hint extends string, Field extends string, Select extends boolean = false> =
130
- | Hint
131
- | AddToHint<RootAlias, Context, Field, Select>;
132
- export type ModifyContext<
133
- Entity extends object,
134
- Context,
135
- Field extends string,
136
- Alias extends string,
137
- Select extends boolean = false,
138
- > =
139
- IsNever<Context> extends true
140
- ? AddToContext<GetType<Entity, object, Field>, object, Field, Alias, Select>
141
- : Context & AddToContext<GetType<Entity, Context, Field>, Context, Field, Alias, Select>;
142
- type StripRootAlias<
143
- F extends string,
144
- RootAlias extends string,
145
- Context = never,
146
- > = F extends `${RootAlias}.${infer Field}`
147
- ? Field
148
- : F extends `${infer Alias}.${string}`
149
- ? Alias extends AliasNames<Context>
150
- ? never
151
- : F
152
- : F;
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>;
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;
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;
57
+ export type ModifyHint<RootAlias, Context, Hint extends string, Field extends string, Select extends boolean = false> = Hint | AddToHint<RootAlias, Context, Field, 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;
153
60
  type StripFieldAlias<F extends string> = F extends `${infer Path} as ${string}` ? Path : F;
154
- type ExtractRootFields<Fields, RootAlias extends string, Context = never> = [Fields] extends ['*']
155
- ? '*'
156
- : Fields extends `${RootAlias}.*`
157
- ? '*'
158
- : Fields extends string
159
- ? StripRootAlias<StripFieldAlias<Fields>, RootAlias, Context>
160
- : never;
61
+ type ExtractRootFields<Fields, RootAlias extends string, Context = never> = [Fields] extends ['*'] ? '*' : Fields extends `${RootAlias}.*` ? '*' : Fields extends string ? StripRootAlias<StripFieldAlias<Fields>, RootAlias, Context> : never;
161
62
  type PrefixWithPath<Path extends string, Field extends string> = `${Path}.${Field}`;
162
63
  type StripJoinAlias<F extends string, Alias extends string> = F extends `${Alias}.${infer Field}` ? Field : F;
163
- export type JoinSelectField<JoinedEntity, Alias extends string> =
164
- | (keyof JoinedEntity & string)
165
- | `${Alias}.${keyof JoinedEntity & string}`;
166
- type AddJoinFields<
167
- RootAlias,
168
- Context,
169
- Field extends string,
170
- Alias extends string,
171
- JoinFields extends readonly string[],
172
- > = JoinFields extends readonly (infer F)[]
173
- ? F extends string
174
- ? PrefixWithPath<AddToHint<RootAlias, Context, Field, true> & string, StripJoinAlias<F, Alias>>
175
- : never
176
- : never;
177
- export type ModifyFields<
178
- CurrentFields extends string,
179
- RootAlias,
180
- Context,
181
- Field extends string,
182
- Alias extends string,
183
- JoinFields extends readonly string[] | undefined,
184
- > = JoinFields extends readonly string[]
185
- ? CurrentFields | AddJoinFields<RootAlias, Context, Field, Alias, JoinFields>
186
- : CurrentFields;
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;
187
67
  type EntityRelations<T> = EntityKey<T, true>;
188
- type JoinedEntityType<Entity extends object, Context, Field extends string> = ExpandProperty<
189
- GetType<Entity, Context, Field>[GetPropName<Field> & keyof GetType<Entity, Context, Field>]
190
- >;
191
- type AliasNames<Context> = Context[keyof Context] extends infer Join
192
- ? Join extends any
193
- ? Join extends [string, infer Alias, any, any]
194
- ? Alias & string
195
- : never
196
- : never
197
- : never;
198
- type ContextRelationKeys<Context> = Context[keyof Context] extends infer Join
199
- ? Join extends any
200
- ? Join extends [string, infer Alias, infer Type, any]
201
- ? `${Alias & string}.${EntityRelations<Type & object>}`
202
- : never
203
- : never
204
- : never;
205
- export type QBField<Entity, RootAlias extends string, Context> =
206
- | EntityRelations<Entity>
207
- | `${RootAlias}.${EntityRelations<Entity>}`
208
- | ([Context] extends [never] ? never : ContextRelationKeys<Context>);
209
- type ContextFieldKeys<Context> = Context[keyof Context] extends infer Join
210
- ? Join extends any
211
- ? Join extends [string, infer Alias, infer Type, any]
212
- ? `${Alias & string}.${keyof Type & string}`
213
- : never
214
- : never
215
- : never;
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;
216
73
  type WithAlias<T extends string> = T | `${T} as ${string}`;
217
- export type Field<Entity, RootAlias extends string = never, Context = never> =
218
- | WithAlias<EntityKey<Entity>>
219
- | (IsNever<RootAlias> extends true ? never : WithAlias<`${RootAlias}.${EntityKey<Entity>}`> | `${RootAlias}.*`)
220
- | ([Context] extends [never] ? never : WithAlias<ContextFieldKeys<Context>> | `${AliasNames<Context>}.*`)
221
- | '*'
222
- | QueryBuilder<any>
223
- | NativeQueryBuilder
224
- | RawQueryFragment<any>
225
- | (RawQueryFragment & symbol);
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);
226
75
  type RootAliasOrderKeys<RootAlias extends string, Entity> = {
227
- [K in `${RootAlias}.${EntityKey<Entity>}`]?: QueryOrderKeysFlat;
76
+ [K in `${RootAlias}.${EntityKey<Entity>}`]?: QueryOrderKeysFlat;
228
77
  };
229
78
  type ContextOrderKeys<Context> = {
230
- [K in ContextFieldKeys<Context>]?: QueryOrderKeysFlat;
79
+ [K in ContextFieldKeys<Context>]?: QueryOrderKeysFlat;
231
80
  };
232
81
  type RawOrderKeys<RawAliases extends string> = {
233
- [K in RawAliases]?: QueryOrderKeysFlat;
82
+ [K in RawAliases]?: QueryOrderKeysFlat;
234
83
  };
235
- export type ContextOrderByMap<
236
- Entity,
237
- RootAlias extends string = never,
238
- Context = never,
239
- RawAliases extends string = never,
240
- > =
241
- | QueryOrderMap<Entity>
242
- | ((IsNever<RootAlias> extends true ? {} : RootAliasOrderKeys<RootAlias, Entity>) &
243
- ([Context] extends [never] ? {} : ContextOrderKeys<Context>) &
244
- (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawOrderKeys<RawAliases>));
245
- type AliasedPath<Alias extends string, Type, P extends string> = P extends `${Alias}.*`
246
- ? P
247
- : P extends `${Alias}.${infer Rest}`
248
- ? `${Alias}.${AutoPath<Type & object, Rest, `${PopulatePath.ALL}`>}`
249
- : never;
250
- type ContextAliasedPath<Context, P extends string> = Context[keyof Context] extends infer Join
251
- ? Join extends any
252
- ? Join extends [string, infer Alias, infer Type, any]
253
- ? AliasedPath<Alias & string, Type, P>
254
- : never
255
- : never
256
- : never;
257
- type NestedAutoPath<Entity, RootAlias extends string, Context, P extends string> = P extends `${string}:ref`
258
- ? never
259
- : P extends `${infer Path} as ${string}`
260
- ?
261
- | AliasedPath<RootAlias, Entity, Path>
262
- | ContextAliasedPath<Context, Path>
263
- | AutoPath<Entity, Path, `${PopulatePath.ALL}`> extends never
264
- ? never
265
- : P
266
- : AliasedPath<RootAlias, Entity, P> | ContextAliasedPath<Context, P> | AutoPath<Entity, P, `${PopulatePath.ALL}`>;
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}`>;
267
88
  type AliasedObjectQuery<Entity extends object, Alias extends string> = {
268
- [K in EntityKey<Entity> as `${Alias}.${K}`]?: ObjectQuery<Entity>[K];
89
+ [K in EntityKey<Entity> as `${Alias}.${K}`]?: ObjectQuery<Entity>[K];
269
90
  };
270
- type JoinCondition<JoinedEntity extends object, Alias extends string> = (
271
- | ObjectQuery<JoinedEntity>
272
- | AliasedObjectQuery<JoinedEntity, Alias>
273
- ) & {
274
- $not?: JoinCondition<JoinedEntity, Alias>;
275
- $or?: JoinCondition<JoinedEntity, Alias>[];
276
- $and?: JoinCondition<JoinedEntity, Alias>[];
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>[];
277
95
  };
278
96
  type RawJoinCondition = {
279
- [key: string]: FilterValue<Scalar> | RawQueryFragment;
97
+ [key: string]: FilterValue<Scalar> | RawQueryFragment;
280
98
  };
281
- type ExtractRawAliasFromField<F> =
282
- F extends RawQueryFragment<infer A>
283
- ? A extends string
284
- ? A
285
- : never
286
- : F extends `${string} as ${infer A}`
287
- ? A
288
- : never;
289
- type ExtractRawAliasesFromTuple<T extends readonly unknown[]> = T extends readonly [infer Head, ...infer Tail]
290
- ? ExtractRawAliasFromField<Head> | ExtractRawAliasesFromTuple<Tail>
291
- : never;
292
- type ExtractRawAliases<Fields> = Fields extends readonly unknown[]
293
- ? ExtractRawAliasesFromTuple<Fields>
294
- : ExtractRawAliasFromField<Fields>;
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>;
295
102
  type FlatOperatorMap = {
296
- $eq?: Scalar | readonly Scalar[] | Subquery | null;
297
- $ne?: Scalar | readonly Scalar[] | Subquery | null;
298
- $in?: readonly Scalar[] | Raw | Subquery;
299
- $nin?: readonly Scalar[] | Raw | Subquery;
300
- $gt?: Scalar | Subquery;
301
- $gte?: Scalar | Subquery;
302
- $lt?: Scalar | Subquery;
303
- $lte?: Scalar | Subquery;
304
- $like?: string;
305
- $re?: string;
306
- $ilike?: string;
307
- $fulltext?: string;
308
- $overlap?: readonly string[] | string | object;
309
- $contains?: readonly string[] | string | object;
310
- $contained?: readonly string[] | string | object;
311
- $exists?: boolean;
312
- $hasKey?: string;
313
- $hasKeys?: readonly string[];
314
- $hasSomeKeys?: readonly string[];
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[];
315
122
  };
316
123
  type AliasedFilterValue = Scalar | FlatOperatorMap | readonly Scalar[] | null | QueryBuilder<any> | NativeQueryBuilder;
317
124
  type TypedAliasedFilterValue<T> = FilterValue<ExpandProperty<T>> | QueryBuilder<any> | NativeQueryBuilder;
318
125
  type RootAliasFilterKeys<RootAlias extends string, Entity> = {
319
- [K in EntityKey<Entity> as `${RootAlias}.${K}`]?: TypedAliasedFilterValue<Entity[K]>;
126
+ [K in EntityKey<Entity> as `${RootAlias}.${K}`]?: TypedAliasedFilterValue<Entity[K]>;
320
127
  };
321
- type ContextFieldType<Context, K extends string> = Context[keyof Context] extends infer Join
322
- ? Join extends any
323
- ? Join extends [string, infer Alias, infer Type, any]
324
- ? K extends `${Alias & string}.${infer Prop}`
325
- ? Prop extends keyof Type
326
- ? TypedAliasedFilterValue<Type[Prop]>
327
- : never
328
- : never
329
- : never
330
- : never
331
- : never;
128
+ type ContextFieldType<Context, K extends string> = Context[keyof Context] extends infer Join ? Join extends any ? Join extends [string, infer Alias, infer Type, any] ? K extends `${Alias & string}.${infer Prop}` ? Prop extends keyof Type ? TypedAliasedFilterValue<Type[Prop]> : never : never : never : never : never;
332
129
  type ContextFilterKeys<Context> = {
333
- [K in ContextFieldKeys<Context>]?: ContextFieldType<Context, K>;
130
+ [K in ContextFieldKeys<Context>]?: ContextFieldType<Context, K>;
334
131
  };
335
132
  type RawFilterKeys<RawAliases extends string> = {
336
- [K in RawAliases]?: AliasedFilterValue;
133
+ [K in RawAliases]?: AliasedFilterValue;
337
134
  };
338
- type NestedFilterCondition<Entity, RootAlias extends string, Context, RawAliases extends string> = ObjectQuery<Entity> &
339
- (IsNever<RootAlias> extends true ? {} : string extends RootAlias ? {} : RootAliasFilterKeys<RootAlias, Entity>) &
340
- ([Context] extends [never] ? {} : ContextFilterKeys<Context>) &
341
- (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawFilterKeys<RawAliases>);
135
+ 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>);
342
136
  type GroupOperators<RootAlias extends string, Context, Entity, RawAliases extends string> = {
343
- $and?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
344
- $or?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
345
- $not?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>;
137
+ $and?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
138
+ $or?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>[];
139
+ $not?: NestedFilterCondition<Entity, RootAlias, Context, RawAliases>;
346
140
  };
347
- export type AliasedFilterCondition<
348
- RootAlias extends string,
349
- Context,
350
- Entity,
351
- RawAliases extends string = never,
352
- > = (IsNever<RootAlias> extends true ? {} : string extends RootAlias ? {} : RootAliasFilterKeys<RootAlias, Entity>) &
353
- ([Context] extends [never] ? {} : ContextFilterKeys<Context>) &
354
- (IsNever<RawAliases> extends true ? {} : string extends RawAliases ? {} : RawFilterKeys<RawAliases>) &
355
- GroupOperators<RootAlias, Context, Entity, RawAliases>;
356
- export type QBFilterQuery<
357
- Entity,
358
- RootAlias extends string = never,
359
- Context = never,
360
- RawAliases extends string = never,
361
- > = FilterObject<Entity> & AliasedFilterCondition<RootAlias, Context, Entity, RawAliases>;
141
+ 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>;
142
+ export type QBFilterQuery<Entity, RootAlias extends string = never, Context = never, RawAliases extends string = never> = FilterObject<Entity> & AliasedFilterCondition<RootAlias, Context, Entity, RawAliases>;
362
143
  /** @internal */
363
144
  export interface QBState<Entity extends object> {
364
- type?: QueryType;
365
- fields?: InternalField<Entity>[];
366
- populate: PopulateOptions<Entity>[];
367
- populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
368
- populateFilter?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
369
- resolvedPopulateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
370
- populateMap: Dictionary<string>;
371
- aliasCounter: number;
372
- flags: Set<QueryFlag>;
373
- finalized: boolean;
374
- populateHintFinalized: boolean;
375
- joins: Dictionary<JoinOptions>;
376
- explicitAlias: boolean;
377
- schema?: string;
378
- cond: Dictionary;
379
- data?: Dictionary;
380
- orderBy: QueryOrderMap<Entity>[];
381
- groupBy: InternalField<Entity>[];
382
- having: Dictionary;
383
- returning?: InternalField<Entity>[];
384
- onConflict?: OnConflictClause<Entity>[];
385
- limit?: number;
386
- offset?: number;
387
- distinctOn?: string[];
388
- joinedProps: Map<string, PopulateOptions<any>>;
389
- cache?: boolean | number | [string, number];
390
- indexHint?: string;
391
- collation?: string;
392
- comments: string[];
393
- hintComments: string[];
394
- flushMode?: FlushMode;
395
- lockMode?: LockMode;
396
- lockTables?: string[];
397
- subQueries: Dictionary<string>;
398
- mainAlias?: Alias<Entity>;
399
- aliases: Dictionary<Alias<any>>;
400
- tptAlias: Dictionary<string>;
401
- unionQuery?: {
402
- sql: string;
403
- params: readonly unknown[];
404
- };
405
- ctes: (CteOptions & {
406
- name: string;
407
- query: NativeQueryBuilder | RawQueryFragment;
408
- recursive?: boolean;
409
- })[];
410
- tptJoinsApplied: boolean;
411
- autoJoinedPaths: string[];
145
+ type?: QueryType;
146
+ fields?: InternalField<Entity>[];
147
+ populate: PopulateOptions<Entity>[];
148
+ populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
149
+ populateFilter?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
150
+ resolvedPopulateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`;
151
+ populateMap: Dictionary<string>;
152
+ aliasCounter: number;
153
+ flags: Set<QueryFlag>;
154
+ finalized: boolean;
155
+ populateHintFinalized: boolean;
156
+ joins: Dictionary<JoinOptions>;
157
+ explicitAlias: boolean;
158
+ schema?: string;
159
+ cond: Dictionary;
160
+ data?: Dictionary;
161
+ orderBy: QueryOrderMap<Entity>[];
162
+ groupBy: InternalField<Entity>[];
163
+ having: Dictionary;
164
+ returning?: InternalField<Entity>[];
165
+ onConflict?: OnConflictClause<Entity>[];
166
+ limit?: number;
167
+ offset?: number;
168
+ distinctOn?: string[];
169
+ joinedProps: Map<string, PopulateOptions<any>>;
170
+ cache?: boolean | number | [string, number];
171
+ indexHint?: string;
172
+ collation?: string;
173
+ comments: string[];
174
+ hintComments: string[];
175
+ flushMode?: FlushMode;
176
+ lockMode?: LockMode;
177
+ lockTables?: string[];
178
+ subQueries: Dictionary<string>;
179
+ mainAlias?: Alias<Entity>;
180
+ aliases: Dictionary<Alias<any>>;
181
+ tptAlias: Dictionary<string>;
182
+ unionQuery?: {
183
+ sql: string;
184
+ params: readonly unknown[];
185
+ };
186
+ ctes: (CteOptions & {
187
+ name: string;
188
+ query: NativeQueryBuilder | RawQueryFragment;
189
+ recursive?: boolean;
190
+ })[];
191
+ tptJoinsApplied: boolean;
192
+ autoJoinedPaths: string[];
412
193
  }
413
194
  /**
414
195
  * SQL query builder with fluent interface.
@@ -429,1110 +210,743 @@ export interface QBState<Entity extends object> {
429
210
  * const publisher = await qb.getSingleResult();
430
211
  * ```
431
212
  */
432
- export declare class QueryBuilder<
433
- Entity extends object = AnyEntity,
434
- RootAlias extends string = never,
435
- Hint extends string = never,
436
- Context extends object = never,
437
- RawAliases extends string = never,
438
- Fields extends string = '*',
439
- CTEs extends Record<string, object> = {},
440
- > implements Subquery {
441
- #private;
442
- protected readonly metadata: MetadataStorage;
443
- protected readonly driver: AbstractSqlDriver;
444
- protected readonly context?: Transaction | undefined;
445
- protected connectionType?: ConnectionType | undefined;
446
- protected em?: SqlEntityManager | undefined;
447
- protected loggerContext?: (LoggingOptions & Dictionary) | undefined;
448
- readonly __subquery: true;
449
- /** @internal */
450
- static createDefaultState<T extends object>(): QBState<T>;
451
- get mainAlias(): Alias<Entity>;
452
- get alias(): string;
453
- get helper(): QueryBuilderHelper;
454
- get type(): QueryType;
455
- /** @internal */
456
- get state(): QBState<Entity>;
457
- protected readonly platform: AbstractSqlPlatform;
458
- /**
459
- * @internal
460
- */
461
- constructor(
462
- entityName: EntityName<Entity> | QueryBuilder<Entity, any, any, any>,
463
- metadata: MetadataStorage,
464
- driver: AbstractSqlDriver,
465
- context?: Transaction | undefined,
466
- alias?: string,
467
- connectionType?: ConnectionType | undefined,
468
- em?: SqlEntityManager | undefined,
469
- loggerContext?: (LoggingOptions & Dictionary) | undefined,
470
- );
471
- /**
472
- * Creates a SELECT query, specifying the fields to retrieve.
473
- *
474
- * @example
475
- * ```ts
476
- * // Select specific fields
477
- * const qb = em.createQueryBuilder(User, 'u');
478
- * qb.select(['u.id', 'u.name', 'u.email']);
479
- *
480
- * // Select with raw expressions
481
- * qb.select([raw('count(*) as total')]);
482
- *
483
- * // Select with aliases (works for regular and formula properties)
484
- * qb.select(['id', 'fullName as displayName']);
485
- * qb.select(['id', sql.ref('fullName').as('displayName')]);
486
- *
487
- * // Select with distinct
488
- * qb.select('*', true);
489
- * ```
490
- */
491
- select<const F extends readonly Field<Entity, RootAlias, Context>[]>(
492
- fields: F,
493
- distinct?: boolean,
494
- ): SelectQueryBuilder<
495
- Entity,
496
- RootAlias,
497
- Hint,
498
- Context,
499
- RawAliases | ExtractRawAliases<F>,
500
- ExtractRootFields<F[number] & string, RootAlias, Context>,
501
- CTEs
502
- >;
503
- /**
504
- * Creates a SELECT query, specifying the fields to retrieve.
505
- *
506
- * @example
507
- * ```ts
508
- * // Select specific fields
509
- * const qb = em.createQueryBuilder(User, 'u');
510
- * qb.select(['u.id', 'u.name', 'u.email']);
511
- *
512
- * // Select with raw expressions
513
- * qb.select([raw('count(*) as total')]);
514
- *
515
- * // Select with distinct
516
- * qb.select('*', true);
517
- * ```
518
- */
519
- select<const P extends string>(
520
- fields: readonly NestedAutoPath<Entity, RootAlias, Context, P>[],
521
- distinct?: boolean,
522
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>, CTEs>;
523
- /**
524
- * Creates a SELECT query, specifying the fields to retrieve.
525
- *
526
- * @example
527
- * ```ts
528
- * // Select specific fields with nested paths (e.g., for embedded properties)
529
- * const qb = em.createQueryBuilder(User, 'u');
530
- * qb.select('address.city');
531
- * ```
532
- */
533
- select<const P extends string>(
534
- fields: NestedAutoPath<Entity, RootAlias, Context, P>,
535
- distinct?: boolean,
536
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>, CTEs>;
537
- /**
538
- * Creates a SELECT query, specifying the fields to retrieve.
539
- *
540
- * @example
541
- * ```ts
542
- * // Select specific fields
543
- * const qb = em.createQueryBuilder(User, 'u');
544
- * qb.select(['u.id', 'u.name', 'u.email']);
545
- *
546
- * // Select with raw expressions
547
- * qb.select([raw('count(*) as total')]);
548
- *
549
- * // Select with distinct
550
- * qb.select('*', true);
551
- * ```
552
- */
553
- select<const F extends Field<Entity, RootAlias, Context>>(
554
- fields: F,
555
- distinct?: boolean,
556
- ): SelectQueryBuilder<
557
- Entity,
558
- RootAlias,
559
- Hint,
560
- Context,
561
- RawAliases | ExtractRawAliases<readonly [F]>,
562
- ExtractRootFields<F & string, RootAlias, Context>,
563
- CTEs
564
- >;
565
- /**
566
- * Adds fields to an existing SELECT query.
567
- */
568
- addSelect<const F extends Field<Entity, RootAlias, Context> | readonly Field<Entity, RootAlias, Context>[]>(
569
- fields: F,
570
- ): SelectQueryBuilder<
571
- Entity,
572
- RootAlias,
573
- Hint,
574
- Context,
575
- RawAliases | ExtractRawAliases<F extends readonly unknown[] ? F : [F]>,
576
- Fields | ExtractRootFields<F extends readonly (infer U)[] ? U & string : F & string, RootAlias, Context>,
577
- CTEs
578
- >;
579
- distinct(): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
580
- /** postgres only */
581
- distinctOn<const F extends readonly Field<Entity, RootAlias, Context>[]>(
582
- fields: F,
583
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
584
- /** postgres only */
585
- distinctOn<F extends Field<Entity, RootAlias, Context>>(
586
- fields: F,
587
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
588
- /**
589
- * Creates an INSERT query with the given data.
590
- *
591
- * @example
592
- * ```ts
593
- * await em.createQueryBuilder(User)
594
- * .insert({ name: 'John', email: 'john@example.com' })
595
- * .execute();
596
- *
597
- * // Bulk insert
598
- * await em.createQueryBuilder(User)
599
- * .insert([{ name: 'John' }, { name: 'Jane' }])
600
- * .execute();
601
- * ```
602
- */
603
- insert(
604
- data: RequiredEntityData<Entity> | RequiredEntityData<Entity>[],
605
- ): InsertQueryBuilder<Entity, RootAlias, Context>;
606
- /**
607
- * Creates an UPDATE query with the given data.
608
- * Use `where()` to specify which rows to update.
609
- *
610
- * @example
611
- * ```ts
612
- * await em.createQueryBuilder(User)
613
- * .update({ name: 'John Doe' })
614
- * .where({ id: 1 })
615
- * .execute();
616
- * ```
617
- */
618
- update(data: EntityData<Entity>): UpdateQueryBuilder<Entity, RootAlias, Context>;
619
- /**
620
- * Creates a DELETE query.
621
- * Use `where()` to specify which rows to delete.
622
- *
623
- * @example
624
- * ```ts
625
- * await em.createQueryBuilder(User)
626
- * .delete()
627
- * .where({ id: 1 })
628
- * .execute();
629
- *
630
- * // Or pass the condition directly
631
- * await em.createQueryBuilder(User)
632
- * .delete({ isActive: false })
633
- * .execute();
634
- * ```
635
- */
636
- delete(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): DeleteQueryBuilder<Entity, RootAlias, Context>;
637
- /**
638
- * Creates a TRUNCATE query to remove all rows from the table.
639
- */
640
- truncate(): TruncateQueryBuilder<Entity>;
641
- /**
642
- * Creates a COUNT query to count matching rows.
643
- *
644
- * @example
645
- * ```ts
646
- * const count = await em.createQueryBuilder(User)
647
- * .count()
648
- * .where({ isActive: true })
649
- * .execute('get');
650
- * ```
651
- */
652
- count<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): CountQueryBuilder<Entity>;
653
- /**
654
- * Adds a JOIN clause to the query for an entity relation.
655
- *
656
- * @example
657
- * ```ts
658
- * const qb = em.createQueryBuilder(Book, 'b');
659
- * qb.select('*')
660
- * .join('b.author', 'a')
661
- * .where({ 'a.name': 'John' });
662
- * ```
663
- */
664
- join<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(
665
- field: Field,
666
- alias: Alias,
667
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
668
- type?: JoinType,
669
- path?: string,
670
- schema?: string,
671
- ): SelectQueryBuilder<
672
- Entity,
673
- RootAlias,
674
- ModifyHint<RootAlias, Context, Hint, Field> & {},
675
- ModifyContext<Entity, Context, Field, Alias>,
676
- RawAliases,
677
- '*',
678
- CTEs
679
- >;
680
- /**
681
- * Adds a JOIN clause to the query for a subquery.
682
- */
683
- join<Alias extends string>(
684
- field: RawQueryFragment | QueryBuilder<any>,
685
- alias: Alias,
686
- cond?: RawJoinCondition,
687
- type?: JoinType,
688
- path?: string,
689
- schema?: string,
690
- ): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
691
- /**
692
- * Adds an INNER JOIN clause to the query for an entity relation.
693
- */
694
- innerJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(
695
- field: Field,
696
- alias: Alias,
697
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
698
- schema?: string,
699
- ): SelectQueryBuilder<
700
- Entity,
701
- RootAlias,
702
- ModifyHint<RootAlias, Context, Hint, Field> & {},
703
- ModifyContext<Entity, Context, Field, Alias>,
704
- RawAliases,
705
- '*',
706
- CTEs
707
- >;
708
- /**
709
- * Adds an INNER JOIN clause to the query for a subquery.
710
- */
711
- innerJoin<Alias extends string>(
712
- field: RawQueryFragment | QueryBuilder<any>,
713
- alias: Alias,
714
- cond?: RawJoinCondition,
715
- schema?: string,
716
- ): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
717
- innerJoinLateral<Alias extends string>(
718
- field: RawQueryFragment | QueryBuilder<any>,
719
- alias: Alias,
720
- cond?: RawJoinCondition,
721
- schema?: string,
722
- ): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
723
- /**
724
- * Adds a LEFT JOIN clause to the query for an entity relation.
725
- */
726
- leftJoin<Field extends QBField<Entity, RootAlias, Context>, Alias extends string>(
727
- field: Field,
728
- alias: Alias,
729
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
730
- schema?: string,
731
- ): SelectQueryBuilder<
732
- Entity,
733
- RootAlias,
734
- ModifyHint<RootAlias, Context, Hint, Field> & {},
735
- ModifyContext<Entity, Context, Field, Alias>,
736
- RawAliases,
737
- '*',
738
- CTEs
739
- >;
740
- /**
741
- * Adds a LEFT JOIN clause to the query for a subquery.
742
- */
743
- leftJoin<Alias extends string>(
744
- field: RawQueryFragment | QueryBuilder<any>,
745
- alias: Alias,
746
- cond?: RawJoinCondition,
747
- schema?: string,
748
- ): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
749
- leftJoinLateral<Alias extends string>(
750
- field: RawQueryFragment | QueryBuilder<any>,
751
- alias: Alias,
752
- cond?: RawJoinCondition,
753
- schema?: string,
754
- ): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
755
- /**
756
- * Adds a JOIN clause and automatically selects the joined entity's fields.
757
- * This is useful for eager loading related entities.
758
- *
759
- * @example
760
- * ```ts
761
- * const qb = em.createQueryBuilder(Book, 'b');
762
- * qb.select('*')
763
- * .joinAndSelect('b.author', 'a')
764
- * .where({ 'a.name': 'John' });
765
- * ```
766
- */
767
- joinAndSelect<
768
- Field extends QBField<Entity, RootAlias, Context>,
769
- Alias extends string,
770
- const JoinFields extends
771
- | readonly [
772
- JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
773
- ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[],
774
- ]
775
- | undefined = undefined,
776
- >(
777
- field: Field | [Field, RawQueryFragment | QueryBuilder<any>],
778
- alias: Alias,
779
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
780
- type?: JoinType,
781
- path?: string,
782
- fields?: JoinFields,
783
- schema?: string,
784
- ): SelectQueryBuilder<
785
- Entity,
786
- RootAlias,
787
- ModifyHint<RootAlias, Context, Hint, Field, true> & {},
788
- ModifyContext<Entity, Context, Field, Alias, true>,
789
- RawAliases,
790
- ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>,
791
- CTEs
792
- >;
793
- leftJoinAndSelect<
794
- Field extends QBField<Entity, RootAlias, Context>,
795
- Alias extends string,
796
- const JoinFields extends
797
- | readonly [
798
- JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
799
- ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[],
800
- ]
801
- | undefined = undefined,
802
- >(
803
- field: Field | [Field, RawQueryFragment | QueryBuilder<any>],
804
- alias: Alias,
805
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
806
- fields?: JoinFields,
807
- schema?: string,
808
- ): SelectQueryBuilder<
809
- Entity,
810
- RootAlias,
811
- ModifyHint<RootAlias, Context, Hint, Field, true> & {},
812
- ModifyContext<Entity, Context, Field, Alias, true>,
813
- RawAliases,
814
- ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>,
815
- CTEs
816
- >;
817
- leftJoinLateralAndSelect<
818
- Field extends QBField<Entity, RootAlias, Context>,
819
- Alias extends string,
820
- const JoinFields extends
821
- | readonly [
822
- JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
823
- ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[],
824
- ]
825
- | undefined = undefined,
826
- >(
827
- field: [Field, RawQueryFragment | QueryBuilder<any>],
828
- alias: Alias,
829
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
830
- fields?: JoinFields,
831
- schema?: string,
832
- ): SelectQueryBuilder<
833
- Entity,
834
- RootAlias,
835
- ModifyHint<RootAlias, Context, Hint, Field, true> & {},
836
- ModifyContext<Entity, Context, Field, Alias, true>,
837
- RawAliases,
838
- ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>,
839
- CTEs
840
- >;
841
- innerJoinAndSelect<
842
- Field extends QBField<Entity, RootAlias, Context>,
843
- Alias extends string,
844
- const JoinFields extends
845
- | readonly [
846
- JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
847
- ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[],
848
- ]
849
- | undefined = undefined,
850
- >(
851
- field: Field | [Field, RawQueryFragment | QueryBuilder<any>],
852
- alias: Alias,
853
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
854
- fields?: JoinFields,
855
- schema?: string,
856
- ): SelectQueryBuilder<
857
- Entity,
858
- RootAlias,
859
- ModifyHint<RootAlias, Context, Hint, Field, true> & {},
860
- ModifyContext<Entity, Context, Field, Alias, true>,
861
- RawAliases,
862
- ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>,
863
- CTEs
864
- >;
865
- innerJoinLateralAndSelect<
866
- Field extends QBField<Entity, RootAlias, Context>,
867
- Alias extends string,
868
- const JoinFields extends
869
- | readonly [
870
- JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
871
- ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[],
872
- ]
873
- | undefined = undefined,
874
- >(
875
- field: [Field, RawQueryFragment | QueryBuilder<any>],
876
- alias: Alias,
877
- cond?: JoinCondition<JoinedEntityType<Entity, Context, Field & string>, Alias>,
878
- fields?: JoinFields,
879
- schema?: string,
880
- ): SelectQueryBuilder<
881
- Entity,
882
- RootAlias,
883
- ModifyHint<RootAlias, Context, Hint, Field, true> & {},
884
- ModifyContext<Entity, Context, Field, Alias, true>,
885
- RawAliases,
886
- ModifyFields<Fields, RootAlias, Context, Field, Alias, JoinFields>,
887
- CTEs
888
- >;
889
- protected getFieldsForJoinedLoad(
890
- prop: EntityProperty<Entity>,
891
- alias: string,
892
- explicitFields?: readonly string[],
893
- ): InternalField<Entity>[];
894
- /**
895
- * Apply filters to the QB where condition.
896
- */
897
- applyFilters(filterOptions?: FilterOptions): Promise<void>;
898
- /**
899
- * @internal
900
- */
901
- scheduleFilterCheck(path: string): void;
902
- /**
903
- * @internal
904
- */
905
- applyJoinedFilters(em: EntityManager, filterOptions: FilterOptions | undefined): Promise<void>;
906
- withSubQuery(subQuery: RawQueryFragment | NativeQueryBuilder, alias: string): this;
907
- /**
908
- * Adds a WHERE clause to the query using an object condition.
909
- *
910
- * Supports filtering by:
911
- * - Direct entity properties: `{ name: 'John' }`
912
- * - Nested relations/embedded: `{ author: { name: 'John' } }`
913
- * - Aliased properties after joins: `{ 'a.name': 'John' }` or `{ 'b.title': 'test' }`
914
- * - Filter operators: `{ age: { $gte: 18 } }`
915
- * - Logical operators: `{ $or: [{ name: 'John' }, { name: 'Jane' }] }`
916
- *
917
- * @example
918
- * ```ts
919
- * // Filter by entity properties
920
- * qb.where({ name: 'John', age: { $gte: 18 } });
921
- *
922
- * // Filter by nested relation
923
- * qb.where({ author: { name: 'John' } });
924
- *
925
- * // Filter by aliased properties after join
926
- * qb.leftJoin('a.books', 'b').where({ 'b.title': 'test' });
927
- *
928
- * // Combine with logical operators
929
- * qb.where({ $or: [{ status: 'active' }, { role: 'admin' }] });
930
- * ```
931
- */
932
- where(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>, operator?: keyof typeof GroupOperator): this;
933
- /**
934
- * Adds a WHERE clause to the query using a raw SQL string or fragment.
935
- *
936
- * @example
937
- * ```ts
938
- * // Raw SQL with parameters
939
- * qb.where('name = ? AND age >= ?', ['John', 18]);
940
- *
941
- * // Using raw() helper
942
- * qb.where(raw('lower(name) = ?', ['john']));
943
- * ```
944
- */
945
- where(cond: string | RawQueryFragment, params?: any[], operator?: keyof typeof GroupOperator): this;
946
- /**
947
- * Adds an AND WHERE clause to the query using an object condition.
948
- *
949
- * @example
950
- * ```ts
951
- * qb.where({ status: 'active' }).andWhere({ role: 'admin' });
952
- * qb.where({ name: 'John' }).andWhere({ 'b.title': 'test' });
953
- * ```
954
- */
955
- andWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
956
- /**
957
- * Adds an AND WHERE clause to the query using a raw SQL string or fragment.
958
- *
959
- * @example
960
- * ```ts
961
- * qb.where({ status: 'active' }).andWhere('age >= ?', [18]);
962
- * ```
963
- */
964
- andWhere(cond: string | RawQueryFragment, params?: any[]): this;
965
- /**
966
- * Adds an OR WHERE clause to the query using an object condition.
967
- *
968
- * @example
969
- * ```ts
970
- * qb.where({ status: 'active' }).orWhere({ role: 'admin' });
971
- * qb.where({ name: 'John' }).orWhere({ name: 'Jane' });
972
- * ```
973
- */
974
- orWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
975
- /**
976
- * Adds an OR WHERE clause to the query using a raw SQL string or fragment.
977
- *
978
- * @example
979
- * ```ts
980
- * qb.where({ status: 'active' }).orWhere('role = ?', ['admin']);
981
- * ```
982
- */
983
- orWhere(cond: string | RawQueryFragment, params?: any[]): this;
984
- /**
985
- * Adds an ORDER BY clause to the query, replacing any existing order.
986
- *
987
- * @example
988
- * ```ts
989
- * qb.orderBy({ name: 'asc', createdAt: 'desc' });
990
- * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
991
- * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
992
- * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
993
- * ```
994
- */
995
- orderBy(
996
- orderBy:
997
- | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>
998
- | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[],
999
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1000
- /**
1001
- * Adds an ORDER BY clause to the query, replacing any existing order.
1002
- *
1003
- * @example
1004
- * ```ts
1005
- * qb.orderBy({ name: 'asc', createdAt: 'desc' });
1006
- * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
1007
- * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
1008
- * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
1009
- * ```
1010
- */
1011
- orderBy<const T extends Record<string, QueryOrderKeysFlat>>(
1012
- orderBy: T & {
1013
- [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string>
1014
- ? T[K]
1015
- : K extends RawAliases
1016
- ? T[K]
1017
- : never;
1018
- },
1019
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1020
- /**
1021
- * Adds additional ORDER BY clause without replacing existing order.
1022
- */
1023
- andOrderBy(
1024
- orderBy:
1025
- | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>
1026
- | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[],
1027
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1028
- /**
1029
- * Adds additional ORDER BY clause without replacing existing order.
1030
- */
1031
- andOrderBy<const T extends Record<string, QueryOrderKeysFlat>>(
1032
- orderBy: T & {
1033
- [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string>
1034
- ? T[K]
1035
- : K extends RawAliases
1036
- ? T[K]
1037
- : never;
1038
- },
1039
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1040
- private processOrderBy;
1041
- /** Collect custom aliases from select fields (stored as 'resolved as alias' strings by select()). */
1042
- private getSelectAliases;
1043
- /**
1044
- * Adds a GROUP BY clause to the query.
1045
- *
1046
- * @example
1047
- * ```ts
1048
- * qb.select([raw('count(*) as count'), 'status'])
1049
- * .groupBy('status');
1050
- * ```
1051
- */
1052
- groupBy<const F extends readonly Field<Entity, RootAlias, Context>[]>(
1053
- fields: F,
1054
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1055
- /**
1056
- * Adds a GROUP BY clause to the query.
1057
- *
1058
- * @example
1059
- * ```ts
1060
- * qb.select([raw('count(*) as count'), 'status'])
1061
- * .groupBy('status');
1062
- * ```
1063
- */
1064
- groupBy<F extends Field<Entity, RootAlias, Context>>(
1065
- fields: F,
1066
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1067
- /**
1068
- * Adds a GROUP BY clause to the query.
1069
- *
1070
- * @example
1071
- * ```ts
1072
- * qb.select([raw('count(*) as count'), 'status'])
1073
- * .groupBy('status');
1074
- * ```
1075
- */
1076
- groupBy<const P extends string>(
1077
- fields: NestedAutoPath<Entity, RootAlias, Context, P> | readonly NestedAutoPath<Entity, RootAlias, Context, P>[],
1078
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1079
- /**
1080
- * Adds a HAVING clause to the query, typically used with GROUP BY.
1081
- *
1082
- * @example
1083
- * ```ts
1084
- * qb.select([raw('count(*) as count'), 'status'])
1085
- * .groupBy('status')
1086
- * .having({ count: { $gt: 5 } });
1087
- * ```
1088
- */
1089
- having(
1090
- cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string,
1091
- params?: any[],
1092
- operator?: keyof typeof GroupOperator,
1093
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1094
- andHaving(
1095
- cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string,
1096
- params?: any[],
1097
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1098
- orHaving(
1099
- cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string,
1100
- params?: any[],
1101
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1102
- onConflict<F extends Field<Entity, RootAlias, Context>>(
1103
- fields?: F | F[] | RawQueryFragment,
1104
- ): InsertQueryBuilder<Entity, RootAlias, Context>;
1105
- ignore(): this;
1106
- merge<const P extends string>(data: readonly NestedAutoPath<Entity, RootAlias, Context, P>[]): this;
1107
- merge<F extends Field<Entity, RootAlias, Context>>(data?: EntityData<Entity> | F[]): this;
1108
- returning<F extends Field<Entity, RootAlias, Context>>(fields?: F | F[]): this;
1109
- /**
1110
- * @internal
1111
- */
1112
- populate(
1113
- populate: PopulateOptions<Entity>[],
1114
- populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`,
1115
- populateFilter?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`,
1116
- ): this;
1117
- /**
1118
- * Sets a LIMIT clause to restrict the number of results.
1119
- *
1120
- * @example
1121
- * ```ts
1122
- * qb.select('*').limit(10); // First 10 results
1123
- * qb.select('*').limit(10, 20); // 10 results starting from offset 20
1124
- * ```
1125
- */
1126
- limit(
1127
- limit?: number,
1128
- offset?: number,
1129
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1130
- /**
1131
- * Sets an OFFSET clause to skip a number of results.
1132
- *
1133
- * @example
1134
- * ```ts
1135
- * qb.select('*').limit(10).offset(20); // Results 21-30
1136
- * ```
1137
- */
1138
- offset(offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1139
- withSchema(schema?: string): this;
1140
- setLockMode(mode?: LockMode, tables?: string[]): this;
1141
- setFlushMode(flushMode?: FlushMode): this;
1142
- setFlag(flag: QueryFlag): this;
1143
- unsetFlag(flag: QueryFlag): this;
1144
- hasFlag(flag: QueryFlag): boolean;
1145
- cache(config?: boolean | number | [string, number]): this;
1146
- /**
1147
- * Adds index hint to the FROM clause.
1148
- */
1149
- indexHint(sql: string | undefined): this;
1150
- /**
1151
- * Adds COLLATE clause to ORDER BY expressions.
1152
- */
1153
- collation(collation: string | undefined): this;
1154
- /**
1155
- * Prepend comment to the sql query using the syntax `/* ... *&#8205;/`. Some characters are forbidden such as `/*, *&#8205;/` and `?`.
1156
- */
1157
- comment(comment: string | string[] | undefined): this;
1158
- /**
1159
- * Add hints to the query using comment-like syntax `/*+ ... *&#8205;/`. MySQL and Oracle use this syntax for optimizer hints.
1160
- * Also various DB proxies and routers use this syntax to pass hints to alter their behavior. In other dialects the hints
1161
- * are ignored as simple comments.
1162
- */
1163
- hintComment(comment: string | string[] | undefined): this;
1164
- /**
1165
- * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
1166
- * Allows setting a main string alias of the selection data.
1167
- */
1168
- from<Entity extends object>(
1169
- target: QueryBuilder<Entity>,
1170
- aliasName?: string,
1171
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1172
- /**
1173
- * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
1174
- * Allows setting a main string alias of the selection data.
1175
- */
1176
- from<Entity extends object>(
1177
- target: EntityName<Entity>,
1178
- ): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1179
- /**
1180
- * Specifies a CTE name as the FROM source, with full type safety.
1181
- * The entity type is inferred from the CTE definition passed to `.with()`.
1182
- */
1183
- from<Name extends string & keyof CTEs, Alias extends string = Name>(
1184
- target: Name,
1185
- aliasName?: Alias,
1186
- ): SelectQueryBuilder<CTEs[Name], Alias, never, never, never, '*', CTEs>;
1187
- getNativeQuery(processVirtualEntity?: boolean): NativeQueryBuilder;
1188
- protected processReturningStatement(
1189
- qb: NativeQueryBuilder,
1190
- meta?: EntityMetadata,
1191
- data?: Dictionary,
1192
- returning?: Field<any>[],
1193
- ): void;
1194
- /**
1195
- * Returns the query with parameters as wildcards.
1196
- */
1197
- getQuery(): string;
1198
- /**
1199
- * Returns raw fragment representation of this QueryBuilder.
1200
- */
1201
- toRaw(): RawQueryFragment;
1202
- toQuery(): {
1203
- sql: string;
1204
- params: readonly unknown[];
1205
- };
1206
- /**
1207
- * Returns the list of all parameters for this query.
1208
- */
1209
- getParams(): readonly unknown[];
1210
- /**
1211
- * Returns raw interpolated query string with all the parameters inlined.
1212
- */
1213
- getFormattedQuery(): string;
1214
- /**
1215
- * @internal
1216
- */
1217
- getAliasForJoinPath(path?: string | JoinOptions, options?: ICriteriaNodeProcessOptions): string | undefined;
1218
- /**
1219
- * @internal
1220
- */
1221
- getJoinForPath(path: string, options?: ICriteriaNodeProcessOptions): JoinOptions | undefined;
1222
- /**
1223
- * @internal
1224
- */
1225
- getNextAlias(entityName?: string | EntityName): string;
1226
- /**
1227
- * Registers a join for a specific polymorphic target type.
1228
- * Used by the driver to create per-target LEFT JOINs for JOINED loading.
1229
- * @internal
1230
- */
1231
- addPolymorphicJoin(
1232
- prop: EntityProperty,
1233
- targetMeta: EntityMetadata,
1234
- ownerAlias: string,
1235
- alias: string,
1236
- type: JoinType,
1237
- path: string,
1238
- schema?: string,
1239
- ): void;
1240
- /**
1241
- * @internal
1242
- */
1243
- getAliasMap(): Dictionary<EntityName>;
1244
- /**
1245
- * Executes this QB and returns the raw results, mapped to the property names (unless disabled via last parameter).
1246
- * Use `method` to specify what kind of result you want to get (array/single/meta).
1247
- */
1248
- execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
1249
- private getConnection;
1250
- /**
1251
- * Executes the query and returns an async iterable (async generator) that yields results one by one.
1252
- * By default, the results are merged and mapped to entity instances, without adding them to the identity map.
1253
- * You can disable merging and mapping by passing the options `{ mergeResults: false, mapResults: false }`.
1254
- * This is useful for processing large datasets without loading everything into memory at once.
1255
- *
1256
- * ```ts
1257
- * const qb = em.createQueryBuilder(Book, 'b');
1258
- * qb.select('*').where({ title: '1984' }).leftJoinAndSelect('b.author', 'a');
1259
- *
1260
- * for await (const book of qb.stream()) {
1261
- * // book is an instance of Book entity
1262
- * console.log(book.title, book.author.name);
1263
- * }
1264
- * ```
1265
- */
1266
- stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
1267
- /**
1268
- * Alias for `qb.getResultList()`
1269
- */
1270
- getResult(): Promise<Loaded<Entity, Hint, Fields>[]>;
1271
- /**
1272
- * Executes the query, returning array of results mapped to entity instances.
1273
- */
1274
- getResultList(limit?: number): Promise<Loaded<Entity, Hint, Fields>[]>;
1275
- private propagatePopulateHint;
1276
- private mapResult;
1277
- private mapResults;
1278
- /**
1279
- * Executes the query, returning the first result or null
1280
- */
1281
- getSingleResult(): Promise<Loaded<Entity, Hint, Fields> | null>;
1282
- /**
1283
- * Executes count query (without offset and limit), returning total count of results
1284
- */
1285
- getCount<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): Promise<number>;
1286
- /**
1287
- * Executes the query, returning both array of results and total count query (without offset and limit).
1288
- */
1289
- getResultAndCount(): Promise<[Loaded<Entity, Hint, Fields>[], number]>;
1290
- /**
1291
- * Returns native query builder instance with sub-query aliased with given alias.
1292
- */
1293
- as(alias: string): NativeQueryBuilder;
1294
- /**
1295
- * Returns native query builder instance with sub-query aliased with given alias.
1296
- * 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.
1297
- */
1298
- as<T>(targetEntity: EntityName<T>, alias: EntityKey<T>): NativeQueryBuilder;
1299
- /**
1300
- * Combines the current query with one or more other queries using `UNION ALL`.
1301
- * All queries must select the same columns. Returns a `QueryBuilder` that
1302
- * can be used with `$in`, passed to `qb.from()`, or converted via `.getQuery()`,
1303
- * `.getParams()`, `.toQuery()`, `.toRaw()`, etc.
1304
- *
1305
- * ```ts
1306
- * const qb1 = em.createQueryBuilder(Employee).select('id').where(condition1);
1307
- * const qb2 = em.createQueryBuilder(Employee).select('id').where(condition2);
1308
- * const qb3 = em.createQueryBuilder(Employee).select('id').where(condition3);
1309
- * const subquery = qb1.unionAll(qb2, qb3);
1310
- *
1311
- * const results = await em.find(Employee, { id: { $in: subquery } });
1312
- * ```
1313
- */
1314
- unionAll(...others: (QueryBuilder<any> | NativeQueryBuilder)[]): QueryBuilder<Entity>;
1315
- /**
1316
- * Combines the current query with one or more other queries using `UNION` (with deduplication).
1317
- * All queries must select the same columns. Returns a `QueryBuilder` that
1318
- * can be used with `$in`, passed to `qb.from()`, or converted via `.getQuery()`,
1319
- * `.getParams()`, `.toQuery()`, `.toRaw()`, etc.
1320
- *
1321
- * ```ts
1322
- * const qb1 = em.createQueryBuilder(Employee).select('id').where(condition1);
1323
- * const qb2 = em.createQueryBuilder(Employee).select('id').where(condition2);
1324
- * const subquery = qb1.union(qb2);
1325
- *
1326
- * const results = await em.find(Employee, { id: { $in: subquery } });
1327
- * ```
1328
- */
1329
- union(...others: (QueryBuilder<any> | NativeQueryBuilder)[]): QueryBuilder<Entity>;
1330
- private buildUnionQuery;
1331
- /**
1332
- * Adds a Common Table Expression (CTE) to the query.
1333
- * When a `QueryBuilder` is passed, its entity type is tracked for type-safe `from()`.
1334
- *
1335
- * @example
1336
- * ```ts
1337
- * const recentBooks = em.createQueryBuilder(Book, 'b').select('*').where({ ... });
1338
- * const qb = em.createQueryBuilder(Author, 'a')
1339
- * .with('recent_books', recentBooks)
1340
- * .select('*')
1341
- * .from('recent_books', 'rb'); // entity type inferred as Book
1342
- * ```
1343
- */
1344
- with<Name extends string, Q extends QueryBuilder<any>>(
1345
- name: Name,
1346
- query: Q,
1347
- options?: CteOptions,
1348
- ): QueryBuilder<
1349
- Entity,
1350
- RootAlias,
1351
- Hint,
1352
- Context,
1353
- RawAliases,
1354
- Fields,
1355
- CTEs & Record<Name, Q extends QueryBuilder<infer T> ? T : object>
1356
- >;
1357
- /**
1358
- * Adds a Common Table Expression (CTE) to the query using a `NativeQueryBuilder` or raw SQL fragment.
1359
- * The CTE name is tracked but without entity type inference — use `from()` to query from it.
1360
- */
1361
- with<Name extends string>(
1362
- name: Name,
1363
- query: NativeQueryBuilder | RawQueryFragment,
1364
- options?: CteOptions,
1365
- ): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, object>>;
1366
- /**
1367
- * Adds a recursive Common Table Expression (CTE) to the query.
1368
- * When a `QueryBuilder` is passed, its entity type is tracked for type-safe `from()`.
1369
- *
1370
- * @example
1371
- * ```ts
1372
- * const base = em.createQueryBuilder(Category).select('*').where({ parent: null });
1373
- * const rec = em.createQueryBuilder(Category, 'c').select('c.*')
1374
- * .leftJoin('c.parent', 'ct', { id: sql.ref('c.parentId') });
1375
- * const qb = em.createQueryBuilder(Category)
1376
- * .withRecursive('category_tree', base.unionAll(rec))
1377
- * .select('*')
1378
- * .from('category_tree', 'ct'); // entity type inferred as Category
1379
- * ```
1380
- */
1381
- withRecursive<Name extends string, Q extends QueryBuilder<any>>(
1382
- name: Name,
1383
- query: Q,
1384
- options?: CteOptions,
1385
- ): QueryBuilder<
1386
- Entity,
1387
- RootAlias,
1388
- Hint,
1389
- Context,
1390
- RawAliases,
1391
- Fields,
1392
- CTEs & Record<Name, Q extends QueryBuilder<infer T> ? T : object>
1393
- >;
1394
- /**
1395
- * Adds a recursive Common Table Expression (CTE) to the query using a `NativeQueryBuilder` or raw SQL fragment.
1396
- * The CTE name is tracked but without entity type inference — use `from()` to query from it.
1397
- */
1398
- withRecursive<Name extends string>(
1399
- name: Name,
1400
- query: NativeQueryBuilder | RawQueryFragment,
1401
- options?: CteOptions,
1402
- ): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, object>>;
1403
- private addCte;
1404
- clone(
1405
- reset?: boolean | (keyof QBState<Entity>)[],
1406
- preserve?: (keyof QBState<Entity>)[],
1407
- ): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
1408
- /**
1409
- * Sets logger context for this query builder.
1410
- */
1411
- setLoggerContext(context: LoggingOptions & Dictionary): void;
1412
- /**
1413
- * Gets logger context for this query builder.
1414
- */
1415
- getLoggerContext<T extends Dictionary & LoggingOptions = Dictionary>(): T;
1416
- private fromVirtual;
1417
- /**
1418
- * Adds a join from a property object. Used internally for TPT joins where the property
1419
- * is synthetic (not in entity.properties) but defined on metadata (e.g., tptParentProp).
1420
- * The caller must create the alias first via createAlias().
1421
- * @internal
1422
- */
1423
- addPropertyJoin(
1424
- prop: EntityProperty,
1425
- ownerAlias: string,
1426
- alias: string,
1427
- type: JoinType,
1428
- path: string,
1429
- schema?: string,
1430
- ): string;
1431
- private joinReference;
1432
- protected prepareFields<T>(
1433
- fields: InternalField<T>[],
1434
- type?: 'where' | 'groupBy' | 'sub-query',
1435
- schema?: string,
1436
- ): (string | RawQueryFragment)[];
1437
- /**
1438
- * Resolves nested paths like `a.books.title` to their actual field references.
1439
- * Auto-joins relations as needed and returns `{alias}.{field}`.
1440
- * For embeddeds: navigates into flattened embeddeds to return the correct field name.
1441
- */
1442
- protected resolveNestedPath(field: string): string | string[];
1443
- protected init(type: QueryType, data?: any, cond?: any): this;
1444
- private getQueryBase;
1445
- private applyDiscriminatorCondition;
1446
- /**
1447
- * Ensures TPT joins are applied. Can be called early before finalize() to populate
1448
- * the _tptAlias map for use in join resolution. Safe to call multiple times.
1449
- * @internal
1450
- */
1451
- ensureTPTJoins(): void;
1452
- /**
1453
- * For TPT (Table-Per-Type) inheritance: INNER JOINs parent tables.
1454
- * When querying a child entity, we need to join all parent tables.
1455
- * Field selection is handled separately in addTPTParentFields().
1456
- */
1457
- private applyTPTJoins;
1458
- /**
1459
- * For TPT inheritance: adds field selections from parent tables.
1460
- */
1461
- private addTPTParentFields;
1462
- /**
1463
- * For TPT polymorphic queries: LEFT JOINs all child tables when querying a TPT base class.
1464
- * Adds discriminator and child fields to determine and load the concrete type.
1465
- */
1466
- private applyTPTPolymorphicJoins;
1467
- private finalize;
1468
- /** @internal */
1469
- processPopulateHint(): void;
1470
- private processPopulateWhere;
1471
- private mergeOnConditions;
1472
- /**
1473
- * When adding an inner join on a left joined relation, we need to nest them,
1474
- * otherwise the inner join could discard rows of the root table.
1475
- */
1476
- private processNestedJoins;
1477
- private hasToManyJoins;
1478
- protected wrapPaginateSubQuery(meta: EntityMetadata): void;
1479
- /**
1480
- * Computes the set of populate paths from the _populate hints.
1481
- */
1482
- protected getPopulatePaths(): Set<string>;
1483
- protected normalizeJoinPath(join: JoinOptions, meta: EntityMetadata): string;
1484
- /**
1485
- * Transfers WHERE conditions to ORDER BY joins that are not used for population.
1486
- * This ensures the outer query's ORDER BY uses the same filtered rows as the subquery.
1487
- * GH #6160
1488
- */
1489
- protected transferConditionsForOrderByJoins(
1490
- meta: EntityMetadata,
1491
- cond: Dictionary | undefined,
1492
- populatePaths: Set<string>,
1493
- ): void;
1494
- /**
1495
- * Removes joins that are not used for population or ordering to improve performance.
1496
- */
1497
- protected pruneJoinsForPagination(): void;
1498
- /**
1499
- * Transfers WHERE conditions that reference a join alias to the join's ON clause.
1500
- * This is needed when a join is kept for ORDER BY after pagination wrapping,
1501
- * so the outer query orders by the same filtered rows as the subquery.
1502
- * @internal
1503
- */
1504
- protected transferConditionsToJoin(cond: Dictionary, join: JoinOptions, path?: string): void;
1505
- private wrapModifySubQuery;
1506
- private getSchema;
1507
- /** @internal */
1508
- createAlias<U = unknown>(
1509
- entityName: EntityName<U>,
1510
- aliasName: string,
1511
- subQuery?: NativeQueryBuilder | RawQueryFragment,
1512
- ): Alias<U>;
1513
- private createMainAlias;
1514
- private fromSubQuery;
1515
- private fromEntityName;
1516
- private fromRawTable;
1517
- private createQueryBuilderHelper;
1518
- private ensureFromClause;
1519
- private ensureNotFinalized;
213
+ 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 = '*', CTEs extends Record<string, object> = {}> implements Subquery {
214
+ #private;
215
+ protected readonly metadata: MetadataStorage;
216
+ protected readonly driver: AbstractSqlDriver;
217
+ protected readonly context?: Transaction | undefined;
218
+ protected connectionType?: ConnectionType | undefined;
219
+ protected em?: SqlEntityManager | undefined;
220
+ protected loggerContext?: (LoggingOptions & Dictionary) | undefined;
221
+ readonly __subquery: true;
222
+ /** @internal */
223
+ static createDefaultState<T extends object>(): QBState<T>;
224
+ get mainAlias(): Alias<Entity>;
225
+ get alias(): string;
226
+ get helper(): QueryBuilderHelper;
227
+ get type(): QueryType;
228
+ /** @internal */
229
+ get state(): QBState<Entity>;
230
+ protected readonly platform: AbstractSqlPlatform;
231
+ /**
232
+ * @internal
233
+ */
234
+ 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);
235
+ /**
236
+ * Creates a SELECT query, specifying the fields to retrieve.
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * // Select specific fields
241
+ * const qb = em.createQueryBuilder(User, 'u');
242
+ * qb.select(['u.id', 'u.name', 'u.email']);
243
+ *
244
+ * // Select with raw expressions
245
+ * qb.select([raw('count(*) as total')]);
246
+ *
247
+ * // Select with aliases (works for regular and formula properties)
248
+ * qb.select(['id', 'fullName as displayName']);
249
+ * qb.select(['id', sql.ref('fullName').as('displayName')]);
250
+ *
251
+ * // Select with distinct
252
+ * qb.select('*', true);
253
+ * ```
254
+ */
255
+ 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>, CTEs>;
256
+ /**
257
+ * Creates a SELECT query, specifying the fields to retrieve.
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * // Select specific fields
262
+ * const qb = em.createQueryBuilder(User, 'u');
263
+ * qb.select(['u.id', 'u.name', 'u.email']);
264
+ *
265
+ * // Select with raw expressions
266
+ * qb.select([raw('count(*) as total')]);
267
+ *
268
+ * // Select with distinct
269
+ * qb.select('*', true);
270
+ * ```
271
+ */
272
+ select<const P extends string>(fields: readonly NestedAutoPath<Entity, RootAlias, Context, P>[], distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>, CTEs>;
273
+ /**
274
+ * Creates a SELECT query, specifying the fields to retrieve.
275
+ *
276
+ * @example
277
+ * ```ts
278
+ * // Select specific fields with nested paths (e.g., for embedded properties)
279
+ * const qb = em.createQueryBuilder(User, 'u');
280
+ * qb.select('address.city');
281
+ * ```
282
+ */
283
+ select<const P extends string>(fields: NestedAutoPath<Entity, RootAlias, Context, P>, distinct?: boolean): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, ExtractRootFields<P, RootAlias, Context>, CTEs>;
284
+ /**
285
+ * Creates a SELECT query, specifying the fields to retrieve.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * // Select specific fields
290
+ * const qb = em.createQueryBuilder(User, 'u');
291
+ * qb.select(['u.id', 'u.name', 'u.email']);
292
+ *
293
+ * // Select with raw expressions
294
+ * qb.select([raw('count(*) as total')]);
295
+ *
296
+ * // Select with distinct
297
+ * qb.select('*', true);
298
+ * ```
299
+ */
300
+ 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>, CTEs>;
301
+ /**
302
+ * Adds fields to an existing SELECT query.
303
+ */
304
+ 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>, CTEs>;
305
+ distinct(): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
306
+ /** postgres only */
307
+ distinctOn<const F extends readonly Field<Entity, RootAlias, Context>[]>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
308
+ /** postgres only */
309
+ distinctOn<F extends Field<Entity, RootAlias, Context>>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
310
+ /**
311
+ * Creates an INSERT query with the given data.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * await em.createQueryBuilder(User)
316
+ * .insert({ name: 'John', email: 'john@example.com' })
317
+ * .execute();
318
+ *
319
+ * // Bulk insert
320
+ * await em.createQueryBuilder(User)
321
+ * .insert([{ name: 'John' }, { name: 'Jane' }])
322
+ * .execute();
323
+ * ```
324
+ */
325
+ insert(data: RequiredEntityData<Entity> | RequiredEntityData<Entity>[]): InsertQueryBuilder<Entity, RootAlias, Context>;
326
+ /**
327
+ * Creates an UPDATE query with the given data.
328
+ * Use `where()` to specify which rows to update.
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * await em.createQueryBuilder(User)
333
+ * .update({ name: 'John Doe' })
334
+ * .where({ id: 1 })
335
+ * .execute();
336
+ * ```
337
+ */
338
+ update(data: EntityData<Entity>): UpdateQueryBuilder<Entity, RootAlias, Context>;
339
+ /**
340
+ * Creates a DELETE query.
341
+ * Use `where()` to specify which rows to delete.
342
+ *
343
+ * @example
344
+ * ```ts
345
+ * await em.createQueryBuilder(User)
346
+ * .delete()
347
+ * .where({ id: 1 })
348
+ * .execute();
349
+ *
350
+ * // Or pass the condition directly
351
+ * await em.createQueryBuilder(User)
352
+ * .delete({ isActive: false })
353
+ * .execute();
354
+ * ```
355
+ */
356
+ delete(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): DeleteQueryBuilder<Entity, RootAlias, Context>;
357
+ /**
358
+ * Creates a TRUNCATE query to remove all rows from the table.
359
+ */
360
+ truncate(): TruncateQueryBuilder<Entity>;
361
+ /**
362
+ * Creates a COUNT query to count matching rows.
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * const count = await em.createQueryBuilder(User)
367
+ * .count()
368
+ * .where({ isActive: true })
369
+ * .execute('get');
370
+ * ```
371
+ */
372
+ count<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): CountQueryBuilder<Entity>;
373
+ /**
374
+ * Adds a JOIN clause to the query for an entity relation.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * const qb = em.createQueryBuilder(Book, 'b');
379
+ * qb.select('*')
380
+ * .join('b.author', 'a')
381
+ * .where({ 'a.name': 'John' });
382
+ * ```
383
+ */
384
+ 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, '*', CTEs>;
385
+ /**
386
+ * Adds a JOIN clause to the query for a subquery.
387
+ */
388
+ 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, '*', CTEs>;
389
+ /**
390
+ * Adds an INNER JOIN clause to the query for an entity relation.
391
+ */
392
+ 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, '*', CTEs>;
393
+ /**
394
+ * Adds an INNER JOIN clause to the query for a subquery.
395
+ */
396
+ innerJoin<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
397
+ innerJoinLateral<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
398
+ /**
399
+ * Adds a LEFT JOIN clause to the query for an entity relation.
400
+ */
401
+ 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, '*', CTEs>;
402
+ /**
403
+ * Adds a LEFT JOIN clause to the query for a subquery.
404
+ */
405
+ leftJoin<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
406
+ leftJoinLateral<Alias extends string>(field: RawQueryFragment | QueryBuilder<any>, alias: Alias, cond?: RawJoinCondition, schema?: string): SelectQueryBuilder<Entity, RootAlias, Hint, ModifyContext<Entity, Context, string, Alias>, RawAliases, '*', CTEs>;
407
+ /**
408
+ * Adds a JOIN clause and automatically selects the joined entity's fields.
409
+ * This is useful for eager loading related entities.
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * const qb = em.createQueryBuilder(Book, 'b');
414
+ * qb.select('*')
415
+ * .joinAndSelect('b.author', 'a')
416
+ * .where({ 'a.name': 'John' });
417
+ * ```
418
+ */
419
+ joinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [
420
+ JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
421
+ ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]
422
+ ] | 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>, CTEs>;
423
+ leftJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [
424
+ JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
425
+ ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]
426
+ ] | 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>, CTEs>;
427
+ leftJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [
428
+ JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
429
+ ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]
430
+ ] | 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>, CTEs>;
431
+ innerJoinAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [
432
+ JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
433
+ ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]
434
+ ] | 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>, CTEs>;
435
+ innerJoinLateralAndSelect<Field extends QBField<Entity, RootAlias, Context>, Alias extends string, const JoinFields extends readonly [
436
+ JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>,
437
+ ...JoinSelectField<JoinedEntityType<Entity, Context, Field & string>, Alias>[]
438
+ ] | 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>, CTEs>;
439
+ protected getFieldsForJoinedLoad(prop: EntityProperty<Entity>, alias: string, explicitFields?: readonly string[]): InternalField<Entity>[];
440
+ /**
441
+ * Apply filters to the QB where condition.
442
+ */
443
+ applyFilters(filterOptions?: FilterOptions): Promise<void>;
444
+ /**
445
+ * @internal
446
+ */
447
+ scheduleFilterCheck(path: string): void;
448
+ /**
449
+ * @internal
450
+ */
451
+ applyJoinedFilters(em: EntityManager, filterOptions: FilterOptions | undefined): Promise<void>;
452
+ withSubQuery(subQuery: RawQueryFragment | NativeQueryBuilder, alias: string): this;
453
+ /**
454
+ * Adds a WHERE clause to the query using an object condition.
455
+ *
456
+ * Supports filtering by:
457
+ * - Direct entity properties: `{ name: 'John' }`
458
+ * - Nested relations/embedded: `{ author: { name: 'John' } }`
459
+ * - Aliased properties after joins: `{ 'a.name': 'John' }` or `{ 'b.title': 'test' }`
460
+ * - Filter operators: `{ age: { $gte: 18 } }`
461
+ * - Logical operators: `{ $or: [{ name: 'John' }, { name: 'Jane' }] }`
462
+ *
463
+ * @example
464
+ * ```ts
465
+ * // Filter by entity properties
466
+ * qb.where({ name: 'John', age: { $gte: 18 } });
467
+ *
468
+ * // Filter by nested relation
469
+ * qb.where({ author: { name: 'John' } });
470
+ *
471
+ * // Filter by aliased properties after join
472
+ * qb.leftJoin('a.books', 'b').where({ 'b.title': 'test' });
473
+ *
474
+ * // Combine with logical operators
475
+ * qb.where({ $or: [{ status: 'active' }, { role: 'admin' }] });
476
+ * ```
477
+ */
478
+ where(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>, operator?: keyof typeof GroupOperator): this;
479
+ /**
480
+ * Adds a WHERE clause to the query using a raw SQL string or fragment.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * // Raw SQL with parameters
485
+ * qb.where('name = ? AND age >= ?', ['John', 18]);
486
+ *
487
+ * // Using raw() helper
488
+ * qb.where(raw('lower(name) = ?', ['john']));
489
+ * ```
490
+ */
491
+ where(cond: string | RawQueryFragment, params?: any[], operator?: keyof typeof GroupOperator): this;
492
+ /**
493
+ * Adds an AND WHERE clause to the query using an object condition.
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * qb.where({ status: 'active' }).andWhere({ role: 'admin' });
498
+ * qb.where({ name: 'John' }).andWhere({ 'b.title': 'test' });
499
+ * ```
500
+ */
501
+ andWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
502
+ /**
503
+ * Adds an AND WHERE clause to the query using a raw SQL string or fragment.
504
+ *
505
+ * @example
506
+ * ```ts
507
+ * qb.where({ status: 'active' }).andWhere('age >= ?', [18]);
508
+ * ```
509
+ */
510
+ andWhere(cond: string | RawQueryFragment, params?: any[]): this;
511
+ /**
512
+ * Adds an OR WHERE clause to the query using an object condition.
513
+ *
514
+ * @example
515
+ * ```ts
516
+ * qb.where({ status: 'active' }).orWhere({ role: 'admin' });
517
+ * qb.where({ name: 'John' }).orWhere({ name: 'Jane' });
518
+ * ```
519
+ */
520
+ orWhere(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases>): this;
521
+ /**
522
+ * Adds an OR WHERE clause to the query using a raw SQL string or fragment.
523
+ *
524
+ * @example
525
+ * ```ts
526
+ * qb.where({ status: 'active' }).orWhere('role = ?', ['admin']);
527
+ * ```
528
+ */
529
+ orWhere(cond: string | RawQueryFragment, params?: any[]): this;
530
+ /**
531
+ * Adds an ORDER BY clause to the query, replacing any existing order.
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * qb.orderBy({ name: 'asc', createdAt: 'desc' });
536
+ * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
537
+ * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
538
+ * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
539
+ * ```
540
+ */
541
+ orderBy(orderBy: ContextOrderByMap<Entity, RootAlias, Context, RawAliases> | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
542
+ /**
543
+ * Adds an ORDER BY clause to the query, replacing any existing order.
544
+ *
545
+ * @example
546
+ * ```ts
547
+ * qb.orderBy({ name: 'asc', createdAt: 'desc' });
548
+ * qb.orderBy([{ name: 'asc' }, { createdAt: 'desc' }]);
549
+ * qb.orderBy({ profile: { bio: 'asc' } }); // nested via object
550
+ * qb.orderBy({ 'profile.bio': 'asc' }); // nested via dot notation
551
+ * ```
552
+ */
553
+ orderBy<const T extends Record<string, QueryOrderKeysFlat>>(orderBy: T & {
554
+ [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string> ? T[K] : K extends RawAliases ? T[K] : never;
555
+ }): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
556
+ /**
557
+ * Adds additional ORDER BY clause without replacing existing order.
558
+ */
559
+ andOrderBy(orderBy: ContextOrderByMap<Entity, RootAlias, Context, RawAliases> | ContextOrderByMap<Entity, RootAlias, Context, RawAliases>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
560
+ /**
561
+ * Adds additional ORDER BY clause without replacing existing order.
562
+ */
563
+ andOrderBy<const T extends Record<string, QueryOrderKeysFlat>>(orderBy: T & {
564
+ [K in keyof T]: K extends NestedAutoPath<Entity, RootAlias, Context, K & string> ? T[K] : K extends RawAliases ? T[K] : never;
565
+ }): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
566
+ private processOrderBy;
567
+ /** Collect custom aliases from select fields (stored as 'resolved as alias' strings by select()). */
568
+ private getSelectAliases;
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 F extends readonly Field<Entity, RootAlias, Context>[]>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
579
+ /**
580
+ * Adds a GROUP BY clause to the query.
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * qb.select([raw('count(*) as count'), 'status'])
585
+ * .groupBy('status');
586
+ * ```
587
+ */
588
+ groupBy<F extends Field<Entity, RootAlias, Context>>(fields: F): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
589
+ /**
590
+ * Adds a GROUP BY clause to the query.
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * qb.select([raw('count(*) as count'), 'status'])
595
+ * .groupBy('status');
596
+ * ```
597
+ */
598
+ groupBy<const P extends string>(fields: NestedAutoPath<Entity, RootAlias, Context, P> | readonly NestedAutoPath<Entity, RootAlias, Context, P>[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
599
+ /**
600
+ * Adds a HAVING clause to the query, typically used with GROUP BY.
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * qb.select([raw('count(*) as count'), 'status'])
605
+ * .groupBy('status')
606
+ * .having({ count: { $gt: 5 } });
607
+ * ```
608
+ */
609
+ having(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[], operator?: keyof typeof GroupOperator): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
610
+ andHaving(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
611
+ orHaving(cond?: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: any[]): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
612
+ onConflict<F extends Field<Entity, RootAlias, Context>>(fields?: F | F[] | RawQueryFragment): InsertQueryBuilder<Entity, RootAlias, Context>;
613
+ ignore(): this;
614
+ merge<const P extends string>(data: readonly NestedAutoPath<Entity, RootAlias, Context, P>[]): this;
615
+ merge<F extends Field<Entity, RootAlias, Context>>(data?: EntityData<Entity> | F[]): this;
616
+ returning<F extends Field<Entity, RootAlias, Context>>(fields?: F | F[]): this;
617
+ /**
618
+ * @internal
619
+ */
620
+ populate(populate: PopulateOptions<Entity>[], populateWhere?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`, populateFilter?: ObjectQuery<Entity> | PopulateHint | `${PopulateHint}`): this;
621
+ /**
622
+ * Sets a LIMIT clause to restrict the number of results.
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * qb.select('*').limit(10); // First 10 results
627
+ * qb.select('*').limit(10, 20); // 10 results starting from offset 20
628
+ * ```
629
+ */
630
+ limit(limit?: number, offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
631
+ /**
632
+ * Sets an OFFSET clause to skip a number of results.
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * qb.select('*').limit(10).offset(20); // Results 21-30
637
+ * ```
638
+ */
639
+ offset(offset?: number): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
640
+ withSchema(schema?: string): this;
641
+ setLockMode(mode?: LockMode, tables?: string[]): this;
642
+ setFlushMode(flushMode?: FlushMode): this;
643
+ setFlag(flag: QueryFlag): this;
644
+ unsetFlag(flag: QueryFlag): this;
645
+ hasFlag(flag: QueryFlag): boolean;
646
+ cache(config?: boolean | number | [string, number]): this;
647
+ /**
648
+ * Adds index hint to the FROM clause.
649
+ */
650
+ indexHint(sql: string | undefined): this;
651
+ /**
652
+ * Adds COLLATE clause to ORDER BY expressions.
653
+ */
654
+ collation(collation: string | undefined): this;
655
+ /**
656
+ * Prepend comment to the sql query using the syntax `/* ... *&#8205;/`. Some characters are forbidden such as `/*, *&#8205;/` and `?`.
657
+ */
658
+ comment(comment: string | string[] | undefined): this;
659
+ /**
660
+ * Add hints to the query using comment-like syntax `/*+ ... *&#8205;/`. MySQL and Oracle use this syntax for optimizer hints.
661
+ * Also various DB proxies and routers use this syntax to pass hints to alter their behavior. In other dialects the hints
662
+ * are ignored as simple comments.
663
+ */
664
+ hintComment(comment: string | string[] | undefined): this;
665
+ /**
666
+ * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
667
+ * Allows setting a main string alias of the selection data.
668
+ */
669
+ from<Entity extends object>(target: QueryBuilder<Entity>, aliasName?: string): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
670
+ /**
671
+ * Specifies FROM which entity's table select/update/delete will be executed, removing all previously set FROM-s.
672
+ * Allows setting a main string alias of the selection data.
673
+ */
674
+ from<Entity extends object>(target: EntityName<Entity>): SelectQueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
675
+ /**
676
+ * Specifies a CTE name as the FROM source, with full type safety.
677
+ * The entity type is inferred from the CTE definition passed to `.with()`.
678
+ */
679
+ from<Name extends string & keyof CTEs, Alias extends string = Name>(target: Name, aliasName?: Alias): SelectQueryBuilder<CTEs[Name], Alias, never, never, never, '*', CTEs>;
680
+ getNativeQuery(processVirtualEntity?: boolean): NativeQueryBuilder;
681
+ protected processReturningStatement(qb: NativeQueryBuilder, meta?: EntityMetadata, data?: Dictionary, returning?: Field<any>[]): void;
682
+ /**
683
+ * Returns the query with parameters as wildcards.
684
+ */
685
+ getQuery(): string;
686
+ /**
687
+ * Returns raw fragment representation of this QueryBuilder.
688
+ */
689
+ toRaw(): RawQueryFragment;
690
+ toQuery(): {
691
+ sql: string;
692
+ params: readonly unknown[];
693
+ };
694
+ /**
695
+ * Returns the list of all parameters for this query.
696
+ */
697
+ getParams(): readonly unknown[];
698
+ /**
699
+ * Returns raw interpolated query string with all the parameters inlined.
700
+ */
701
+ getFormattedQuery(): string;
702
+ /**
703
+ * @internal
704
+ */
705
+ getAliasForJoinPath(path?: string | JoinOptions, options?: ICriteriaNodeProcessOptions): string | undefined;
706
+ /**
707
+ * @internal
708
+ */
709
+ getJoinForPath(path: string, options?: ICriteriaNodeProcessOptions): JoinOptions | undefined;
710
+ /**
711
+ * @internal
712
+ */
713
+ getNextAlias(entityName?: string | EntityName): string;
714
+ /**
715
+ * Registers a join for a specific polymorphic target type.
716
+ * Used by the driver to create per-target LEFT JOINs for JOINED loading.
717
+ * @internal
718
+ */
719
+ addPolymorphicJoin(prop: EntityProperty, targetMeta: EntityMetadata, ownerAlias: string, alias: string, type: JoinType, path: string, schema?: string): void;
720
+ /**
721
+ * @internal
722
+ */
723
+ getAliasMap(): Dictionary<EntityName>;
724
+ /**
725
+ * Executes this QB and returns the raw results, mapped to the property names (unless disabled via last parameter).
726
+ * Use `method` to specify what kind of result you want to get (array/single/meta).
727
+ */
728
+ execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
729
+ private getConnection;
730
+ /**
731
+ * Executes the query and returns an async iterable (async generator) that yields results one by one.
732
+ * By default, the results are merged and mapped to entity instances, without adding them to the identity map.
733
+ * You can disable merging and mapping by passing the options `{ mergeResults: false, mapResults: false }`.
734
+ * This is useful for processing large datasets without loading everything into memory at once.
735
+ *
736
+ * ```ts
737
+ * const qb = em.createQueryBuilder(Book, 'b');
738
+ * qb.select('*').where({ title: '1984' }).leftJoinAndSelect('b.author', 'a');
739
+ *
740
+ * for await (const book of qb.stream()) {
741
+ * // book is an instance of Book entity
742
+ * console.log(book.title, book.author.name);
743
+ * }
744
+ * ```
745
+ */
746
+ stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
747
+ /**
748
+ * Alias for `qb.getResultList()`
749
+ */
750
+ getResult(): Promise<Loaded<Entity, Hint, Fields>[]>;
751
+ /**
752
+ * Executes the query, returning array of results mapped to entity instances.
753
+ */
754
+ getResultList(limit?: number): Promise<Loaded<Entity, Hint, Fields>[]>;
755
+ private propagatePopulateHint;
756
+ private mapResult;
757
+ private mapResults;
758
+ /**
759
+ * Executes the query, returning the first result or null
760
+ */
761
+ getSingleResult(): Promise<Loaded<Entity, Hint, Fields> | null>;
762
+ /**
763
+ * Executes count query (without offset and limit), returning total count of results
764
+ */
765
+ getCount<F extends Field<Entity, RootAlias, Context>>(field?: F | F[], distinct?: boolean): Promise<number>;
766
+ /**
767
+ * Executes the query, returning both array of results and total count query (without offset and limit).
768
+ */
769
+ getResultAndCount(): Promise<[Loaded<Entity, Hint, Fields>[], number]>;
770
+ /**
771
+ * Returns native query builder instance with sub-query aliased with given alias.
772
+ */
773
+ as(alias: string): NativeQueryBuilder;
774
+ /**
775
+ * Returns native query builder instance with sub-query aliased with given alias.
776
+ * 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.
777
+ */
778
+ as<T>(targetEntity: EntityName<T>, alias: EntityKey<T>): NativeQueryBuilder;
779
+ /**
780
+ * Combines the current query with one or more other queries using `UNION ALL`.
781
+ * All queries must select the same columns. Returns a `QueryBuilder` that
782
+ * can be used with `$in`, passed to `qb.from()`, or converted via `.getQuery()`,
783
+ * `.getParams()`, `.toQuery()`, `.toRaw()`, etc.
784
+ *
785
+ * ```ts
786
+ * const qb1 = em.createQueryBuilder(Employee).select('id').where(condition1);
787
+ * const qb2 = em.createQueryBuilder(Employee).select('id').where(condition2);
788
+ * const qb3 = em.createQueryBuilder(Employee).select('id').where(condition3);
789
+ * const subquery = qb1.unionAll(qb2, qb3);
790
+ *
791
+ * const results = await em.find(Employee, { id: { $in: subquery } });
792
+ * ```
793
+ */
794
+ unionAll(...others: (QueryBuilder<any> | NativeQueryBuilder)[]): QueryBuilder<Entity>;
795
+ /**
796
+ * Combines the current query with one or more other queries using `UNION` (with deduplication).
797
+ * All queries must select the same columns. Returns a `QueryBuilder` that
798
+ * can be used with `$in`, passed to `qb.from()`, or converted via `.getQuery()`,
799
+ * `.getParams()`, `.toQuery()`, `.toRaw()`, etc.
800
+ *
801
+ * ```ts
802
+ * const qb1 = em.createQueryBuilder(Employee).select('id').where(condition1);
803
+ * const qb2 = em.createQueryBuilder(Employee).select('id').where(condition2);
804
+ * const subquery = qb1.union(qb2);
805
+ *
806
+ * const results = await em.find(Employee, { id: { $in: subquery } });
807
+ * ```
808
+ */
809
+ union(...others: (QueryBuilder<any> | NativeQueryBuilder)[]): QueryBuilder<Entity>;
810
+ private buildUnionQuery;
811
+ /**
812
+ * Adds a Common Table Expression (CTE) to the query.
813
+ * When a `QueryBuilder` is passed, its entity type is tracked for type-safe `from()`.
814
+ *
815
+ * @example
816
+ * ```ts
817
+ * const recentBooks = em.createQueryBuilder(Book, 'b').select('*').where({ ... });
818
+ * const qb = em.createQueryBuilder(Author, 'a')
819
+ * .with('recent_books', recentBooks)
820
+ * .select('*')
821
+ * .from('recent_books', 'rb'); // entity type inferred as Book
822
+ * ```
823
+ */
824
+ with<Name extends string, Q extends QueryBuilder<any>>(name: Name, query: Q, options?: CteOptions): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, Q extends QueryBuilder<infer T> ? T : object>>;
825
+ /**
826
+ * Adds a Common Table Expression (CTE) to the query using a `NativeQueryBuilder` or raw SQL fragment.
827
+ * The CTE name is tracked but without entity type inference — use `from()` to query from it.
828
+ */
829
+ with<Name extends string>(name: Name, query: NativeQueryBuilder | RawQueryFragment, options?: CteOptions): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, object>>;
830
+ /**
831
+ * Adds a recursive Common Table Expression (CTE) to the query.
832
+ * When a `QueryBuilder` is passed, its entity type is tracked for type-safe `from()`.
833
+ *
834
+ * @example
835
+ * ```ts
836
+ * const base = em.createQueryBuilder(Category).select('*').where({ parent: null });
837
+ * const rec = em.createQueryBuilder(Category, 'c').select('c.*')
838
+ * .leftJoin('c.parent', 'ct', { id: sql.ref('c.parentId') });
839
+ * const qb = em.createQueryBuilder(Category)
840
+ * .withRecursive('category_tree', base.unionAll(rec))
841
+ * .select('*')
842
+ * .from('category_tree', 'ct'); // entity type inferred as Category
843
+ * ```
844
+ */
845
+ withRecursive<Name extends string, Q extends QueryBuilder<any>>(name: Name, query: Q, options?: CteOptions): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, Q extends QueryBuilder<infer T> ? T : object>>;
846
+ /**
847
+ * Adds a recursive Common Table Expression (CTE) to the query using a `NativeQueryBuilder` or raw SQL fragment.
848
+ * The CTE name is tracked but without entity type inference — use `from()` to query from it.
849
+ */
850
+ withRecursive<Name extends string>(name: Name, query: NativeQueryBuilder | RawQueryFragment, options?: CteOptions): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs & Record<Name, object>>;
851
+ private addCte;
852
+ clone(reset?: boolean | (keyof QBState<Entity>)[], preserve?: (keyof QBState<Entity>)[]): QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs>;
853
+ /**
854
+ * Sets logger context for this query builder.
855
+ */
856
+ setLoggerContext(context: LoggingOptions & Dictionary): void;
857
+ /**
858
+ * Gets logger context for this query builder.
859
+ */
860
+ getLoggerContext<T extends Dictionary & LoggingOptions = Dictionary>(): T;
861
+ private fromVirtual;
862
+ /**
863
+ * Adds a join from a property object. Used internally for TPT joins where the property
864
+ * is synthetic (not in entity.properties) but defined on metadata (e.g., tptParentProp).
865
+ * The caller must create the alias first via createAlias().
866
+ * @internal
867
+ */
868
+ addPropertyJoin(prop: EntityProperty, ownerAlias: string, alias: string, type: JoinType, path: string, schema?: string): string;
869
+ private joinReference;
870
+ protected prepareFields<T>(fields: InternalField<T>[], type?: 'where' | 'groupBy' | 'sub-query', schema?: string): (string | RawQueryFragment)[];
871
+ /**
872
+ * Resolves nested paths like `a.books.title` to their actual field references.
873
+ * Auto-joins relations as needed and returns `{alias}.{field}`.
874
+ * For embeddeds: navigates into flattened embeddeds to return the correct field name.
875
+ */
876
+ protected resolveNestedPath(field: string): string | string[];
877
+ protected init(type: QueryType, data?: any, cond?: any): this;
878
+ private getQueryBase;
879
+ private applyDiscriminatorCondition;
880
+ /**
881
+ * Ensures TPT joins are applied. Can be called early before finalize() to populate
882
+ * the _tptAlias map for use in join resolution. Safe to call multiple times.
883
+ * @internal
884
+ */
885
+ ensureTPTJoins(): void;
886
+ /**
887
+ * For TPT (Table-Per-Type) inheritance: INNER JOINs parent tables.
888
+ * When querying a child entity, we need to join all parent tables.
889
+ * Field selection is handled separately in addTPTParentFields().
890
+ */
891
+ private applyTPTJoins;
892
+ /**
893
+ * For TPT inheritance: adds field selections from parent tables.
894
+ */
895
+ private addTPTParentFields;
896
+ /**
897
+ * For TPT polymorphic queries: LEFT JOINs all child tables when querying a TPT base class.
898
+ * Adds discriminator and child fields to determine and load the concrete type.
899
+ */
900
+ private applyTPTPolymorphicJoins;
901
+ private finalize;
902
+ /** @internal */
903
+ processPopulateHint(): void;
904
+ private processPopulateWhere;
905
+ private mergeOnConditions;
906
+ /**
907
+ * When adding an inner join on a left joined relation, we need to nest them,
908
+ * otherwise the inner join could discard rows of the root table.
909
+ */
910
+ private processNestedJoins;
911
+ private hasToManyJoins;
912
+ protected wrapPaginateSubQuery(meta: EntityMetadata): void;
913
+ /**
914
+ * Computes the set of populate paths from the _populate hints.
915
+ */
916
+ protected getPopulatePaths(): Set<string>;
917
+ protected normalizeJoinPath(join: JoinOptions, meta: EntityMetadata): string;
918
+ /**
919
+ * Transfers WHERE conditions to ORDER BY joins that are not used for population.
920
+ * This ensures the outer query's ORDER BY uses the same filtered rows as the subquery.
921
+ * GH #6160
922
+ */
923
+ protected transferConditionsForOrderByJoins(meta: EntityMetadata, cond: Dictionary | undefined, populatePaths: Set<string>): void;
924
+ /**
925
+ * Removes joins that are not used for population or ordering to improve performance.
926
+ */
927
+ protected pruneJoinsForPagination(): void;
928
+ /**
929
+ * Transfers WHERE conditions that reference a join alias to the join's ON clause.
930
+ * This is needed when a join is kept for ORDER BY after pagination wrapping,
931
+ * so the outer query orders by the same filtered rows as the subquery.
932
+ * @internal
933
+ */
934
+ protected transferConditionsToJoin(cond: Dictionary, join: JoinOptions, path?: string): void;
935
+ private wrapModifySubQuery;
936
+ private getSchema;
937
+ /** @internal */
938
+ createAlias<U = unknown>(entityName: EntityName<U>, aliasName: string, subQuery?: NativeQueryBuilder | RawQueryFragment): Alias<U>;
939
+ private createMainAlias;
940
+ private fromSubQuery;
941
+ private fromEntityName;
942
+ private fromRawTable;
943
+ private createQueryBuilderHelper;
944
+ private ensureFromClause;
945
+ private ensureNotFinalized;
1520
946
  }
1521
- export interface RunQueryBuilder<
1522
- Entity extends object,
1523
- RootAlias extends string = never,
1524
- Context extends object = never,
1525
- RawAliases extends string = never,
1526
- > extends Omit<
1527
- QueryBuilder<Entity, RootAlias, never, Context, RawAliases, '*'>,
1528
- 'getResult' | 'getSingleResult' | 'getResultList' | 'where'
1529
- > {
1530
- where(
1531
- cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string,
1532
- params?: keyof typeof GroupOperator | any[],
1533
- operator?: keyof typeof GroupOperator,
1534
- ): this;
1535
- execute<Result = QueryResult<Entity>>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
947
+ 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'> {
948
+ where(cond: QBFilterQuery<Entity, RootAlias, Context, RawAliases> | string, params?: keyof typeof GroupOperator | any[], operator?: keyof typeof GroupOperator): this;
949
+ execute<Result = QueryResult<Entity>>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
1536
950
  }
1537
951
  /**
1538
952
  * @internal Optimized DTO type for execute().
@@ -1547,111 +961,45 @@ export interface RunQueryBuilder<
1547
961
  * - Fields + nested joins: falls back to EntityDTO<Loaded<T, H, F>>
1548
962
  */
1549
963
  type DirectDTO<T, F extends keyof T> = {
1550
- [K in F]: EntityDTOProp<T, NonNullable<T[K]>> | Extract<T[K], null | undefined>;
964
+ [K in F]: EntityDTOProp<T, NonNullable<T[K]>> | Extract<T[K], null | undefined>;
1551
965
  };
1552
- type PopulatedDTO<T, K extends keyof T> =
1553
- NonNullable<T[K]> extends Collection<infer U> ? EntityDTOFlat<U & object>[] : EntityDTOFlat<ExpandProperty<T[K]>>;
966
+ type PopulatedDTO<T, K extends keyof T> = NonNullable<T[K]> extends Collection<infer U> ? EntityDTOFlat<U & object>[] : EntityDTOFlat<ExpandProperty<T[K]>>;
1554
967
  type SubFields<F extends string, Rel extends string> = F extends `${Rel}.${infer Sub}` ? Sub : never;
1555
- type RootFields<F extends string, H extends string> = F extends `${string}.${string}`
1556
- ? F extends `${H}.${string}`
1557
- ? never
1558
- : F
1559
- : F;
1560
- type JoinDTO<T, K extends keyof T, F extends string> =
1561
- NonNullable<T[K]> extends Collection<infer U>
1562
- ? SubFields<F, K & string> extends never
1563
- ? EntityDTOProp<T, Collection<U>>
1564
- : DirectDTO<U, (SubFields<F, K & string> | PrimaryProperty<U>) & keyof U>[]
1565
- : SubFields<F, K & string> extends never
1566
- ? EntityDTOProp<T, T[K]>
1567
- :
1568
- | DirectDTO<
1569
- NonNullable<T[K]>,
1570
- (SubFields<F, K & string> | PrimaryProperty<NonNullable<T[K]>>) & keyof NonNullable<T[K]>
1571
- >
1572
- | Extract<T[K], null | undefined>;
1573
- type ExecuteDTO<T, H extends string, F extends string> = [H] extends [never]
1574
- ? [F] extends ['*']
1575
- ? EntityDTOFlat<T>
1576
- : DirectDTO<T, F & keyof T>
1577
- : [F] extends ['*']
1578
- ? true extends (H extends `${string}.${string}` ? true : false)
1579
- ? SerializeDTO<T, H>
1580
- : Omit<EntityDTOFlat<T>, H & keyof EntityDTOFlat<T>> & {
1581
- [K in H & keyof T as K & keyof EntityDTOFlat<T>]: PopulatedDTO<T, K> | Extract<T[K], null | undefined>;
1582
- }
1583
- : true extends (H extends `${string}.${string}` ? true : false)
1584
- ? EntityDTOFlat<Loaded<T, H, F>>
1585
- : DirectDTO<T, (RootFields<F, H> | PrimaryProperty<T>) & keyof T> & {
1586
- [K in H & keyof T]: JoinDTO<T, K, F>;
1587
- };
968
+ type RootFields<F extends string, H extends string> = F extends `${string}.${string}` ? F extends `${H}.${string}` ? never : F : F;
969
+ type JoinDTO<T, K extends keyof T, F extends string> = NonNullable<T[K]> extends Collection<infer U> ? SubFields<F, K & string> extends never ? EntityDTOProp<T, Collection<U>> : DirectDTO<U, (SubFields<F, K & string> | PrimaryProperty<U>) & keyof U>[] : SubFields<F, K & string> extends never ? EntityDTOProp<T, T[K]> : DirectDTO<NonNullable<T[K]>, (SubFields<F, K & string> | PrimaryProperty<NonNullable<T[K]>>) & keyof NonNullable<T[K]>> | Extract<T[K], null | undefined>;
970
+ type ExecuteDTO<T, H extends string, F extends string> = [H] extends [never] ? [F] extends ['*'] ? EntityDTOFlat<T> : DirectDTO<T, F & keyof T> : [F] extends ['*'] ? true extends (H extends `${string}.${string}` ? true : false) ? SerializeDTO<T, H> : Omit<EntityDTOFlat<T>, H & keyof EntityDTOFlat<T>> & {
971
+ [K in H & keyof T as K & keyof EntityDTOFlat<T>]: PopulatedDTO<T, K> | Extract<T[K], null | undefined>;
972
+ } : true extends (H extends `${string}.${string}` ? true : false) ? EntityDTOFlat<Loaded<T, H, F>> : DirectDTO<T, (RootFields<F, H> | PrimaryProperty<T>) & keyof T> & {
973
+ [K in H & keyof T]: JoinDTO<T, K, F>;
974
+ };
1588
975
  /** Shorthand for `QueryBuilder` with all generic parameters set to `any`. */
1589
976
  export type AnyQueryBuilder<T extends object = AnyEntity> = QueryBuilder<T, any, any, any, any, any, any>;
1590
- export interface SelectQueryBuilder<
1591
- Entity extends object = AnyEntity,
1592
- RootAlias extends string = never,
1593
- Hint extends string = never,
1594
- Context extends object = never,
1595
- RawAliases extends string = never,
1596
- Fields extends string = '*',
1597
- CTEs extends Record<string, object> = {},
1598
- > extends QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs> {
1599
- execute<Result = ExecuteDTO<Entity, Hint, Fields>[]>(
1600
- method?: 'all' | 'get' | 'run',
1601
- mapResults?: boolean,
1602
- ): Promise<Result>;
1603
- execute<Result = ExecuteDTO<Entity, Hint, Fields>[]>(method: 'all', mapResults?: boolean): Promise<Result>;
1604
- execute<Result = ExecuteDTO<Entity, Hint, Fields>>(method: 'get', mapResults?: boolean): Promise<Result>;
1605
- execute<Result = QueryResult<Entity>>(method: 'run', mapResults?: boolean): Promise<Result>;
977
+ 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 = '*', CTEs extends Record<string, object> = {}> extends QueryBuilder<Entity, RootAlias, Hint, Context, RawAliases, Fields, CTEs> {
978
+ execute<Result = ExecuteDTO<Entity, Hint, Fields>[]>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
979
+ execute<Result = ExecuteDTO<Entity, Hint, Fields>[]>(method: 'all', mapResults?: boolean): Promise<Result>;
980
+ execute<Result = ExecuteDTO<Entity, Hint, Fields>>(method: 'get', mapResults?: boolean): Promise<Result>;
981
+ execute<Result = QueryResult<Entity>>(method: 'run', mapResults?: boolean): Promise<Result>;
1606
982
  }
1607
983
  export interface CountQueryBuilder<Entity extends object> extends QueryBuilder<Entity, any, any> {
1608
- execute<
1609
- Result = {
1610
- count: number;
1611
- }[],
1612
- >(
1613
- method?: 'all' | 'get' | 'run',
1614
- mapResults?: boolean,
1615
- ): Promise<Result>;
1616
- execute<
1617
- Result = {
1618
- count: number;
1619
- }[],
1620
- >(
1621
- method: 'all',
1622
- mapResults?: boolean,
1623
- ): Promise<Result>;
1624
- execute<
1625
- Result = {
1626
- count: number;
1627
- },
1628
- >(
1629
- method: 'get',
1630
- mapResults?: boolean,
1631
- ): Promise<Result>;
1632
- execute<
1633
- Result = QueryResult<{
1634
- count: number;
1635
- }>,
1636
- >(
1637
- method: 'run',
1638
- mapResults?: boolean,
1639
- ): Promise<Result>;
984
+ execute<Result = {
985
+ count: number;
986
+ }[]>(method?: 'all' | 'get' | 'run', mapResults?: boolean): Promise<Result>;
987
+ execute<Result = {
988
+ count: number;
989
+ }[]>(method: 'all', mapResults?: boolean): Promise<Result>;
990
+ execute<Result = {
991
+ count: number;
992
+ }>(method: 'get', mapResults?: boolean): Promise<Result>;
993
+ execute<Result = QueryResult<{
994
+ count: number;
995
+ }>>(method: 'run', mapResults?: boolean): Promise<Result>;
996
+ }
997
+ export interface InsertQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
998
+ }
999
+ export interface UpdateQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
1000
+ }
1001
+ export interface DeleteQueryBuilder<T extends object, RootAlias extends string = never, Context extends object = never> extends RunQueryBuilder<T, RootAlias, Context> {
1002
+ }
1003
+ export interface TruncateQueryBuilder<T extends object> extends RunQueryBuilder<T> {
1640
1004
  }
1641
- export interface InsertQueryBuilder<
1642
- T extends object,
1643
- RootAlias extends string = never,
1644
- Context extends object = never,
1645
- > extends RunQueryBuilder<T, RootAlias, Context> {}
1646
- export interface UpdateQueryBuilder<
1647
- T extends object,
1648
- RootAlias extends string = never,
1649
- Context extends object = never,
1650
- > extends RunQueryBuilder<T, RootAlias, Context> {}
1651
- export interface DeleteQueryBuilder<
1652
- T extends object,
1653
- RootAlias extends string = never,
1654
- Context extends object = never,
1655
- > extends RunQueryBuilder<T, RootAlias, Context> {}
1656
- export interface TruncateQueryBuilder<T extends object> extends RunQueryBuilder<T> {}
1657
1005
  export {};