• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

typeorm / typeorm / 12968994847

25 Jan 2025 10:33PM UTC coverage: 71.671% (-0.7%) from 72.369%
12968994847

Pull #11262

github

web-flow
Merge f05a3d4e8 into 79960e136
Pull Request #11262: ci(PR): adjust timeouts and add concurrency

8567 of 12650 branches covered (67.72%)

Branch coverage included in aggregate %.

17727 of 24037 relevant lines covered (73.75%)

135711.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.45
/src/query-builder/QueryBuilder.ts
1
import { ObjectLiteral } from "../common/ObjectLiteral"
2
import { QueryRunner } from "../query-runner/QueryRunner"
3
import { DataSource } from "../data-source/DataSource"
4
import { QueryBuilderCteOptions } from "./QueryBuilderCte"
5
import { QueryExpressionMap } from "./QueryExpressionMap"
29✔
6
import { SelectQueryBuilder } from "./SelectQueryBuilder"
7
import { UpdateQueryBuilder } from "./UpdateQueryBuilder"
8
import { DeleteQueryBuilder } from "./DeleteQueryBuilder"
9
import { SoftDeleteQueryBuilder } from "./SoftDeleteQueryBuilder"
10
import { InsertQueryBuilder } from "./InsertQueryBuilder"
11
import { RelationQueryBuilder } from "./RelationQueryBuilder"
12
import { EntityTarget } from "../common/EntityTarget"
13
import { Alias } from "./Alias"
14
import { Brackets } from "./Brackets"
29✔
15
import { QueryDeepPartialEntity } from "./QueryPartialEntity"
16
import { EntityMetadata } from "../metadata/EntityMetadata"
17
import { ColumnMetadata } from "../metadata/ColumnMetadata"
18
import { FindOperator } from "../find-options/FindOperator"
29✔
19
import { In } from "../find-options/operator/In"
29✔
20
import { TypeORMError } from "../error"
29✔
21
import { WhereClause, WhereClauseCondition } from "./WhereClause"
22
import { NotBrackets } from "./NotBrackets"
23
import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundError"
29✔
24
import { ReturningType } from "../driver/Driver"
25
import { OracleDriver } from "../driver/oracle/OracleDriver"
26
import { InstanceChecker } from "../util/InstanceChecker"
29✔
27
import { escapeRegExp } from "../util/escapeRegExp"
29✔
28

29
// todo: completely cover query builder with tests
30
// todo: entityOrProperty can be target name. implement proper behaviour if it is.
31
// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
32
// todo: fix problem with long aliases eg getMaxIdentifierLength
33
// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
34
// todo: implement joinAlways in relations and relationId
35
// todo: finish partial selection
36
// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
37
// todo: implement @Select decorator
38
// todo: add select and map functions
39

40
// todo: implement relation/entity loading and setting them into properties within a separate query
41
// .loadAndMap("post.categories", "post.categories", qb => ...)
42
// .loadAndMap("post.categories", Category, qb => ...)
43

44
/**
45
 * Allows to build complex sql queries in a fashion way and execute those queries.
46
 */
47
export abstract class QueryBuilder<Entity extends ObjectLiteral> {
29✔
48
    readonly "@instanceof" = Symbol.for("QueryBuilder")
1,104,110✔
49

50
    // -------------------------------------------------------------------------
51
    // Public Properties
52
    // -------------------------------------------------------------------------
53

54
    /**
55
     * Connection on which QueryBuilder was created.
56
     */
57
    readonly connection: DataSource
58

59
    /**
60
     * Contains all properties of the QueryBuilder that needs to be build a final query.
61
     */
62
    readonly expressionMap: QueryExpressionMap
63

64
    // -------------------------------------------------------------------------
65
    // Protected Properties
66
    // -------------------------------------------------------------------------
67

68
    /**
69
     * Query runner used to execute query builder query.
70
     */
71
    protected queryRunner?: QueryRunner
72

73
    /**
74
     * If QueryBuilder was created in a subquery mode then its parent QueryBuilder (who created subquery) will be stored here.
75
     */
76
    protected parentQueryBuilder: QueryBuilder<any>
77

78
    /**
79
     * Memo to help keep place of current parameter index for `createParameter`
80
     */
81
    private parameterIndex = 0
1,104,110✔
82

83
    /**
84
     * Contains all registered query builder classes.
85
     */
86
    private static queryBuilderRegistry: Record<string, any> = {}
29✔
87

88
    // -------------------------------------------------------------------------
89
    // Constructor
90
    // -------------------------------------------------------------------------
91

92
    /**
93
     * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
94
     */
95
    constructor(queryBuilder: QueryBuilder<any>)
96

97
    /**
98
     * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
99
     */
100
    constructor(connection: DataSource, queryRunner?: QueryRunner)
101

102
    /**
103
     * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
104
     */
105
    constructor(
106
        connectionOrQueryBuilder: DataSource | QueryBuilder<any>,
107
        queryRunner?: QueryRunner,
108
    ) {
109
        if (InstanceChecker.isDataSource(connectionOrQueryBuilder)) {
1,104,110✔
110
            this.connection = connectionOrQueryBuilder
829,811✔
111
            this.queryRunner = queryRunner
829,811✔
112
            this.expressionMap = new QueryExpressionMap(this.connection)
829,811✔
113
        } else {
114
            this.connection = connectionOrQueryBuilder.connection
274,299✔
115
            this.queryRunner = connectionOrQueryBuilder.queryRunner
274,299✔
116
            this.expressionMap = connectionOrQueryBuilder.expressionMap.clone()
274,299✔
117
        }
118
    }
119

120
    static registerQueryBuilderClass(name: string, factory: any) {
121
        QueryBuilder.queryBuilderRegistry[name] = factory
87,078✔
122
    }
123

124
    // -------------------------------------------------------------------------
125
    // Abstract Methods
126
    // -------------------------------------------------------------------------
127

128
    /**
129
     * Gets generated SQL query without parameters being replaced.
130
     */
131
    abstract getQuery(): string
132

133
    // -------------------------------------------------------------------------
134
    // Accessors
135
    // -------------------------------------------------------------------------
136

137
    /**
138
     * Gets the main alias string used in this query builder.
139
     */
140
    get alias(): string {
141
        if (!this.expressionMap.mainAlias)
229,809!
142
            throw new TypeORMError(`Main alias is not set`) // todo: better exception
×
143

144
        return this.expressionMap.mainAlias.name
229,809✔
145
    }
146

147
    // -------------------------------------------------------------------------
148
    // Public Methods
149
    // -------------------------------------------------------------------------
150

151
    /**
152
     * Creates SELECT query.
153
     * Replaces all previous selections if they exist.
154
     */
155
    select(): SelectQueryBuilder<Entity>
156

157
    /**
158
     * Creates SELECT query and selects given data.
159
     * Replaces all previous selections if they exist.
160
     */
161
    select(
162
        selection: string,
163
        selectionAliasName?: string,
164
    ): SelectQueryBuilder<Entity>
165

166
    /**
167
     * Creates SELECT query and selects given data.
168
     * Replaces all previous selections if they exist.
169
     */
170
    select(selection: string[]): SelectQueryBuilder<Entity>
171

172
    /**
173
     * Creates SELECT query and selects given data.
174
     * Replaces all previous selections if they exist.
175
     */
176
    select(
177
        selection?: string | string[],
178
        selectionAliasName?: string,
179
    ): SelectQueryBuilder<Entity> {
180
        this.expressionMap.queryType = "select"
480✔
181
        if (Array.isArray(selection)) {
480!
182
            this.expressionMap.selects = selection.map((selection) => ({
×
183
                selection: selection,
184
            }))
185
        } else if (selection) {
480✔
186
            this.expressionMap.selects = [
480✔
187
                { selection: selection, aliasName: selectionAliasName },
188
            ]
189
        }
190

191
        if (InstanceChecker.isSelectQueryBuilder(this)) return this as any
480!
192

193
        return QueryBuilder.queryBuilderRegistry["SelectQueryBuilder"](this)
480✔
194
    }
195

196
    /**
197
     * Creates INSERT query.
198
     */
199
    insert(): InsertQueryBuilder<Entity> {
200
        this.expressionMap.queryType = "insert"
229,071✔
201

202
        if (InstanceChecker.isInsertQueryBuilder(this)) return this as any
229,071!
203

204
        return QueryBuilder.queryBuilderRegistry["InsertQueryBuilder"](this)
229,071✔
205
    }
206

207
    /**
208
     * Creates UPDATE query and applies given update values.
209
     */
210
    update(): UpdateQueryBuilder<Entity>
211

212
    /**
213
     * Creates UPDATE query and applies given update values.
214
     */
215
    update(
216
        updateSet: QueryDeepPartialEntity<Entity>,
217
    ): UpdateQueryBuilder<Entity>
218

219
    /**
220
     * Creates UPDATE query for the given entity and applies given update values.
221
     */
222
    update<Entity extends ObjectLiteral>(
223
        entity: EntityTarget<Entity>,
224
        updateSet?: QueryDeepPartialEntity<Entity>,
225
    ): UpdateQueryBuilder<Entity>
226

227
    /**
228
     * Creates UPDATE query for the given table name and applies given update values.
229
     */
230
    update(
231
        tableName: string,
232
        updateSet?: QueryDeepPartialEntity<Entity>,
233
    ): UpdateQueryBuilder<Entity>
234

235
    /**
236
     * Creates UPDATE query and applies given update values.
237
     */
238
    update(
239
        entityOrTableNameUpdateSet?: EntityTarget<any> | ObjectLiteral,
240
        maybeUpdateSet?: ObjectLiteral,
241
    ): UpdateQueryBuilder<any> {
242
        const updateSet = maybeUpdateSet
20,068!
243
            ? maybeUpdateSet
244
            : (entityOrTableNameUpdateSet as ObjectLiteral | undefined)
245
        entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
20,068!
246
            entityOrTableNameUpdateSet,
247
        )
248
            ? entityOrTableNameUpdateSet.options.name
249
            : entityOrTableNameUpdateSet
250

251
        if (
20,068✔
252
            typeof entityOrTableNameUpdateSet === "function" ||
20,559✔
253
            typeof entityOrTableNameUpdateSet === "string"
254
        ) {
255
            const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet)
19,856✔
256
            this.expressionMap.setMainAlias(mainAlias)
19,856✔
257
        }
258

259
        this.expressionMap.queryType = "update"
20,068✔
260
        this.expressionMap.valuesSet = updateSet
20,068✔
261

262
        if (InstanceChecker.isUpdateQueryBuilder(this)) return this as any
20,068!
263

264
        return QueryBuilder.queryBuilderRegistry["UpdateQueryBuilder"](this)
20,068✔
265
    }
266

267
    /**
268
     * Creates DELETE query.
269
     */
270
    delete(): DeleteQueryBuilder<Entity> {
271
        this.expressionMap.queryType = "delete"
4,591✔
272

273
        if (InstanceChecker.isDeleteQueryBuilder(this)) return this as any
4,591!
274

275
        return QueryBuilder.queryBuilderRegistry["DeleteQueryBuilder"](this)
4,591✔
276
    }
277

278
    softDelete(): SoftDeleteQueryBuilder<any> {
279
        this.expressionMap.queryType = "soft-delete"
1,186✔
280

281
        if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this as any
1,186!
282

283
        return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this)
1,186✔
284
    }
285

286
    restore(): SoftDeleteQueryBuilder<any> {
287
        this.expressionMap.queryType = "restore"
319✔
288

289
        if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this as any
319!
290

291
        return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this)
319✔
292
    }
293

294
    /**
295
     * Sets entity's relation with which this query builder gonna work.
296
     */
297
    relation(propertyPath: string): RelationQueryBuilder<Entity>
298

299
    /**
300
     * Sets entity's relation with which this query builder gonna work.
301
     */
302
    relation<T extends ObjectLiteral>(
303
        entityTarget: EntityTarget<T>,
304
        propertyPath: string,
305
    ): RelationQueryBuilder<T>
306

307
    /**
308
     * Sets entity's relation with which this query builder gonna work.
309
     */
310
    relation(
311
        entityTargetOrPropertyPath: Function | string,
312
        maybePropertyPath?: string,
313
    ): RelationQueryBuilder<Entity> {
314
        const entityTarget =
315
            arguments.length === 2 ? entityTargetOrPropertyPath : undefined
2,010!
316
        const propertyPath =
317
            arguments.length === 2
2,010!
318
                ? (maybePropertyPath as string)
319
                : (entityTargetOrPropertyPath as string)
320

321
        this.expressionMap.queryType = "relation"
2,010✔
322
        this.expressionMap.relationPropertyPath = propertyPath
2,010✔
323

324
        if (entityTarget) {
2,010✔
325
            const mainAlias = this.createFromAlias(entityTarget)
2,010✔
326
            this.expressionMap.setMainAlias(mainAlias)
2,010✔
327
        }
328

329
        if (InstanceChecker.isRelationQueryBuilder(this)) return this as any
2,010!
330

331
        return QueryBuilder.queryBuilderRegistry["RelationQueryBuilder"](this)
2,010✔
332
    }
333

334
    /**
335
     * Checks if given relation exists in the entity.
336
     * Returns true if relation exists, false otherwise.
337
     *
338
     * todo: move this method to manager? or create a shortcut?
339
     */
340
    hasRelation<T>(target: EntityTarget<T>, relation: string): boolean
341

342
    /**
343
     * Checks if given relations exist in the entity.
344
     * Returns true if relation exists, false otherwise.
345
     *
346
     * todo: move this method to manager? or create a shortcut?
347
     */
348
    hasRelation<T>(target: EntityTarget<T>, relation: string[]): boolean
349

350
    /**
351
     * Checks if given relation or relations exist in the entity.
352
     * Returns true if relation exists, false otherwise.
353
     *
354
     * todo: move this method to manager? or create a shortcut?
355
     */
356
    hasRelation<T>(
357
        target: EntityTarget<T>,
358
        relation: string | string[],
359
    ): boolean {
360
        const entityMetadata = this.connection.getMetadata(target)
×
361
        const relations = Array.isArray(relation) ? relation : [relation]
×
362
        return relations.every((relation) => {
×
363
            return !!entityMetadata.findRelationWithPropertyPath(relation)
×
364
        })
365
    }
366

367
    /**
368
     * Check the existence of a parameter for this query builder.
369
     */
370
    hasParameter(key: string): boolean {
371
        return (
2,030,259✔
372
            this.parentQueryBuilder?.hasParameter(key) ||
4,054,958✔
373
            key in this.expressionMap.parameters
374
        )
375
    }
376

377
    /**
378
     * Sets parameter name and its value.
379
     *
380
     * The key for this parameter may contain numbers, letters, underscores, or periods.
381
     */
382
    setParameter(key: string, value: any): this {
383
        if (typeof value === "function") {
2,080,118✔
384
            throw new TypeORMError(
29✔
385
                `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`,
386
            )
387
        }
388

389
        if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
2,080,089!
390
            throw new TypeORMError(
×
391
                "QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.",
392
            )
393
        }
394

395
        if (this.parentQueryBuilder) {
2,080,089✔
396
            this.parentQueryBuilder.setParameter(key, value)
82,899✔
397
        }
398

399
        this.expressionMap.parameters[key] = value
2,080,089✔
400
        return this
2,080,089✔
401
    }
402

403
    /**
404
     * Adds all parameters from the given object.
405
     */
406
    setParameters(parameters: ObjectLiteral): this {
407
        for (const [key, value] of Object.entries(parameters)) {
53,942✔
408
            this.setParameter(key, value)
58,171✔
409
        }
410

411
        return this
53,913✔
412
    }
413

414
    protected createParameter(value: any): string {
415
        let parameterName
416

417
        do {
1,937,727✔
418
            parameterName = `orm_param_${this.parameterIndex++}`
1,941,945✔
419
        } while (this.hasParameter(parameterName))
420

421
        this.setParameter(parameterName, value)
1,937,727✔
422

423
        return `:${parameterName}`
1,937,727✔
424
    }
425

426
    /**
427
     * Adds native parameters from the given object.
428
     *
429
     * @deprecated Use `setParameters` instead
430
     */
431
    setNativeParameters(parameters: ObjectLiteral): this {
432
        // set parent query builder parameters as well in sub-query mode
433
        if (this.parentQueryBuilder) {
7,522!
434
            this.parentQueryBuilder.setNativeParameters(parameters)
×
435
        }
436

437
        Object.keys(parameters).forEach((key) => {
7,522✔
438
            this.expressionMap.nativeParameters[key] = parameters[key]
×
439
        })
440
        return this
7,522✔
441
    }
442

443
    /**
444
     * Gets all parameters.
445
     */
446
    getParameters(): ObjectLiteral {
447
        const parameters: ObjectLiteral = Object.assign(
468,144✔
448
            {},
449
            this.expressionMap.parameters,
450
        )
451

452
        // add discriminator column parameter if it exist
453
        if (
468,144✔
454
            this.expressionMap.mainAlias &&
936,288✔
455
            this.expressionMap.mainAlias.hasMetadata
456
        ) {
457
            const metadata = this.expressionMap.mainAlias!.metadata
453,715✔
458
            if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
453,715✔
459
                const values = metadata.childEntityMetadatas
3,017✔
460
                    .filter(
461
                        (childMetadata) => childMetadata.discriminatorColumn,
409✔
462
                    )
463
                    .map((childMetadata) => childMetadata.discriminatorValue)
409✔
464
                values.push(metadata.discriminatorValue)
3,017✔
465
                parameters["discriminatorColumnValues"] = values
3,017✔
466
            }
467
        }
468

469
        return parameters
468,144✔
470
    }
471

472
    /**
473
     * Prints sql to stdout using console.log.
474
     */
475
    printSql(): this {
476
        // TODO rename to logSql()
477
        const [query, parameters] = this.getQueryAndParameters()
×
478
        this.connection.logger.logQuery(query, parameters)
×
479
        return this
×
480
    }
481

482
    /**
483
     * Gets generated sql that will be executed.
484
     * Parameters in the query are escaped for the currently used driver.
485
     */
486
    getSql(): string {
487
        return this.getQueryAndParameters()[0]
1,090✔
488
    }
489

490
    /**
491
     * Gets query to be executed with all parameters used in it.
492
     */
493
    getQueryAndParameters(): [string, any[]] {
494
        // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
495
        const query = this.getQuery()
460,276✔
496
        const parameters = this.getParameters()
459,812✔
497
        return this.connection.driver.escapeQueryWithParameters(
459,812✔
498
            query,
499
            parameters,
500
            this.expressionMap.nativeParameters,
501
        )
502
    }
503

504
    /**
505
     * Executes sql generated by query builder and returns raw database results.
506
     */
507
    async execute(): Promise<any> {
508
        const [sql, parameters] = this.getQueryAndParameters()
35✔
509
        const queryRunner = this.obtainQueryRunner()
35✔
510
        try {
35✔
511
            return await queryRunner.query(sql, parameters) // await is needed here because we are using finally
35✔
512
        } finally {
513
            if (queryRunner !== this.queryRunner) {
35✔
514
                // means we created our own query runner
515
                await queryRunner.release()
35✔
516
            }
517
        }
518
    }
519

520
    /**
521
     * Creates a completely new query builder.
522
     * Uses same query runner as current QueryBuilder.
523
     */
524
    createQueryBuilder(queryRunner?: QueryRunner): this {
525
        return new (this.constructor as any)(
47,426✔
526
            this.connection,
527
            queryRunner ?? this.queryRunner,
94,837✔
528
        )
529
    }
530

531
    /**
532
     * Clones query builder as it is.
533
     * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
534
     * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
535
     * where queryBuilder is cloned QueryBuilder.
536
     */
537
    clone(): this {
538
        return new (this.constructor as any)(this)
16,574✔
539
    }
540

541
    /**
542
     * Includes a Query comment in the query builder.  This is helpful for debugging purposes,
543
     * such as finding a specific query in the database server's logs, or for categorization using
544
     * an APM product.
545
     */
546
    comment(comment: string): this {
547
        this.expressionMap.comment = comment
264✔
548
        return this
264✔
549
    }
550

551
    /**
552
     * Disables escaping.
553
     */
554
    disableEscaping(): this {
555
        this.expressionMap.disableEscaping = false
92✔
556
        return this
92✔
557
    }
558

559
    /**
560
     * Escapes table name, column name or alias name using current database's escaping character.
561
     */
562
    escape(name: string): string {
563
        if (!this.expressionMap.disableEscaping) return name
49,437,847✔
564
        return this.connection.driver.escape(name)
49,437,002✔
565
    }
566

567
    /**
568
     * Sets or overrides query builder's QueryRunner.
569
     */
570
    setQueryRunner(queryRunner: QueryRunner): this {
571
        this.queryRunner = queryRunner
12✔
572
        return this
12✔
573
    }
574

575
    /**
576
     * Indicates if listeners and subscribers must be called before and after query execution.
577
     * Enabled by default.
578
     */
579
    callListeners(enabled: boolean): this {
580
        this.expressionMap.callListeners = enabled
239,590✔
581
        return this
239,590✔
582
    }
583

584
    /**
585
     * If set to true the query will be wrapped into a transaction.
586
     */
587
    useTransaction(enabled: boolean): this {
588
        this.expressionMap.useTransaction = enabled
29✔
589
        return this
29✔
590
    }
591

592
    /**
593
     * Adds CTE to query
594
     */
595
    addCommonTableExpression(
596
        queryBuilder: QueryBuilder<any> | string,
597
        alias: string,
598
        options?: QueryBuilderCteOptions,
599
    ): this {
600
        this.expressionMap.commonTableExpressions.push({
128✔
601
            queryBuilder,
602
            alias,
603
            options: options || {},
134✔
604
        })
605
        return this
128✔
606
    }
607

608
    // -------------------------------------------------------------------------
609
    // Protected Methods
610
    // -------------------------------------------------------------------------
611

612
    /**
613
     * Gets escaped table name with schema name if SqlServer driver used with custom
614
     * schema name, otherwise returns escaped table name.
615
     */
616
    protected getTableName(tablePath: string): string {
617
        return tablePath
5,167,212✔
618
            .split(".")
619
            .map((i) => {
620
                // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
621
                if (i === "") return i
5,173,599✔
622
                return this.escape(i)
5,171,511✔
623
            })
624
            .join(".")
625
    }
626

627
    /**
628
     * Gets name of the table where insert should be performed.
629
     */
630
    protected getMainTableName(): string {
631
        if (!this.expressionMap.mainAlias)
483,711!
632
            throw new TypeORMError(
×
633
                `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`,
634
            )
635

636
        if (this.expressionMap.mainAlias.hasMetadata)
483,711✔
637
            return this.expressionMap.mainAlias.metadata.tablePath
478,115✔
638

639
        return this.expressionMap.mainAlias.tablePath!
5,596✔
640
    }
641

642
    /**
643
     * Specifies FROM which entity's table select/update/delete will be executed.
644
     * Also sets a main string alias of the selection data.
645
     */
646
    protected createFromAlias(
647
        entityTarget:
648
            | EntityTarget<any>
649
            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
650
        aliasName?: string,
651
    ): Alias {
652
        // if table has a metadata then find it to properly escape its properties
653
        // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
654
        if (this.connection.hasMetadata(entityTarget)) {
788,129✔
655
            const metadata = this.connection.getMetadata(entityTarget)
773,425✔
656

657
            return this.expressionMap.createAlias({
773,425✔
658
                type: "from",
659
                name: aliasName,
660
                metadata: this.connection.getMetadata(entityTarget),
661
                tablePath: metadata.tablePath,
662
            })
663
        } else {
664
            if (typeof entityTarget === "string") {
14,704✔
665
                const isSubquery =
666
                    entityTarget.substr(0, 1) === "(" &&
14,617✔
667
                    entityTarget.substr(-1) === ")"
668

669
                return this.expressionMap.createAlias({
14,617✔
670
                    type: "from",
671
                    name: aliasName,
672
                    tablePath: !isSubquery
14,617✔
673
                        ? (entityTarget as string)
674
                        : undefined,
675
                    subQuery: isSubquery ? entityTarget : undefined,
14,617✔
676
                })
677
            }
678

679
            const subQueryBuilder: SelectQueryBuilder<any> = (
680
                entityTarget as any
87✔
681
            )((this as any as SelectQueryBuilder<any>).subQuery())
682
            this.setParameters(subQueryBuilder.getParameters())
87✔
683
            const subquery = subQueryBuilder.getQuery()
87✔
684

685
            return this.expressionMap.createAlias({
87✔
686
                type: "from",
687
                name: aliasName,
688
                subQuery: subquery,
689
            })
690
        }
691
    }
692

693
    /**
694
     * @deprecated this way of replace property names is too slow.
695
     *  Instead, we'll replace property names at the end - once query is build.
696
     */
697
    protected replacePropertyNames(statement: string) {
698
        return statement
4,980,980✔
699
    }
700

701
    /**
702
     * Replaces all entity's propertyName to name in the given SQL string.
703
     */
704
    protected replacePropertyNamesForTheWholeQuery(statement: string) {
705
        const replacements: { [key: string]: { [key: string]: string } } = {}
791,937✔
706

707
        for (const alias of this.expressionMap.aliases) {
791,937✔
708
            if (!alias.hasMetadata) continue
5,195,679✔
709
            const replaceAliasNamePrefix =
710
                this.expressionMap.aliasNamePrefixingEnabled && alias.name
5,179,301✔
711
                    ? `${alias.name}.`
712
                    : ""
713

714
            if (!replacements[replaceAliasNamePrefix]) {
5,179,301✔
715
                replacements[replaceAliasNamePrefix] = {}
5,178,392✔
716
            }
717

718
            // Insert & overwrite the replacements from least to most relevant in our replacements object.
719
            // To do this we iterate and overwrite in the order of relevance.
720
            // Least to Most Relevant:
721
            // * Relation Property Path to first join column key
722
            // * Relation Property Path + Column Path
723
            // * Column Database Name
724
            // * Column Property Name
725
            // * Column Property Path
726

727
            for (const relation of alias.metadata.relations) {
5,179,301✔
728
                if (relation.joinColumns.length > 0)
1,268,762✔
729
                    replacements[replaceAliasNamePrefix][
833,719✔
730
                        relation.propertyPath
731
                    ] = relation.joinColumns[0].databaseName
732
            }
733

734
            for (const relation of alias.metadata.relations) {
5,179,301✔
735
                const allColumns = [
1,268,762✔
736
                    ...relation.joinColumns,
737
                    ...relation.inverseJoinColumns,
738
                ]
739
                for (const joinColumn of allColumns) {
1,268,762✔
740
                    const propertyKey = `${relation.propertyPath}.${
1,272,749✔
741
                        joinColumn.referencedColumn!.propertyPath
742
                    }`
743
                    replacements[replaceAliasNamePrefix][propertyKey] =
1,272,749✔
744
                        joinColumn.databaseName
745
                }
746
            }
747

748
            for (const column of alias.metadata.columns) {
5,179,301✔
749
                replacements[replaceAliasNamePrefix][column.databaseName] =
13,518,077✔
750
                    column.databaseName
751
            }
752

753
            for (const column of alias.metadata.columns) {
5,179,301✔
754
                replacements[replaceAliasNamePrefix][column.propertyName] =
13,518,077✔
755
                    column.databaseName
756
            }
757

758
            for (const column of alias.metadata.columns) {
5,179,301✔
759
                replacements[replaceAliasNamePrefix][column.propertyPath] =
13,518,077✔
760
                    column.databaseName
761
            }
762
        }
763

764
        const replacementKeys = Object.keys(replacements)
791,937✔
765
        const replaceAliasNamePrefixes = replacementKeys
791,937✔
766
            .map((key) => escapeRegExp(key))
5,178,392✔
767
            .join("|")
768

769
        if (replacementKeys.length > 0) {
791,937✔
770
            statement = statement.replace(
777,250✔
771
                new RegExp(
772
                    // Avoid a lookbehind here since it's not well supported
773
                    `([ =(]|^.{0})` + // any of ' =(' or start of line
774
                        // followed by our prefix, e.g. 'tablename.' or ''
775
                        `${
776
                            replaceAliasNamePrefixes
777,250✔
777
                                ? "(" + replaceAliasNamePrefixes + ")"
778
                                : ""
779
                        }([^ =(),]+)` + // a possible property name: sequence of anything but ' =(),'
780
                        // terminated by ' =),' or end of line
781
                        `(?=[ =),]|.{0}$)`,
782
                    "gm",
783
                ),
784
                (...matches) => {
785
                    let match: string, pre: string, p: string
786
                    if (replaceAliasNamePrefixes) {
9,606,132✔
787
                        match = matches[0]
9,366,603✔
788
                        pre = matches[1]
9,366,603✔
789
                        p = matches[3]
9,366,603✔
790

791
                        if (replacements[matches[2]][p]) {
9,366,603✔
792
                            return `${pre}${this.escape(
9,366,603✔
793
                                matches[2].substring(0, matches[2].length - 1),
794
                            )}.${this.escape(replacements[matches[2]][p])}`
795
                        }
796
                    } else {
797
                        match = matches[0]
239,529✔
798
                        pre = matches[1]
239,529✔
799
                        p = matches[2]
239,529✔
800

801
                        if (replacements[""][p]) {
239,529✔
802
                            return `${pre}${this.escape(replacements[""][p])}`
33,007✔
803
                        }
804
                    }
805
                    return match
206,522✔
806
                },
807
            )
808
        }
809

810
        return statement
791,937✔
811
    }
812

813
    protected createComment(): string {
814
        if (!this.expressionMap.comment) {
790,896✔
815
            return ""
790,664✔
816
        }
817

818
        // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
819
        // In some dialects query nesting is available - but not all.  Because of this, we'll need
820
        // to scrub "ending" characters from the SQL but otherwise we can leave everything else
821
        // as-is and it should be valid.
822

823
        return `/* ${this.expressionMap.comment.replace(/\*\//g, "")} */ `
232✔
824
    }
825

826
    /**
827
     * Time travel queries for CockroachDB
828
     */
829
    protected createTimeTravelQuery(): string {
830
        if (
563,124✔
831
            this.expressionMap.queryType === "select" &&
1,100,511✔
832
            this.expressionMap.timeTravel
833
        ) {
834
            return ` AS OF SYSTEM TIME ${this.expressionMap.timeTravel}`
18✔
835
        }
836

837
        return ""
563,106✔
838
    }
839

840
    /**
841
     * Creates "WHERE" expression.
842
     */
843
    protected createWhereExpression() {
844
        const conditionsArray = []
563,124✔
845

846
        const whereExpression = this.createWhereClausesExpression(
563,124✔
847
            this.expressionMap.wheres,
848
        )
849

850
        if (whereExpression.length > 0 && whereExpression !== "1=1") {
563,124✔
851
            conditionsArray.push(this.replacePropertyNames(whereExpression))
535,770✔
852
        }
853

854
        if (this.expressionMap.mainAlias!.hasMetadata) {
563,124✔
855
            const metadata = this.expressionMap.mainAlias!.metadata
550,415✔
856
            // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
857
            if (
550,415✔
858
                this.expressionMap.queryType === "select" &&
1,480,289✔
859
                !this.expressionMap.withDeleted &&
860
                metadata.deleteDateColumn
861
            ) {
862
                const column = this.expressionMap.aliasNamePrefixingEnabled
1,672!
863
                    ? this.expressionMap.mainAlias!.name +
864
                      "." +
865
                      metadata.deleteDateColumn.propertyName
866
                    : metadata.deleteDateColumn.propertyName
867

868
                const condition = `${this.replacePropertyNames(column)} IS NULL`
1,672✔
869
                conditionsArray.push(condition)
1,672✔
870
            }
871

872
            if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
550,415✔
873
                const column = this.expressionMap.aliasNamePrefixingEnabled
1,465✔
874
                    ? this.expressionMap.mainAlias!.name +
875
                      "." +
876
                      metadata.discriminatorColumn.databaseName
877
                    : metadata.discriminatorColumn.databaseName
878

879
                const condition = `${this.replacePropertyNames(
1,465✔
880
                    column,
881
                )} IN (:...discriminatorColumnValues)`
882
                conditionsArray.push(condition)
1,465✔
883
            }
884
        }
885

886
        if (this.expressionMap.extraAppendedAndWhereCondition) {
563,124✔
887
            const condition = this.replacePropertyNames(
7,390✔
888
                this.expressionMap.extraAppendedAndWhereCondition,
889
            )
890
            conditionsArray.push(condition)
7,390✔
891
        }
892

893
        let condition = ""
563,124✔
894

895
        // time travel
896
        condition += this.createTimeTravelQuery()
563,124✔
897

898
        if (!conditionsArray.length) {
563,124✔
899
            condition += ""
26,405✔
900
        } else if (conditionsArray.length === 1) {
536,719✔
901
            condition += ` WHERE ${conditionsArray[0]}`
527,251✔
902
        } else {
903
            condition += ` WHERE ( ${conditionsArray.join(" ) AND ( ")} )`
9,468✔
904
        }
905

906
        return condition
563,124✔
907
    }
908

909
    /**
910
     * Creates "RETURNING" / "OUTPUT" expression.
911
     */
912
    protected createReturningExpression(returningType: ReturningType): string {
913
        const columns = this.getReturningColumns()
254,714✔
914
        const driver = this.connection.driver
254,714✔
915

916
        // also add columns we must auto-return to perform entity updation
917
        // if user gave his own returning
918
        if (
254,714✔
919
            typeof this.expressionMap.returning !== "string" &&
599,409✔
920
            this.expressionMap.extraReturningColumns.length > 0 &&
921
            driver.isReturningSqlSupported(returningType)
922
        ) {
923
            columns.push(
55,016✔
924
                ...this.expressionMap.extraReturningColumns.filter((column) => {
925
                    return columns.indexOf(column) === -1
69,404✔
926
                }),
927
            )
928
        }
929

930
        if (columns.length) {
254,714✔
931
            let columnsExpression = columns
55,034✔
932
                .map((column) => {
933
                    const name = this.escape(column.databaseName)
69,452✔
934
                    if (driver.options.type === "mssql") {
69,452✔
935
                        if (
30,726!
936
                            this.expressionMap.queryType === "insert" ||
31,464✔
937
                            this.expressionMap.queryType === "update" ||
938
                            this.expressionMap.queryType === "soft-delete" ||
939
                            this.expressionMap.queryType === "restore"
940
                        ) {
941
                            return "INSERTED." + name
30,726✔
942
                        } else {
943
                            return (
×
944
                                this.escape(this.getMainTableName()) +
945
                                "." +
946
                                name
947
                            )
948
                        }
949
                    } else {
950
                        return name
38,726✔
951
                    }
952
                })
953
                .join(", ")
954

955
            if (driver.options.type === "oracle") {
55,034✔
956
                columnsExpression +=
6,686✔
957
                    " INTO " +
958
                    columns
959
                        .map((column) => {
960
                            return this.createParameter({
7,976✔
961
                                type: (
962
                                    driver as OracleDriver
963
                                ).columnTypeToNativeParameter(column.type),
964
                                dir: (driver as OracleDriver).oracle.BIND_OUT,
965
                            })
966
                        })
967
                        .join(", ")
968
            }
969

970
            if (driver.options.type === "mssql") {
55,034✔
971
                if (
24,066✔
972
                    this.expressionMap.queryType === "insert" ||
24,516✔
973
                    this.expressionMap.queryType === "update"
974
                ) {
975
                    columnsExpression += " INTO @OutputTable"
23,904✔
976
                }
977
            }
978

979
            return columnsExpression
55,034✔
980
        } else if (typeof this.expressionMap.returning === "string") {
199,680✔
981
            return this.expressionMap.returning
105✔
982
        }
983

984
        return ""
199,575✔
985
    }
986

987
    /**
988
     * If returning / output cause is set to array of column names,
989
     * then this method will return all column metadatas of those column names.
990
     */
991
    protected getReturningColumns(): ColumnMetadata[] {
992
        const columns: ColumnMetadata[] = []
254,714✔
993
        if (Array.isArray(this.expressionMap.returning)) {
254,714✔
994
            ;(this.expressionMap.returning as string[]).forEach(
30✔
995
                (columnName) => {
996
                    if (this.expressionMap.mainAlias!.hasMetadata) {
51✔
997
                        columns.push(
51✔
998
                            ...this.expressionMap.mainAlias!.metadata.findColumnsWithPropertyPath(
999
                                columnName,
1000
                            ),
1001
                        )
1002
                    }
1003
                },
1004
            )
1005
        }
1006
        return columns
254,714✔
1007
    }
1008

1009
    protected createWhereClausesExpression(clauses: WhereClause[]): string {
1010
        return clauses
766,055✔
1011
            .map((clause, index) => {
1012
                const expression = this.createWhereConditionExpression(
775,726✔
1013
                    clause.condition,
1014
                )
1015

1016
                switch (clause.type) {
775,726✔
1017
                    case "and":
1018
                        return (
255,351✔
1019
                            (index > 0 ? "AND " : "") +
255,351✔
1020
                            `${
1021
                                this.connection.options.isolateWhereStatements
255,351!
1022
                                    ? "("
1023
                                    : ""
1024
                            }${expression}${
1025
                                this.connection.options.isolateWhereStatements
255,351!
1026
                                    ? ")"
1027
                                    : ""
1028
                            }`
1029
                        )
1030
                    case "or":
1031
                        return (
26,454✔
1032
                            (index > 0 ? "OR " : "") +
26,454✔
1033
                            `${
1034
                                this.connection.options.isolateWhereStatements
26,454!
1035
                                    ? "("
1036
                                    : ""
1037
                            }${expression}${
1038
                                this.connection.options.isolateWhereStatements
26,454!
1039
                                    ? ")"
1040
                                    : ""
1041
                            }`
1042
                        )
1043
                }
1044

1045
                return expression
493,921✔
1046
            })
1047
            .join(" ")
1048
            .trim()
1049
    }
1050

1051
    /**
1052
     * Computes given where argument - transforms to a where string all forms it can take.
1053
     */
1054
    protected createWhereConditionExpression(
1055
        condition: WhereClauseCondition,
1056
        alwaysWrap: boolean = false,
826,182✔
1057
    ): string {
1058
        if (typeof condition === "string") return condition
868,463✔
1059

1060
        if (Array.isArray(condition)) {
481,879✔
1061
            if (condition.length === 0) {
202,931!
1062
                return "1=1"
×
1063
            }
1064

1065
            // In the future we should probably remove this entire condition
1066
            // but for now to prevent any breaking changes it exists.
1067
            if (condition.length === 1 && !alwaysWrap) {
202,931✔
1068
                return this.createWhereClausesExpression(condition)
139,135✔
1069
            }
1070

1071
            return "(" + this.createWhereClausesExpression(condition) + ")"
63,796✔
1072
        }
1073

1074
        const { driver } = this.connection
278,948✔
1075

1076
        switch (condition.operator) {
278,948✔
1077
            case "lessThan":
1078
                return `${condition.parameters[0]} < ${condition.parameters[1]}`
209✔
1079
            case "lessThanOrEqual":
1080
                return `${condition.parameters[0]} <= ${condition.parameters[1]}`
58✔
1081
            case "arrayContains":
1082
                return `${condition.parameters[0]} @> ${condition.parameters[1]}`
24✔
1083
            case "jsonContains":
1084
                return `${condition.parameters[0]} ::jsonb @> ${condition.parameters[1]}`
15✔
1085
            case "arrayContainedBy":
1086
                return `${condition.parameters[0]} <@ ${condition.parameters[1]}`
24✔
1087
            case "arrayOverlap":
1088
                return `${condition.parameters[0]} && ${condition.parameters[1]}`
12✔
1089
            case "moreThan":
1090
                return `${condition.parameters[0]} > ${condition.parameters[1]}`
76✔
1091
            case "moreThanOrEqual":
1092
                return `${condition.parameters[0]} >= ${condition.parameters[1]}`
58✔
1093
            case "notEqual":
1094
                return `${condition.parameters[0]} != ${condition.parameters[1]}`
87✔
1095
            case "equal":
1096
                return `${condition.parameters[0]} = ${condition.parameters[1]}`
118,724✔
1097
            case "ilike":
1098
                if (
64✔
1099
                    driver.options.type === "postgres" ||
119✔
1100
                    driver.options.type === "cockroachdb"
1101
                ) {
1102
                    return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`
15✔
1103
                }
1104

1105
                return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`
49✔
1106
            case "like":
1107
                return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`
94✔
1108
            case "between":
1109
                return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`
174✔
1110
            case "in":
1111
                if (condition.parameters.length <= 1) {
116,391✔
1112
                    return "0=1"
58✔
1113
                }
1114
                return `${condition.parameters[0]} IN (${condition.parameters
116,333✔
1115
                    .slice(1)
1116
                    .join(", ")})`
1117
            case "any":
1118
                if (driver.options.type === "cockroachdb") {
6!
1119
                    return `${condition.parameters[0]}::STRING = ANY(${condition.parameters[1]}::STRING[])`
×
1120
                }
1121

1122
                return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`
6✔
1123
            case "isNull":
1124
                return `${condition.parameters[0]} IS NULL`
215✔
1125

1126
            case "not":
1127
                return `NOT(${this.createWhereConditionExpression(
424✔
1128
                    condition.condition,
1129
                )})`
1130
            case "brackets":
1131
                return `${this.createWhereConditionExpression(
42,281✔
1132
                    condition.condition,
1133
                    true,
1134
                )}`
1135
            case "and":
1136
                return "(" + condition.parameters.join(" AND ") + ")"
6✔
1137
            case "or":
1138
                return "(" + condition.parameters.join(" OR ") + ")"
6✔
1139
        }
1140

1141
        throw new TypeError(
×
1142
            `Unsupported FindOperator ${FindOperator.constructor.name}`,
1143
        )
1144
    }
1145

1146
    protected createCteExpression(): string {
1147
        if (!this.hasCommonTableExpressions()) {
792,227✔
1148
            return ""
792,081✔
1149
        }
1150
        const databaseRequireRecusiveHint =
1151
            this.connection.driver.cteCapabilities.requiresRecursiveHint
146✔
1152

1153
        const cteStrings = this.expressionMap.commonTableExpressions.map(
146✔
1154
            (cte) => {
1155
                let cteBodyExpression = typeof cte.queryBuilder === 'string' ? cte.queryBuilder : '';
146✔
1156
                if (typeof cte.queryBuilder !== "string") {
146✔
1157
                    if (cte.queryBuilder.hasCommonTableExpressions()) {
94!
1158
                        throw new TypeORMError(
×
1159
                            `Nested CTEs aren't supported (CTE: ${cte.alias})`,
1160
                        )
1161
                    }
1162
                    cteBodyExpression = cte.queryBuilder.getQuery()
94✔
1163
                    if (
94!
1164
                        !this.connection.driver.cteCapabilities.writable &&
134✔
1165
                        !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
1166
                    ) {
1167
                        throw new TypeORMError(
×
1168
                            `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`,
1169
                        )
1170
                    }
1171
                    this.setParameters(cte.queryBuilder.getParameters())
94✔
1172
                }
1173
                let cteHeader = this.escape(cte.alias)
146✔
1174
                if (cte.options.columnNames) {
146✔
1175
                    const escapedColumnNames = cte.options.columnNames.map(
140✔
1176
                        (column) => this.escape(column),
140✔
1177
                    )
1178
                    if (
140✔
1179
                        InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
1180
                    ) {
1181
                        if (
88!
1182
                            cte.queryBuilder.expressionMap.selects.length &&
176✔
1183
                            cte.options.columnNames.length !==
1184
                                cte.queryBuilder.expressionMap.selects.length
1185
                        ) {
1186
                            throw new TypeORMError(
×
1187
                                `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`,
1188
                            )
1189
                        }
1190
                    }
1191
                    cteHeader += `(${escapedColumnNames.join(", ")})`
140✔
1192
                }
1193
                const recursiveClause =
1194
                    cte.options.recursive && databaseRequireRecusiveHint
146✔
1195
                        ? "RECURSIVE"
1196
                        : ""
1197
                let materializeClause = ""
146✔
1198
                if (
146✔
1199
                    this.connection.driver.cteCapabilities.materializedHint &&
212✔
1200
                    cte.options.materialized !== undefined
1201
                ) {
1202
                    materializeClause = cte.options.materialized
24✔
1203
                        ? "MATERIALIZED"
1204
                        : "NOT MATERIALIZED"
1205
                }
1206

1207
                return [
146✔
1208
                    recursiveClause,
1209
                    cteHeader,
1210
                    "AS",
1211
                    materializeClause,
1212
                    `(${cteBodyExpression})`,
1213
                ]
1214
                    .filter(Boolean)
1215
                    .join(" ")
1216
            },
1217
        )
1218

1219
        return "WITH " + cteStrings.join(", ") + " "
146✔
1220
    }
1221

1222
    /**
1223
     * Creates "WHERE" condition for an in-ids condition.
1224
     */
1225
    protected getWhereInIdsCondition(
1226
        ids: any | any[],
1227
    ): ObjectLiteral | Brackets {
1228
        const metadata = this.expressionMap.mainAlias!.metadata
132,576✔
1229
        const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
132,576✔
1230
            metadata.ensureEntityIdMap(id),
167,790✔
1231
        )
1232

1233
        // using in(...ids) for single primary key entities
1234
        if (!metadata.hasMultiplePrimaryKeys) {
132,576✔
1235
            const primaryColumn = metadata.primaryColumns[0]
116,712✔
1236

1237
            // getEntityValue will try to transform `In`, it is a bug
1238
            // todo: remove this transformer check after #2390 is fixed
1239
            // This also fails for embedded & relation, so until that is fixed skip it.
1240
            if (
116,712✔
1241
                !primaryColumn.transformer &&
349,836✔
1242
                !primaryColumn.relationMetadata &&
1243
                !primaryColumn.embeddedMetadata
1244
            ) {
1245
                return {
116,066✔
1246
                    [primaryColumn.propertyName]: In(
1247
                        normalized.map((id) =>
1248
                            primaryColumn.getEntityValue(id, false),
150,508✔
1249
                        ),
1250
                    ),
1251
                }
1252
            }
1253
        }
1254

1255
        return new Brackets((qb) => {
16,510✔
1256
            for (const data of normalized) {
16,510✔
1257
                qb.orWhere(new Brackets((qb) => qb.where(data)))
17,282✔
1258
            }
1259
        })
1260
    }
1261

1262
    protected getExistsCondition(subQuery: any): [string, any[]] {
1263
        const query = subQuery
203✔
1264
            .clone()
1265
            .orderBy()
1266
            .groupBy()
1267
            .offset(undefined)
1268
            .limit(undefined)
1269
            .skip(undefined)
1270
            .take(undefined)
1271
            .select("1")
1272
            .setOption("disable-global-order")
1273

1274
        return [`EXISTS (${query.getQuery()})`, query.getParameters()]
203✔
1275
    }
1276

1277
    private findColumnsForPropertyPath(
1278
        propertyPath: string,
1279
    ): [Alias, string[], ColumnMetadata[]] {
1280
        // Make a helper to iterate the entity & relations?
1281
        // Use that to set the correct alias?  Or the other way around?
1282

1283
        // Start with the main alias with our property paths
1284
        let alias = this.expressionMap.mainAlias
186,701✔
1285
        const root: string[] = []
186,701✔
1286
        const propertyPathParts = propertyPath.split(".")
186,701✔
1287

1288
        while (propertyPathParts.length > 1) {
186,701✔
1289
            const part = propertyPathParts[0]
6,452✔
1290

1291
            if (!alias?.hasMetadata) {
6,452!
1292
                // If there's no metadata, we're wasting our time
1293
                // and can't actually look any of this up.
1294
                break
×
1295
            }
1296

1297
            if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
6,452✔
1298
                // If this is an embedded then we should combine the two as part of our lookup.
1299
                // Instead of just breaking, we keep going with this in case there's an embedded/relation
1300
                // inside an embedded.
1301
                propertyPathParts.unshift(
6,452✔
1302
                    `${propertyPathParts.shift()}.${propertyPathParts.shift()}`,
1303
                )
1304
                continue
6,452✔
1305
            }
1306

1307
            if (alias.metadata.hasRelationWithPropertyPath(part)) {
×
1308
                // If this is a relation then we should find the aliases
1309
                // that match the relation & then continue further down
1310
                // the property path
1311
                const joinAttr = this.expressionMap.joinAttributes.find(
×
1312
                    (joinAttr) => joinAttr.relationPropertyPath === part,
×
1313
                )
1314

1315
                if (!joinAttr?.alias) {
×
1316
                    const fullRelationPath =
1317
                        root.length > 0 ? `${root.join(".")}.${part}` : part
×
1318
                    throw new Error(
×
1319
                        `Cannot find alias for relation at ${fullRelationPath}`,
1320
                    )
1321
                }
1322

1323
                alias = joinAttr.alias
×
1324
                root.push(...part.split("."))
×
1325
                propertyPathParts.shift()
×
1326
                continue
×
1327
            }
1328

1329
            break
×
1330
        }
1331

1332
        if (!alias) {
186,701!
1333
            throw new Error(`Cannot find alias for property ${propertyPath}`)
×
1334
        }
1335

1336
        // Remaining parts are combined back and used to find the actual property path
1337
        const aliasPropertyPath = propertyPathParts.join(".")
186,701✔
1338

1339
        const columns =
1340
            alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath)
186,701✔
1341

1342
        if (!columns.length) {
186,701✔
1343
            throw new EntityPropertyNotFoundError(propertyPath, alias.metadata)
116✔
1344
        }
1345

1346
        return [alias, root, columns]
186,585✔
1347
    }
1348

1349
    /**
1350
     * Creates a property paths for a given ObjectLiteral.
1351
     */
1352
    protected createPropertyPath(
1353
        metadata: EntityMetadata,
1354
        entity: ObjectLiteral,
1355
        prefix: string = "",
180,533✔
1356
    ) {
1357
        const paths: string[] = []
186,817✔
1358

1359
        for (const key of Object.keys(entity)) {
186,817✔
1360
            const path = prefix ? `${prefix}.${key}` : key
214,364✔
1361

1362
            // There's times where we don't actually want to traverse deeper.
1363
            // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
1364
            if (
214,364✔
1365
                entity[key] === null ||
559,474✔
1366
                typeof entity[key] !== "object" ||
1367
                InstanceChecker.isFindOperator(entity[key])
1368
            ) {
1369
                paths.push(path)
198,079✔
1370
                continue
198,079✔
1371
            }
1372

1373
            if (metadata.hasEmbeddedWithPropertyPath(path)) {
16,285✔
1374
                const subPaths = this.createPropertyPath(
6,284✔
1375
                    metadata,
1376
                    entity[key],
1377
                    path,
1378
                )
1379
                paths.push(...subPaths)
6,284✔
1380
                continue
6,284✔
1381
            }
1382

1383
            if (metadata.hasRelationWithPropertyPath(path)) {
10,001✔
1384
                const relation = metadata.findRelationWithPropertyPath(path)!
8,721✔
1385

1386
                // There's also cases where we don't want to return back all of the properties.
1387
                // These handles the situation where someone passes the model & we don't need to make
1388
                // a HUGE `where` to uniquely look up the entity.
1389

1390
                // In the case of a *-to-one, there's only ever one possible entity on the other side
1391
                // so if the join columns are all defined we can return just the relation itself
1392
                // because it will fetch only the join columns and do the lookup.
1393
                if (
8,721✔
1394
                    relation.relationType === "one-to-one" ||
16,376✔
1395
                    relation.relationType === "many-to-one"
1396
                ) {
1397
                    const joinColumns = relation.joinColumns
8,721✔
1398
                        .map((j) => j.referencedColumn)
11,104✔
1399
                        .filter((j): j is ColumnMetadata => !!j)
11,104✔
1400

1401
                    const hasAllJoinColumns =
1402
                        joinColumns.length > 0 &&
8,721✔
1403
                        joinColumns.every((column) =>
1404
                            column.getEntityValue(entity[key], false),
11,104✔
1405
                        )
1406

1407
                    if (hasAllJoinColumns) {
8,721✔
1408
                        paths.push(path)
8,518✔
1409
                        continue
8,518✔
1410
                    }
1411
                }
1412

1413
                if (
203!
1414
                    relation.relationType === "one-to-many" ||
406✔
1415
                    relation.relationType === "many-to-many"
1416
                ) {
1417
                    throw new Error(
×
1418
                        `Cannot query across ${relation.relationType} for property ${path}`,
1419
                    )
1420
                }
1421

1422
                // For any other case, if the `entity[key]` contains all of the primary keys we can do a
1423
                // lookup via these.  We don't need to look up via any other values 'cause these are
1424
                // the unique primary keys.
1425
                // This handles the situation where someone passes the model & we don't need to make
1426
                // a HUGE where.
1427
                const primaryColumns =
1428
                    relation.inverseEntityMetadata.primaryColumns
203✔
1429
                const hasAllPrimaryKeys =
1430
                    primaryColumns.length > 0 &&
203✔
1431
                    primaryColumns.every((column) =>
1432
                        column.getEntityValue(entity[key], false),
203✔
1433
                    )
1434

1435
                if (hasAllPrimaryKeys) {
203!
1436
                    const subPaths = primaryColumns.map(
×
1437
                        (column) => `${path}.${column.propertyPath}`,
×
1438
                    )
1439
                    paths.push(...subPaths)
×
1440
                    continue
×
1441
                }
1442

1443
                // If nothing else, just return every property that's being passed to us.
1444
                const subPaths = this.createPropertyPath(
203✔
1445
                    relation.inverseEntityMetadata,
1446
                    entity[key],
1447
                ).map((p) => `${path}.${p}`)
203✔
1448
                paths.push(...subPaths)
203✔
1449
                continue
203✔
1450
            }
1451

1452
            paths.push(path)
1,280✔
1453
        }
1454

1455
        return paths
186,817✔
1456
    }
1457

1458
    protected *getPredicates(where: ObjectLiteral) {
1459
        if (this.expressionMap.mainAlias!.hasMetadata) {
160,669!
1460
            const propertyPaths = this.createPropertyPath(
160,669✔
1461
                this.expressionMap.mainAlias!.metadata,
1462
                where,
1463
            )
1464

1465
            for (const propertyPath of propertyPaths) {
160,669✔
1466
                const [alias, aliasPropertyPath, columns] =
1467
                    this.findColumnsForPropertyPath(propertyPath)
186,701✔
1468

1469
                for (const column of columns) {
186,585✔
1470
                    let containedWhere = where
186,585✔
1471

1472
                    for (const part of aliasPropertyPath) {
186,585✔
1473
                        if (!containedWhere || !(part in containedWhere)) {
×
1474
                            containedWhere = {}
×
1475
                            break
×
1476
                        }
1477

1478
                        containedWhere = containedWhere[part]
×
1479
                    }
1480

1481
                    // Use the correct alias & the property path from the column
1482
                    const aliasPath = this.expressionMap
186,585✔
1483
                        .aliasNamePrefixingEnabled
1484
                        ? `${alias.name}.${column.propertyPath}`
1485
                        : column.propertyPath
1486

1487
                    const parameterValue = column.getEntityValue(
186,585✔
1488
                        containedWhere,
1489
                        true,
1490
                    )
1491

1492
                    yield [aliasPath, parameterValue]
186,585✔
1493
                }
1494
            }
1495
        } else {
1496
            for (const key of Object.keys(where)) {
×
1497
                const parameterValue = where[key]
×
1498
                const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
×
1499
                    ? `${this.alias}.${key}`
1500
                    : key
1501

1502
                yield [aliasPath, parameterValue]
×
1503
            }
1504
        }
1505
    }
1506

1507
    protected getWherePredicateCondition(
1508
        aliasPath: string,
1509
        parameterValue: any,
1510
    ): WhereClauseCondition {
1511
        if (InstanceChecker.isFindOperator(parameterValue)) {
237,041✔
1512
            let parameters: any[] = []
118,384✔
1513
            if (parameterValue.useParameter) {
118,384✔
1514
                if (parameterValue.objectLiteralParameters) {
118,099✔
1515
                    this.setParameters(parameterValue.objectLiteralParameters)
203✔
1516
                } else if (parameterValue.multipleParameters) {
117,896✔
1517
                    for (const v of parameterValue.value) {
116,928✔
1518
                        parameters.push(this.createParameter(v))
152,021✔
1519
                    }
1520
                } else {
1521
                    parameters.push(this.createParameter(parameterValue.value))
968✔
1522
                }
1523
            }
1524

1525
            if (parameterValue.type === "raw") {
118,384✔
1526
                if (parameterValue.getSql) {
261✔
1527
                    return parameterValue.getSql(aliasPath)
232✔
1528
                } else {
1529
                    return {
29✔
1530
                        operator: "equal",
1531
                        parameters: [aliasPath, parameterValue.value],
1532
                    }
1533
                }
1534
            } else if (parameterValue.type === "not") {
118,123✔
1535
                if (parameterValue.child) {
511✔
1536
                    return {
424✔
1537
                        operator: parameterValue.type,
1538
                        condition: this.getWherePredicateCondition(
1539
                            aliasPath,
1540
                            parameterValue.child,
1541
                        ),
1542
                    }
1543
                } else {
1544
                    return {
87✔
1545
                        operator: "notEqual",
1546
                        parameters: [aliasPath, ...parameters],
1547
                    }
1548
                }
1549
            } else if (parameterValue.type === "and") {
117,612✔
1550
                const values: FindOperator<any>[] = parameterValue.value
6✔
1551

1552
                return {
6✔
1553
                    operator: parameterValue.type,
1554
                    parameters: values.map((operator) =>
1555
                        this.createWhereConditionExpression(
18✔
1556
                            this.getWherePredicateCondition(
1557
                                aliasPath,
1558
                                operator,
1559
                            ),
1560
                        ),
1561
                    ),
1562
                }
1563
            } else if (parameterValue.type === "or") {
117,606✔
1564
                const values: FindOperator<any>[] = parameterValue.value
6✔
1565

1566
                return {
6✔
1567
                    operator: parameterValue.type,
1568
                    parameters: values.map((operator) =>
1569
                        this.createWhereConditionExpression(
12✔
1570
                            this.getWherePredicateCondition(
1571
                                aliasPath,
1572
                                operator,
1573
                            ),
1574
                        ),
1575
                    ),
1576
                }
1577
            } else {
1578
                return {
117,600✔
1579
                    operator: parameterValue.type,
1580
                    parameters: [aliasPath, ...parameters],
1581
                }
1582
            }
1583
            // } else if (parameterValue === null) {
1584
            //     return {
1585
            //         operator: "isNull",
1586
            //         parameters: [
1587
            //             aliasPath,
1588
            //         ]
1589
            //     };
1590
        } else {
1591
            return {
118,657✔
1592
                operator: "equal",
1593
                parameters: [aliasPath, this.createParameter(parameterValue)],
1594
            }
1595
        }
1596
    }
1597

1598
    protected getWhereCondition(
1599
        where:
1600
            | string
1601
            | ((qb: this) => string)
1602
            | Brackets
1603
            | NotBrackets
1604
            | ObjectLiteral
1605
            | ObjectLiteral[],
1606
    ): WhereClauseCondition {
1607
        if (typeof where === "string") {
582,023✔
1608
            return where
376,768✔
1609
        }
1610

1611
        if (InstanceChecker.isBrackets(where)) {
205,255✔
1612
            const whereQueryBuilder = this.createQueryBuilder()
42,281✔
1613

1614
            whereQueryBuilder.parentQueryBuilder = this
42,281✔
1615

1616
            whereQueryBuilder.expressionMap.mainAlias =
42,281✔
1617
                this.expressionMap.mainAlias
1618
            whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
42,281✔
1619
                this.expressionMap.aliasNamePrefixingEnabled
1620
            whereQueryBuilder.expressionMap.parameters =
42,281✔
1621
                this.expressionMap.parameters
1622
            whereQueryBuilder.expressionMap.nativeParameters =
42,281✔
1623
                this.expressionMap.nativeParameters
1624

1625
            whereQueryBuilder.expressionMap.wheres = []
42,281✔
1626

1627
            where.whereFactory(whereQueryBuilder as any)
42,281✔
1628

1629
            return {
42,281✔
1630
                operator: InstanceChecker.isNotBrackets(where)
42,281!
1631
                    ? "not"
1632
                    : "brackets",
1633
                condition: whereQueryBuilder.expressionMap.wheres,
1634
            }
1635
        }
1636

1637
        if (typeof where === "function") {
162,974✔
1638
            return where(this)
2,608✔
1639
        }
1640

1641
        const wheres: ObjectLiteral[] = Array.isArray(where) ? where : [where]
160,366✔
1642
        const clauses: WhereClause[] = []
160,366✔
1643

1644
        for (const where of wheres) {
160,366✔
1645
            const conditions: WhereClauseCondition = []
160,669✔
1646

1647
            // Filter the conditions and set up the parameter values
1648
            for (const [aliasPath, parameterValue] of this.getPredicates(
160,669✔
1649
                where,
1650
            )) {
1651
                conditions.push({
186,585✔
1652
                    type: "and",
1653
                    condition: this.getWherePredicateCondition(
1654
                        aliasPath,
1655
                        parameterValue,
1656
                    ),
1657
                })
1658
            }
1659

1660
            clauses.push({ type: "or", condition: conditions })
160,553✔
1661
        }
1662

1663
        if (clauses.length === 1) {
160,250✔
1664
            return clauses[0].condition
160,011✔
1665
        }
1666

1667
        return clauses
239✔
1668
    }
1669

1670
    /**
1671
     * Creates a query builder used to execute sql queries inside this query builder.
1672
     */
1673
    protected obtainQueryRunner() {
1674
        return this.queryRunner || this.connection.createQueryRunner()
252,101✔
1675
    }
1676

1677
    protected hasCommonTableExpressions(): boolean {
1678
        return this.expressionMap.commonTableExpressions.length > 0
792,321✔
1679
    }
1680
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc