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

typeorm / typeorm / 14796576772

02 May 2025 01:52PM UTC coverage: 45.367% (-30.9%) from 76.309%
14796576772

Pull #11434

github

web-flow
Merge ec4ce2d00 into fadad1a74
Pull Request #11434: feat: release PR releases using pkg.pr.new

5216 of 12761 branches covered (40.87%)

Branch coverage included in aggregate %.

11439 of 23951 relevant lines covered (47.76%)

15712.55 hits per line

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

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

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

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

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

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

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

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

202
        if (InstanceChecker.isInsertQueryBuilder(this)) return this as any
35,461!
203

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

251
        if (
2,366✔
252
            typeof entityOrTableNameUpdateSet === "function" ||
2,430✔
253
            typeof entityOrTableNameUpdateSet === "string"
254
        ) {
255
            const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet)
2,338✔
256
            this.expressionMap.setMainAlias(mainAlias)
2,338✔
257
        }
258

259
        this.expressionMap.queryType = "update"
2,366✔
260
        this.expressionMap.valuesSet = updateSet
2,366✔
261

262
        if (InstanceChecker.isUpdateQueryBuilder(this)) return this as any
2,366!
263

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

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

273
        if (InstanceChecker.isDeleteQueryBuilder(this)) return this as any
517!
274

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

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

281
        if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this as any
104!
282

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

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

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

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

321
        this.expressionMap.queryType = "relation"
276✔
322
        this.expressionMap.relationPropertyPath = propertyPath
276✔
323

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

329
        if (InstanceChecker.isRelationQueryBuilder(this)) return this as any
276!
330

331
        return QueryBuilder.queryBuilderRegistry["RelationQueryBuilder"](this)
276✔
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 (
170,982✔
372
            this.parentQueryBuilder?.hasParameter(key) ||
341,620✔
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") {
177,131✔
384
            throw new TypeORMError(
4✔
385
                `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`,
386
            )
387
        }
388

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

395
        if (this.parentQueryBuilder) {
177,123✔
396
            this.parentQueryBuilder.setParameter(key, value)
9,657✔
397
        }
398

399
        this.expressionMap.parameters[key] = value
177,123✔
400
        return this
177,123✔
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)) {
6,221✔
408
            this.setParameter(key, value)
6,632✔
409
        }
410

411
        return this
6,217✔
412
    }
413

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

417
        do {
160,680✔
418
            parameterName = `orm_param_${this.parameterIndex++}`
161,016✔
419
        } while (this.hasParameter(parameterName))
420

421
        this.setParameter(parameterName, value)
160,680✔
422

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

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

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

452
        // add discriminator column parameter if it exist
453
        if (
67,528✔
454
            this.expressionMap.mainAlias &&
135,056✔
455
            this.expressionMap.mainAlias.hasMetadata
456
        ) {
457
            const metadata = this.expressionMap.mainAlias!.metadata
65,769✔
458
            if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
65,769✔
459
                const values = metadata.childEntityMetadatas
420✔
460
                    .filter(
461
                        (childMetadata) => childMetadata.discriminatorColumn,
56✔
462
                    )
463
                    .map((childMetadata) => childMetadata.discriminatorValue)
56✔
464
                values.push(metadata.discriminatorValue)
420✔
465
                parameters["discriminatorColumnValues"] = values
420✔
466
            }
467
        }
468

469
        return parameters
67,528✔
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]
142✔
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()
66,495✔
496
        const parameters = this.getParameters()
66,419✔
497
        return this.connection.driver.escapeQueryWithParameters(
66,419✔
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()
4✔
509
        const queryRunner = this.obtainQueryRunner()
4✔
510
        try {
4✔
511
            return await queryRunner.query(sql, parameters) // await is needed here because we are using finally
4✔
512
        } finally {
513
            if (queryRunner !== this.queryRunner) {
4✔
514
                // means we created our own query runner
515
                await queryRunner.release()
4✔
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)(
5,542✔
526
            this.connection,
527
            queryRunner ?? this.queryRunner,
11,084✔
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)
2,284✔
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
36✔
548
        return this
36✔
549
    }
550

551
    /**
552
     * Disables escaping.
553
     */
554
    disableEscaping(): this {
555
        this.expressionMap.disableEscaping = false
22✔
556
        return this
22✔
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
5,709,204✔
564
        return this.connection.driver.escape(name)
5,708,810✔
565
    }
566

567
    /**
568
     * Sets or overrides query builder's QueryRunner.
569
     */
570
    setQueryRunner(queryRunner: QueryRunner): this {
571
        this.queryRunner = queryRunner
×
572
        return this
×
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
36,792✔
581
        return this
36,792✔
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
4✔
589
        return this
4✔
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({
16✔
601
            queryBuilder,
602
            alias,
603
            options: options || {},
16!
604
        })
605
        return this
16✔
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
674,141✔
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
674,149!
622
                return this.escape(i)
674,149✔
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)
73,861!
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)
73,861✔
637
            return this.expressionMap.mainAlias.metadata.tablePath
73,303✔
638

639
        return this.expressionMap.mainAlias.tablePath!
558✔
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)) {
107,402✔
655
            const metadata = this.connection.getMetadata(entityTarget)
105,639✔
656

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

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

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

685
            return this.expressionMap.createAlias({
12✔
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
644,499✔
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 } } = {}
107,927✔
706

707
        for (const alias of this.expressionMap.aliases) {
107,927✔
708
            if (!alias.hasMetadata) continue
678,025✔
709
            const replaceAliasNamePrefix =
710
                this.expressionMap.aliasNamePrefixingEnabled && alias.name
676,031✔
711
                    ? `${alias.name}.`
712
                    : ""
713

714
            if (!replacements[replaceAliasNamePrefix]) {
676,031✔
715
                replacements[replaceAliasNamePrefix] = {}
675,911✔
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) {
676,031✔
728
                if (relation.joinColumns.length > 0)
99,621✔
729
                    replacements[replaceAliasNamePrefix][
77,999✔
730
                        relation.propertyPath
731
                    ] = relation.joinColumns[0].databaseName
732
            }
733

734
            for (const relation of alias.metadata.relations) {
676,031✔
735
                const allColumns = [
99,621✔
736
                    ...relation.joinColumns,
737
                    ...relation.inverseJoinColumns,
738
                ]
739
                for (const joinColumn of allColumns) {
99,621✔
740
                    const propertyKey = `${relation.propertyPath}.${
139,364✔
741
                        joinColumn.referencedColumn!.propertyPath
742
                    }`
743
                    replacements[replaceAliasNamePrefix][propertyKey] =
139,364✔
744
                        joinColumn.databaseName
745
                }
746
            }
747

748
            for (const column of alias.metadata.columns) {
676,031✔
749
                replacements[replaceAliasNamePrefix][column.databaseName] =
1,452,401✔
750
                    column.databaseName
751
            }
752

753
            for (const column of alias.metadata.columns) {
676,031✔
754
                replacements[replaceAliasNamePrefix][column.propertyName] =
1,452,401✔
755
                    column.databaseName
756
            }
757

758
            for (const column of alias.metadata.columns) {
676,031✔
759
                replacements[replaceAliasNamePrefix][column.propertyPath] =
1,452,401✔
760
                    column.databaseName
761
            }
762
        }
763

764
        const replacementKeys = Object.keys(replacements)
107,927✔
765
        const replaceAliasNamePrefixes = replacementKeys
107,927✔
766
            .map((key) => escapeRegExp(key))
675,911✔
767
            .join("|")
768

769
        if (replacementKeys.length > 0) {
107,927✔
770
            statement = statement.replace(
106,168✔
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
106,168✔
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) {
1,238,493✔
787
                        match = matches[0]
1,212,453✔
788
                        pre = matches[1]
1,212,453✔
789
                        p = matches[3]
1,212,453✔
790

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

801
                        if (replacements[""][p]) {
26,040✔
802
                            return `${pre}${this.escape(replacements[""][p])}`
3,583✔
803
                        }
804
                    }
805
                    return match
22,458✔
806
                },
807
            )
808
        }
809

810
        return statement
107,927✔
811
    }
812

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

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

837
        return ""
72,517✔
838
    }
839

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

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

850
        if (whereExpression.length > 0 && whereExpression !== "1=1") {
72,517✔
851
            conditionsArray.push(this.replacePropertyNames(whereExpression))
68,817✔
852
        }
853

854
        if (this.expressionMap.mainAlias!.hasMetadata) {
72,517✔
855
            const metadata = this.expressionMap.mainAlias!.metadata
70,962✔
856
            // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
857
            if (
70,962✔
858
                this.expressionMap.queryType === "select" &&
190,598✔
859
                !this.expressionMap.withDeleted &&
860
                metadata.deleteDateColumn
861
            ) {
862
                const column = this.expressionMap.aliasNamePrefixingEnabled
311!
863
                    ? this.expressionMap.mainAlias!.name +
864
                      "." +
865
                      metadata.deleteDateColumn.propertyName
866
                    : metadata.deleteDateColumn.propertyName
867

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

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

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

886
        if (this.expressionMap.extraAppendedAndWhereCondition) {
72,517✔
887
            const condition = this.replacePropertyNames(
1,022✔
888
                this.expressionMap.extraAppendedAndWhereCondition,
889
            )
890
            conditionsArray.push(condition)
1,022✔
891
        }
892

893
        let condition = ""
72,517✔
894

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

898
        if (!conditionsArray.length) {
72,517✔
899
            condition += ""
3,570✔
900
        } else if (conditionsArray.length === 1) {
68,947✔
901
            condition += ` WHERE ${conditionsArray[0]}`
67,548✔
902
        } else {
903
            condition += ` WHERE ( ${conditionsArray.join(" ) AND ( ")} )`
1,399✔
904
        }
905

906
        return condition
72,517✔
907
    }
908

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

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

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

955
            if (driver.options.type === "oracle") {
3,319✔
956
                columnsExpression +=
3,319✔
957
                    " INTO " +
958
                    columns
959
                        .map((column) => {
960
                            return this.createParameter({
3,908✔
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") {
3,319!
971
                if (
×
972
                    this.expressionMap.queryType === "insert" ||
×
973
                    this.expressionMap.queryType === "update"
974
                ) {
975
                    columnsExpression += " INTO @OutputTable"
×
976
                }
977
            }
978

979
            return columnsExpression
3,319✔
980
        } else if (typeof this.expressionMap.returning === "string") {
35,089✔
981
            return this.expressionMap.returning
3✔
982
        }
983

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

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

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

1045
                return expression
66,979✔
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,
101,611✔
1057
    ): string {
1058
        if (typeof condition === "string") return condition
106,554✔
1059

1060
        if (Array.isArray(condition)) {
58,771✔
1061
            if (condition.length === 0) {
26,692!
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) {
26,692✔
1068
                return this.createWhereClausesExpression(condition)
19,360✔
1069
            }
1070

1071
            return "(" + this.createWhereClausesExpression(condition) + ")"
7,332✔
1072
        }
1073

1074
        const { driver } = this.connection
32,079✔
1075

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

1105
                return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`
8✔
1106
            case "like":
1107
                return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`
14✔
1108
            case "between":
1109
                return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`
25✔
1110
            case "in":
1111
                if (condition.parameters.length <= 1) {
15,681✔
1112
                    return "0=1"
8✔
1113
                }
1114
                return `${condition.parameters[0]} IN (${condition.parameters
15,673✔
1115
                    .slice(1)
1116
                    .join(", ")})`
1117
            case "any":
1118
                if (driver.options.type === "cockroachdb") {
×
1119
                    return `${condition.parameters[0]}::STRING = ANY(${condition.parameters[1]}::STRING[])`
×
1120
                }
1121

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

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

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

1146
    protected createCteExpression(): string {
1147
        if (!this.hasCommonTableExpressions()) {
107,979✔
1148
            return ""
107,963✔
1149
        }
1150
        const databaseRequireRecusiveHint =
1151
            this.connection.driver.cteCapabilities.requiresRecursiveHint
16✔
1152

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

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

1220
        return "WITH " + cteStrings.join(", ") + " "
16✔
1221
    }
1222

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

1234
        // using in(...ids) for single primary key entities
1235
        if (!metadata.hasMultiplePrimaryKeys) {
17,637✔
1236
            const primaryColumn = metadata.primaryColumns[0]
15,728✔
1237

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

1256
        return new Brackets((qb) => {
2,001✔
1257
            for (const data of normalized) {
2,001✔
1258
                qb.orWhere(new Brackets((qb) => qb.where(data)))
2,061✔
1259
            }
1260
        })
1261
    }
1262

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

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

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

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

1289
        while (propertyPathParts.length > 1) {
24,474✔
1290
            const part = propertyPathParts[0]
913✔
1291

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

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

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

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

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

1330
            break
×
1331
        }
1332

1333
        if (!alias) {
24,474!
1334
            throw new Error(`Cannot find alias for property ${propertyPath}`)
×
1335
        }
1336

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

1340
        const columns =
1341
            alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath)
24,474✔
1342

1343
        if (!columns.length) {
24,474✔
1344
            throw new EntityPropertyNotFoundError(propertyPath, alias.metadata)
16✔
1345
        }
1346

1347
        return [alias, root, columns]
24,458✔
1348
    }
1349

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

1360
        for (const key of Object.keys(entity)) {
24,985✔
1361
            const path = prefix ? `${prefix}.${key}` : key
27,910✔
1362

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

1374
            if (metadata.hasEmbeddedWithPropertyPath(path)) {
2,089✔
1375
                const subPaths = this.createPropertyPath(
880✔
1376
                    metadata,
1377
                    entity[key],
1378
                    path,
1379
                )
1380
                paths.push(...subPaths)
880✔
1381
                continue
880✔
1382
            }
1383

1384
            if (metadata.hasRelationWithPropertyPath(path)) {
1,209✔
1385
                const relation = metadata.findRelationWithPropertyPath(path)!
1,153✔
1386

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

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

1402
                    const hasAllJoinColumns =
1403
                        joinColumns.length > 0 &&
1,149✔
1404
                        joinColumns.every((column) =>
1405
                            column.getEntityValue(entity[key], false),
1,455✔
1406
                        )
1407

1408
                    if (hasAllJoinColumns) {
1,149✔
1409
                        paths.push(path)
1,112✔
1410
                        continue
1,112✔
1411
                    }
1412
                }
1413

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

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

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

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

1453
            paths.push(path)
56✔
1454
        }
1455

1456
        return paths
24,981✔
1457
    }
1458

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

1466
            for (const propertyPath of propertyPaths) {
21,753✔
1467
                const [alias, aliasPropertyPath, columns] =
1468
                    this.findColumnsForPropertyPath(propertyPath)
24,474✔
1469

1470
                for (const column of columns) {
24,458✔
1471
                    let containedWhere = where
24,458✔
1472

1473
                    for (const part of aliasPropertyPath) {
24,458✔
1474
                        if (!containedWhere || !(part in containedWhere)) {
9!
1475
                            containedWhere = {}
×
1476
                            break
×
1477
                        }
1478

1479
                        containedWhere = containedWhere[part]
9✔
1480
                    }
1481

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

1488
                    const parameterValue = column.getEntityValue(
24,458✔
1489
                        containedWhere,
1490
                        true,
1491
                    )
1492

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

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

1508
    protected getWherePredicateCondition(
1509
        aliasPath: string,
1510
        parameterValue: any,
1511
    ): WhereClauseCondition {
1512
        if (InstanceChecker.isFindOperator(parameterValue)) {
27,185✔
1513
            const parameters: any[] = []
15,955✔
1514
            if (parameterValue.useParameter) {
15,955✔
1515
                if (parameterValue.objectLiteralParameters) {
15,917✔
1516
                    this.setParameters(parameterValue.objectLiteralParameters)
28✔
1517
                } else if (parameterValue.multipleParameters) {
15,889✔
1518
                    for (const v of parameterValue.value) {
15,755✔
1519
                        parameters.push(this.createParameter(v))
26,367✔
1520
                    }
1521
                } else {
1522
                    parameters.push(this.createParameter(parameterValue.value))
134✔
1523
                }
1524
            }
1525

1526
            if (parameterValue.type === "raw") {
15,955✔
1527
                if (parameterValue.getSql) {
37✔
1528
                    return parameterValue.getSql(aliasPath)
33✔
1529
                } else {
1530
                    return {
4✔
1531
                        operator: "equal",
1532
                        parameters: [aliasPath, parameterValue.value],
1533
                    }
1534
                }
1535
            } else if (parameterValue.type === "not") {
15,918✔
1536
                if (parameterValue.child) {
68✔
1537
                    return {
56✔
1538
                        operator: parameterValue.type,
1539
                        condition: this.getWherePredicateCondition(
1540
                            aliasPath,
1541
                            parameterValue.child,
1542
                        ),
1543
                    }
1544
                } else {
1545
                    return {
12✔
1546
                        operator: "notEqual",
1547
                        parameters: [aliasPath, ...parameters],
1548
                    }
1549
                }
1550
            } else if (parameterValue.type === "and") {
15,850!
1551
                const values: FindOperator<any>[] = parameterValue.value
×
1552

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

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

1599
    protected getWhereCondition(
1600
        where:
1601
            | string
1602
            | ((qb: this) => string)
1603
            | Brackets
1604
            | NotBrackets
1605
            | ObjectLiteral
1606
            | ObjectLiteral[],
1607
    ): WhereClauseCondition {
1608
        if (typeof where === "string") {
73,452✔
1609
            return where
46,508✔
1610
        }
1611

1612
        if (InstanceChecker.isBrackets(where)) {
26,944✔
1613
            const whereQueryBuilder = this.createQueryBuilder()
4,947✔
1614

1615
            whereQueryBuilder.parentQueryBuilder = this
4,947✔
1616

1617
            whereQueryBuilder.expressionMap.mainAlias =
4,947✔
1618
                this.expressionMap.mainAlias
1619
            whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
4,947✔
1620
                this.expressionMap.aliasNamePrefixingEnabled
1621
            whereQueryBuilder.expressionMap.parameters =
4,947✔
1622
                this.expressionMap.parameters
1623
            whereQueryBuilder.expressionMap.nativeParameters =
4,947✔
1624
                this.expressionMap.nativeParameters
1625

1626
            whereQueryBuilder.expressionMap.wheres = []
4,947✔
1627

1628
            where.whereFactory(whereQueryBuilder as any)
4,947✔
1629

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

1638
        if (typeof where === "function") {
21,997✔
1639
            return where(this)
276✔
1640
        }
1641

1642
        const wheres: ObjectLiteral[] = Array.isArray(where) ? where : [where]
21,721✔
1643
        const clauses: WhereClause[] = []
21,721✔
1644

1645
        for (const where of wheres) {
21,721✔
1646
            const conditions: WhereClauseCondition = []
21,757✔
1647

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

1661
            clauses.push({ type: "or", condition: conditions })
21,737✔
1662
        }
1663

1664
        if (clauses.length === 1) {
21,701✔
1665
            return clauses[0].condition
21,673✔
1666
        }
1667

1668
        return clauses
28✔
1669
    }
1670

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

1678
    protected hasCommonTableExpressions(): boolean {
1679
        return this.expressionMap.commonTableExpressions.length > 0
107,987✔
1680
    }
1681
}
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

© 2025 Coveralls, Inc