@mikro-orm/sql 7.0.10 → 7.0.11-dev.0

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