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

typeorm / typeorm / 12875151876

20 Jan 2025 08:19PM UTC coverage: 72.366% (-0.007%) from 72.373%
12875151876

push

github

web-flow
chore: added --cache to prettier call (#10865)

8657 of 12650 branches covered (68.43%)

Branch coverage included in aggregate %.

17894 of 24040 relevant lines covered (74.43%)

118184.15 hits per line

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

90.24
/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"
25✔
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"
25✔
15
import { QueryDeepPartialEntity } from "./QueryPartialEntity"
16
import { EntityMetadata } from "../metadata/EntityMetadata"
17
import { ColumnMetadata } from "../metadata/ColumnMetadata"
18
import { FindOperator } from "../find-options/FindOperator"
25✔
19
import { In } from "../find-options/operator/In"
25✔
20
import { TypeORMError } from "../error"
25✔
21
import { WhereClause, WhereClauseCondition } from "./WhereClause"
22
import { NotBrackets } from "./NotBrackets"
23
import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundError"
25✔
24
import { ReturningType } from "../driver/Driver"
25
import { OracleDriver } from "../driver/oracle/OracleDriver"
26
import { InstanceChecker } from "../util/InstanceChecker"
25✔
27
import { escapeRegExp } from "../util/escapeRegExp"
25✔
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> {
25✔
48
    readonly "@instanceof" = Symbol.for("QueryBuilder")
968,873✔
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
968,873✔
82

83
    /**
84
     * Contains all registered query builder classes.
85
     */
86
    private static queryBuilderRegistry: Record<string, any> = {}
25✔
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)) {
968,873✔
110
            this.connection = connectionOrQueryBuilder
725,810✔
111
            this.queryRunner = queryRunner
725,810✔
112
            this.expressionMap = new QueryExpressionMap(this.connection)
725,810✔
113
        } else {
114
            this.connection = connectionOrQueryBuilder.connection
243,063✔
115
            this.queryRunner = connectionOrQueryBuilder.queryRunner
243,063✔
116
            this.expressionMap = connectionOrQueryBuilder.expressionMap.clone()
243,063✔
117
        }
118
    }
119

120
    static registerQueryBuilderClass(name: string, factory: any) {
121
        QueryBuilder.queryBuilderRegistry[name] = factory
75,684✔
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)
205,495!
142
            throw new TypeORMError(`Main alias is not set`) // todo: better exception
×
143

144
        return this.expressionMap.mainAlias.name
205,495✔
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"
256✔
181
        if (Array.isArray(selection)) {
256!
182
            this.expressionMap.selects = selection.map((selection) => ({
×
183
                selection: selection,
184
            }))
185
        } else if (selection) {
256✔
186
            this.expressionMap.selects = [
256✔
187
                { selection: selection, aliasName: selectionAliasName },
188
            ]
189
        }
190

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

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

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

202
        if (InstanceChecker.isInsertQueryBuilder(this)) return this as any
204,832!
203

204
        return QueryBuilder.queryBuilderRegistry["InsertQueryBuilder"](this)
204,832✔
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
16,716!
243
            ? maybeUpdateSet
244
            : (entityOrTableNameUpdateSet as ObjectLiteral | undefined)
245
        entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
16,716!
246
            entityOrTableNameUpdateSet,
247
        )
248
            ? entityOrTableNameUpdateSet.options.name
249
            : entityOrTableNameUpdateSet
250

251
        if (
16,716✔
252
            typeof entityOrTableNameUpdateSet === "function" ||
17,136✔
253
            typeof entityOrTableNameUpdateSet === "string"
254
        ) {
255
            const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet)
16,539✔
256
            this.expressionMap.setMainAlias(mainAlias)
16,539✔
257
        }
258

259
        this.expressionMap.queryType = "update"
16,716✔
260
        this.expressionMap.valuesSet = updateSet
16,716✔
261

262
        if (InstanceChecker.isUpdateQueryBuilder(this)) return this as any
16,716!
263

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

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

273
        if (InstanceChecker.isDeleteQueryBuilder(this)) return this as any
3,849!
274

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

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

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

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

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

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

291
        return QueryBuilder.queryBuilderRegistry["SoftDeleteQueryBuilder"](this)
275✔
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
1,734!
316
        const propertyPath =
317
            arguments.length === 2
1,734!
318
                ? (maybePropertyPath as string)
319
                : (entityTargetOrPropertyPath as string)
320

321
        this.expressionMap.queryType = "relation"
1,734✔
322
        this.expressionMap.relationPropertyPath = propertyPath
1,734✔
323

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

329
        if (InstanceChecker.isRelationQueryBuilder(this)) return this as any
1,734!
330

331
        return QueryBuilder.queryBuilderRegistry["RelationQueryBuilder"](this)
1,734✔
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 (
1,975,502✔
372
            this.parentQueryBuilder?.hasParameter(key) ||
3,946,868✔
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,018,292✔
384
            throw new TypeORMError(
25✔
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,018,267✔
390
            throw new TypeORMError(
12✔
391
                "QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.",
392
            )
393
        }
394

395
        if (this.parentQueryBuilder) {
2,018,255✔
396
            this.parentQueryBuilder.setParameter(key, value)
68,235✔
397
        }
398

399
        this.expressionMap.parameters[key] = value
2,018,255✔
400
        return this
2,018,255✔
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)) {
45,101✔
408
            this.setParameter(key, value)
48,800✔
409
        }
410

411
        return this
45,076✔
412
    }
413

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

417
        do {
1,900,064✔
418
            parameterName = `orm_param_${this.parameterIndex++}`
1,903,301✔
419
        } while (this.hasParameter(parameterName))
420

421
        this.setParameter(parameterName, value)
1,900,064✔
422

423
        return `:${parameterName}`
1,900,064✔
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) {
6,525!
434
            this.parentQueryBuilder.setNativeParameters(parameters)
×
435
        }
436

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

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

452
        // add discriminator column parameter if it exist
453
        if (
411,683✔
454
            this.expressionMap.mainAlias &&
823,366✔
455
            this.expressionMap.mainAlias.hasMetadata
456
        ) {
457
            const metadata = this.expressionMap.mainAlias!.metadata
399,244✔
458
            if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
399,244✔
459
                const values = metadata.childEntityMetadatas
2,650✔
460
                    .filter(
461
                        (childMetadata) => childMetadata.discriminatorColumn,
353✔
462
                    )
463
                    .map((childMetadata) => childMetadata.discriminatorValue)
353✔
464
                values.push(metadata.discriminatorValue)
2,650✔
465
                parameters["discriminatorColumnValues"] = values
2,650✔
466
            }
467
        }
468

469
        return parameters
411,683✔
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]
930✔
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()
404,941✔
496
        const parameters = this.getParameters()
404,529✔
497
        return this.connection.driver.escapeQueryWithParameters(
404,529✔
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()
31✔
509
        const queryRunner = this.obtainQueryRunner()
31✔
510
        try {
31✔
511
            return await queryRunner.query(sql, parameters) // await is needed here because we are using finally
31✔
512
        } finally {
513
            if (queryRunner !== this.queryRunner) {
31✔
514
                // means we created our own query runner
515
                await queryRunner.release()
31✔
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)(
39,037✔
526
            this.connection,
527
            queryRunner ?? this.queryRunner,
78,059✔
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)
14,364✔
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
228✔
548
        return this
228✔
549
    }
550

551
    /**
552
     * Disables escaping.
553
     */
554
    disableEscaping(): this {
555
        this.expressionMap.disableEscaping = false
112✔
556
        return this
112✔
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
43,753,944✔
564
        return this.connection.driver.escape(name)
43,752,352✔
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
213,502✔
581
        return this
213,502✔
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
25✔
589
        return this
25✔
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({
112✔
601
            queryBuilder,
602
            alias,
603
            options: options || {},
118✔
604
        })
605
        return this
112✔
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
4,503,821✔
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
4,506,707✔
622
                return this.escape(i)
4,506,243✔
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)
431,014!
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)
431,014✔
637
            return this.expressionMap.mainAlias.metadata.tablePath
426,196✔
638

639
        return this.expressionMap.mainAlias.tablePath!
4,818✔
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)) {
691,492✔
655
            const metadata = this.connection.getMetadata(entityTarget)
678,894✔
656

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

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

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

685
            return this.expressionMap.createAlias({
75✔
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,336,009✔
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 } } = {}
694,775✔
706

707
        for (const alias of this.expressionMap.aliases) {
694,775✔
708
            if (!alias.hasMetadata) continue
4,528,336✔
709
            const replaceAliasNamePrefix =
710
                this.expressionMap.aliasNamePrefixingEnabled && alias.name
4,514,289✔
711
                    ? `${alias.name}.`
712
                    : ""
713

714
            if (!replacements[replaceAliasNamePrefix]) {
4,514,289✔
715
                replacements[replaceAliasNamePrefix] = {}
4,513,500✔
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) {
4,514,289✔
728
                if (relation.joinColumns.length > 0)
1,171,165✔
729
                    replacements[replaceAliasNamePrefix][
759,721✔
730
                        relation.propertyPath
731
                    ] = relation.joinColumns[0].databaseName
732
            }
733

734
            for (const relation of alias.metadata.relations) {
4,514,289✔
735
                const allColumns = [
1,171,165✔
736
                    ...relation.joinColumns,
737
                    ...relation.inverseJoinColumns,
738
                ]
739
                for (const joinColumn of allColumns) {
1,171,165✔
740
                    const propertyKey = `${relation.propertyPath}.${
1,140,645✔
741
                        joinColumn.referencedColumn!.propertyPath
742
                    }`
743
                    replacements[replaceAliasNamePrefix][propertyKey] =
1,140,645✔
744
                        joinColumn.databaseName
745
                }
746
            }
747

748
            for (const column of alias.metadata.columns) {
4,514,289✔
749
                replacements[replaceAliasNamePrefix][column.databaseName] =
12,082,907✔
750
                    column.databaseName
751
            }
752

753
            for (const column of alias.metadata.columns) {
4,514,289✔
754
                replacements[replaceAliasNamePrefix][column.propertyName] =
12,082,907✔
755
                    column.databaseName
756
            }
757

758
            for (const column of alias.metadata.columns) {
4,514,289✔
759
                replacements[replaceAliasNamePrefix][column.propertyPath] =
12,082,907✔
760
                    column.databaseName
761
            }
762
        }
763

764
        const replacementKeys = Object.keys(replacements)
694,775✔
765
        const replaceAliasNamePrefixes = replacementKeys
694,775✔
766
            .map((key) => escapeRegExp(key))
4,513,500✔
767
            .join("|")
768

769
        if (replacementKeys.length > 0) {
694,775✔
770
            statement = statement.replace(
682,190✔
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
682,190✔
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) {
8,352,287✔
787
                        match = matches[0]
8,154,455✔
788
                        pre = matches[1]
8,154,455✔
789
                        p = matches[3]
8,154,455✔
790

791
                        if (replacements[matches[2]][p]) {
8,154,455✔
792
                            return `${pre}${this.escape(
8,154,452✔
793
                                matches[2].substring(0, matches[2].length - 1),
794
                            )}.${this.escape(replacements[matches[2]][p])}`
795
                        }
796
                    } else {
797
                        match = matches[0]
197,832✔
798
                        pre = matches[1]
197,832✔
799
                        p = matches[2]
197,832✔
800

801
                        if (replacements[""][p]) {
197,832✔
802
                            return `${pre}${this.escape(replacements[""][p])}`
27,708✔
803
                        }
804
                    }
805
                    return match
170,127✔
806
                },
807
            )
808
        }
809

810
        return statement
694,775✔
811
    }
812

813
    protected createComment(): string {
814
        if (!this.expressionMap.comment) {
693,875✔
815
            return ""
693,675✔
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, "")} */ `
200✔
824
    }
825

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

837
        return ""
490,162✔
838
    }
839

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

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

850
        if (whereExpression.length > 0 && whereExpression !== "1=1") {
490,180✔
851
            conditionsArray.push(this.replacePropertyNames(whereExpression))
466,515✔
852
        }
853

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

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

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

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

886
        if (this.expressionMap.extraAppendedAndWhereCondition) {
490,180✔
887
            const condition = this.replacePropertyNames(
6,405✔
888
                this.expressionMap.extraAppendedAndWhereCondition,
889
            )
890
            conditionsArray.push(condition)
6,405✔
891
        }
892

893
        let condition = ""
490,180✔
894

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

898
        if (!conditionsArray.length) {
490,180✔
899
            condition += ""
22,841✔
900
        } else if (conditionsArray.length === 1) {
467,339✔
901
            condition += ` WHERE ${conditionsArray[0]}`
458,768✔
902
        } else {
903
            condition += ` WHERE ( ${conditionsArray.join(" ) AND ( ")} )`
8,571✔
904
        }
905

906
        return condition
490,180✔
907
    }
908

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

916
        // also add columns we must auto-return to perform entity updation
917
        // if user gave his own returning
918
        if (
226,247✔
919
            typeof this.expressionMap.returning !== "string" &&
537,189✔
920
            this.expressionMap.extraReturningColumns.length > 0 &&
921
            driver.isReturningSqlSupported(returningType)
922
        ) {
923
            columns.push(
36,305✔
924
                ...this.expressionMap.extraReturningColumns.filter((column) => {
925
                    return columns.indexOf(column) === -1
45,527✔
926
                }),
927
            )
928
        }
929

930
        if (columns.length) {
226,247✔
931
            let columnsExpression = columns
36,316✔
932
                .map((column) => {
933
                    const name = this.escape(column.databaseName)
45,554✔
934
                    if (driver.options.type === "mssql") {
45,554✔
935
                        if (
6,828!
936
                            this.expressionMap.queryType === "insert" ||
6,992✔
937
                            this.expressionMap.queryType === "update" ||
938
                            this.expressionMap.queryType === "soft-delete" ||
939
                            this.expressionMap.queryType === "restore"
940
                        ) {
941
                            return "INSERTED." + name
6,828✔
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") {
36,316✔
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") {
36,316✔
971
                if (
5,348✔
972
                    this.expressionMap.queryType === "insert" ||
5,448✔
973
                    this.expressionMap.queryType === "update"
974
                ) {
975
                    columnsExpression += " INTO @OutputTable"
5,312✔
976
                }
977
            }
978

979
            return columnsExpression
36,316✔
980
        } else if (typeof this.expressionMap.returning === "string") {
189,931✔
981
            return this.expressionMap.returning
63✔
982
        }
983

984
        return ""
189,868✔
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[] = []
226,247✔
993
        if (Array.isArray(this.expressionMap.returning)) {
226,247✔
994
            ;(this.expressionMap.returning as string[]).forEach(
16✔
995
                (columnName) => {
996
                    if (this.expressionMap.mainAlias!.hasMetadata) {
30✔
997
                        columns.push(
30✔
998
                            ...this.expressionMap.mainAlias!.metadata.findColumnsWithPropertyPath(
999
                                columnName,
1000
                            ),
1001
                        )
1002
                    }
1003
                },
1004
            )
1005
        }
1006
        return columns
226,247✔
1007
    }
1008

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

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

1045
                return expression
425,373✔
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,
718,477✔
1057
    ): string {
1058
        if (typeof condition === "string") return condition
753,300✔
1059

1060
        if (Array.isArray(condition)) {
417,325✔
1061
            if (condition.length === 0) {
174,093!
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) {
174,093✔
1068
                return this.createWhereClausesExpression(condition)
121,564✔
1069
            }
1070

1071
            return "(" + this.createWhereClausesExpression(condition) + ")"
52,529✔
1072
        }
1073

1074
        const { driver } = this.connection
243,232✔
1075

1076
        switch (condition.operator) {
243,232✔
1077
            case "lessThan":
1078
                return `${condition.parameters[0]} < ${condition.parameters[1]}`
181✔
1079
            case "lessThanOrEqual":
1080
                return `${condition.parameters[0]} <= ${condition.parameters[1]}`
50✔
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]}`
68✔
1091
            case "moreThanOrEqual":
1092
                return `${condition.parameters[0]} >= ${condition.parameters[1]}`
50✔
1093
            case "notEqual":
1094
                return `${condition.parameters[0]} != ${condition.parameters[1]}`
75✔
1095
            case "equal":
1096
                return `${condition.parameters[0]} = ${condition.parameters[1]}`
107,081✔
1097
            case "ilike":
1098
                if (
56✔
1099
                    driver.options.type === "postgres" ||
103✔
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]})`
41✔
1106
            case "like":
1107
                return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`
92✔
1108
            case "between":
1109
                return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`
153✔
1110
            case "in":
1111
                if (condition.parameters.length <= 1) {
99,937✔
1112
                    return "0=1"
50✔
1113
                }
1114
                return `${condition.parameters[0]} IN (${condition.parameters
99,887✔
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`
193✔
1125

1126
            case "not":
1127
                return `NOT(${this.createWhereConditionExpression(
380✔
1128
                    condition.condition,
1129
                )})`
1130
            case "brackets":
1131
                return `${this.createWhereConditionExpression(
34,823✔
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()) {
695,037✔
1148
            return ""
694,907✔
1149
        }
1150
        const databaseRequireRecusiveHint =
1151
            this.connection.driver.cteCapabilities.requiresRecursiveHint
130✔
1152

1153
        const cteStrings = this.expressionMap.commonTableExpressions.map(
130✔
1154
            (cte) => {
1155
                let cteBodyExpression = typeof cte.queryBuilder === 'string' ? cte.queryBuilder : '';
130✔
1156
                if (typeof cte.queryBuilder !== "string") {
130✔
1157
                    if (cte.queryBuilder.hasCommonTableExpressions()) {
86!
1158
                        throw new TypeORMError(
×
1159
                            `Nested CTEs aren't supported (CTE: ${cte.alias})`,
1160
                        )
1161
                    }
1162
                    cteBodyExpression = cte.queryBuilder.getQuery()
86✔
1163
                    if (
86!
1164
                        !this.connection.driver.cteCapabilities.writable &&
118✔
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())
86✔
1172
                }
1173
                let cteHeader = this.escape(cte.alias)
130✔
1174
                if (cte.options.columnNames) {
130✔
1175
                    const escapedColumnNames = cte.options.columnNames.map(
124✔
1176
                        (column) => this.escape(column),
124✔
1177
                    )
1178
                    if (
124✔
1179
                        InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
1180
                    ) {
1181
                        if (
80!
1182
                            cte.queryBuilder.expressionMap.selects.length &&
160✔
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(", ")})`
124✔
1192
                }
1193
                const recursiveClause =
1194
                    cte.options.recursive && databaseRequireRecusiveHint
130✔
1195
                        ? "RECURSIVE"
1196
                        : ""
1197
                let materializeClause = ""
130✔
1198
                if (
130✔
1199
                    this.connection.driver.cteCapabilities.materializedHint &&
196✔
1200
                    cte.options.materialized !== undefined
1201
                ) {
1202
                    materializeClause = cte.options.materialized
24✔
1203
                        ? "MATERIALIZED"
1204
                        : "NOT MATERIALIZED"
1205
                }
1206

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

1219
        return "WITH " + cteStrings.join(", ") + " "
130✔
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
113,381✔
1229
        const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
113,381✔
1230
            metadata.ensureEntityIdMap(id),
177,590✔
1231
        )
1232

1233
        // using in(...ids) for single primary key entities
1234
        if (!metadata.hasMultiplePrimaryKeys) {
113,381✔
1235
            const primaryColumn = metadata.primaryColumns[0]
100,228✔
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 (
100,228✔
1241
                !primaryColumn.transformer &&
300,390✔
1242
                !primaryColumn.relationMetadata &&
1243
                !primaryColumn.embeddedMetadata
1244
            ) {
1245
                return {
99,653✔
1246
                    [primaryColumn.propertyName]: In(
1247
                        normalized.map((id) =>
1248
                            primaryColumn.getEntityValue(id, false),
163,267✔
1249
                        ),
1250
                    ),
1251
                }
1252
            }
1253
        }
1254

1255
        return new Brackets((qb) => {
13,728✔
1256
            for (const data of normalized) {
13,728✔
1257
                qb.orWhere(new Brackets((qb) => qb.where(data)))
14,323✔
1258
            }
1259
        })
1260
    }
1261

1262
    protected getExistsCondition(subQuery: any): [string, any[]] {
1263
        const query = subQuery
175✔
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()]
175✔
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
160,951✔
1285
        const root: string[] = []
160,951✔
1286
        const propertyPathParts = propertyPath.split(".")
160,951✔
1287

1288
        while (propertyPathParts.length > 1) {
160,951✔
1289
            const part = propertyPathParts[0]
5,623✔
1290

1291
            if (!alias?.hasMetadata) {
5,623!
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)) {
5,623✔
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(
5,596✔
1302
                    `${propertyPathParts.shift()}.${propertyPathParts.shift()}`,
1303
                )
1304
                continue
5,596✔
1305
            }
1306

1307
            if (alias.metadata.hasRelationWithPropertyPath(part)) {
27✔
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(
27✔
1312
                    (joinAttr) => joinAttr.relationPropertyPath === part,
33✔
1313
                )
1314

1315
                if (!joinAttr?.alias) {
27!
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
27✔
1324
                root.push(...part.split("."))
27✔
1325
                propertyPathParts.shift()
27✔
1326
                continue
27✔
1327
            }
1328

1329
            break
×
1330
        }
1331

1332
        if (!alias) {
160,951!
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(".")
160,951✔
1338

1339
        const columns =
1340
            alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath)
160,951✔
1341

1342
        if (!columns.length) {
160,951✔
1343
            throw new EntityPropertyNotFoundError(propertyPath, alias.metadata)
100✔
1344
        }
1345

1346
        return [alias, root, columns]
160,851✔
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 = "",
155,841✔
1356
    ) {
1357
        const paths: string[] = []
161,293✔
1358

1359
        for (const key of Object.keys(entity)) {
161,293✔
1360
            const path = prefix ? `${prefix}.${key}` : key
184,272✔
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 (
184,272✔
1365
                entity[key] === null ||
480,919✔
1366
                typeof entity[key] !== "object" ||
1367
                InstanceChecker.isFindOperator(entity[key])
1368
            ) {
1369
                paths.push(path)
170,232✔
1370
                continue
170,232✔
1371
            }
1372

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

1383
            if (metadata.hasRelationWithPropertyPath(path)) {
8,588✔
1384
                const relation = metadata.findRelationWithPropertyPath(path)!
7,417✔
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 (
7,417✔
1394
                    relation.relationType === "one-to-one" ||
13,917✔
1395
                    relation.relationType === "many-to-one"
1396
                ) {
1397
                    const joinColumns = relation.joinColumns
7,405✔
1398
                        .map((j) => j.referencedColumn)
9,404✔
1399
                        .filter((j): j is ColumnMetadata => !!j)
9,404✔
1400

1401
                    const hasAllJoinColumns =
1402
                        joinColumns.length > 0 &&
7,405✔
1403
                        joinColumns.every((column) =>
1404
                            column.getEntityValue(entity[key], false),
9,404✔
1405
                        )
1406

1407
                    if (hasAllJoinColumns) {
7,405✔
1408
                        paths.push(path)
7,203✔
1409
                        continue
7,203✔
1410
                    }
1411
                }
1412

1413
                if (
214✔
1414
                    relation.relationType === "one-to-many" ||
422✔
1415
                    relation.relationType === "many-to-many"
1416
                ) {
1417
                    throw new Error(
12✔
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
202✔
1429
                const hasAllPrimaryKeys =
1430
                    primaryColumns.length > 0 &&
202✔
1431
                    primaryColumns.every((column) =>
1432
                        column.getEntityValue(entity[key], false),
202✔
1433
                    )
1434

1435
                if (hasAllPrimaryKeys) {
202!
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(
202✔
1445
                    relation.inverseEntityMetadata,
1446
                    entity[key],
1447
                ).map((p) => `${path}.${p}`)
202✔
1448
                paths.push(...subPaths)
202✔
1449
                continue
202✔
1450
            }
1451

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

1455
        return paths
161,281✔
1456
    }
1457

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

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

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

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

1478
                        containedWhere = containedWhere[part]
27✔
1479
                    }
1480

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

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

1492
                    yield [aliasPath, parameterValue]
160,851✔
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)) {
208,722✔
1512
            let parameters: any[] = []
101,700✔
1513
            if (parameterValue.useParameter) {
101,700✔
1514
                if (parameterValue.objectLiteralParameters) {
101,445✔
1515
                    this.setParameters(parameterValue.objectLiteralParameters)
175✔
1516
                } else if (parameterValue.multipleParameters) {
101,270✔
1517
                    for (const v of parameterValue.value) {
100,408✔
1518
                        parameters.push(this.createParameter(v))
164,595✔
1519
                    }
1520
                } else {
1521
                    parameters.push(this.createParameter(parameterValue.value))
862✔
1522
                }
1523
            }
1524

1525
            if (parameterValue.type === "raw") {
101,700✔
1526
                if (parameterValue.getSql) {
228✔
1527
                    return parameterValue.getSql(aliasPath)
203✔
1528
                } else {
1529
                    return {
25✔
1530
                        operator: "equal",
1531
                        parameters: [aliasPath, parameterValue.value],
1532
                    }
1533
                }
1534
            } else if (parameterValue.type === "not") {
101,472✔
1535
                if (parameterValue.child) {
443✔
1536
                    return {
368✔
1537
                        operator: parameterValue.type,
1538
                        condition: this.getWherePredicateCondition(
1539
                            aliasPath,
1540
                            parameterValue.child,
1541
                        ),
1542
                    }
1543
                } else {
1544
                    return {
75✔
1545
                        operator: "notEqual",
1546
                        parameters: [aliasPath, ...parameters],
1547
                    }
1548
                }
1549
            } else if (parameterValue.type === "and") {
101,029✔
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") {
101,023✔
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 {
101,017✔
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 {
107,022✔
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") {
503,595✔
1608
            return where
327,660✔
1609
        }
1610

1611
        if (InstanceChecker.isBrackets(where)) {
175,935✔
1612
            const whereQueryBuilder = this.createQueryBuilder()
34,835✔
1613

1614
            whereQueryBuilder.parentQueryBuilder = this
34,835✔
1615

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

1625
            whereQueryBuilder.expressionMap.wheres = []
34,835✔
1626

1627
            where.whereFactory(whereQueryBuilder as any)
34,835✔
1628

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

1637
        if (typeof where === "function") {
141,100✔
1638
            return where(this)
2,086✔
1639
        }
1640

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

1644
        for (const where of wheres) {
139,014✔
1645
            const conditions: WhereClauseCondition = []
139,281✔
1646

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

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

1663
        if (clauses.length === 1) {
138,902✔
1664
            return clauses[0].condition
138,691✔
1665
        }
1666

1667
        return clauses
211✔
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()
224,063✔
1675
    }
1676

1677
    protected hasCommonTableExpressions(): boolean {
1678
        return this.expressionMap.commonTableExpressions.length > 0
695,123✔
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