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

typeorm / typeorm / 15089093306

17 May 2025 09:03PM UTC coverage: 50.109% (-26.2%) from 76.346%
15089093306

Pull #11437

github

naorpeled
add comment about vector <#>
Pull Request #11437: feat(postgres): support vector data type

5836 of 12767 branches covered (45.71%)

Branch coverage included in aggregate %.

16 of 17 new or added lines in 4 files covered. (94.12%)

6283 existing lines in 64 files now uncovered.

12600 of 24025 relevant lines covered (52.45%)

28708.0 hits per line

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

87.45
/src/query-builder/QueryBuilder.ts
1
import { ObjectLiteral } from "../common/ObjectLiteral"
2
import { QueryRunner } from "../query-runner/QueryRunner"
3
import { DataSource } from "../data-source/DataSource"
4
import { QueryBuilderCteOptions } from "./QueryBuilderCte"
5
import { QueryExpressionMap } from "./QueryExpressionMap"
6✔
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"
6✔
15
import { QueryDeepPartialEntity } from "./QueryPartialEntity"
16
import { EntityMetadata } from "../metadata/EntityMetadata"
17
import { ColumnMetadata } from "../metadata/ColumnMetadata"
18
import { FindOperator } from "../find-options/FindOperator"
6✔
19
import { In } from "../find-options/operator/In"
6✔
20
import { TypeORMError } from "../error"
6✔
21
import { WhereClause, WhereClauseCondition } from "./WhereClause"
22
import { NotBrackets } from "./NotBrackets"
23
import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundError"
6✔
24
import { ReturningType } from "../driver/Driver"
25
import { OracleDriver } from "../driver/oracle/OracleDriver"
26
import { InstanceChecker } from "../util/InstanceChecker"
6✔
27
import { escapeRegExp } from "../util/escapeRegExp"
6✔
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> {
6✔
48
    readonly "@instanceof" = Symbol.for("QueryBuilder")
239,686✔
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
239,686✔
82

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

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

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

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

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

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

202
        if (InstanceChecker.isInsertQueryBuilder(this)) return this as any
51,700!
203

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

251
        if (
3,772✔
252
            typeof entityOrTableNameUpdateSet === "function" ||
3,868✔
253
            typeof entityOrTableNameUpdateSet === "string"
254
        ) {
255
            const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet)
3,730✔
256
            this.expressionMap.setMainAlias(mainAlias)
3,730✔
257
        }
258

259
        this.expressionMap.queryType = "update"
3,772✔
260
        this.expressionMap.valuesSet = updateSet
3,772✔
261

262
        if (InstanceChecker.isUpdateQueryBuilder(this)) return this as any
3,772!
263

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

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

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

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

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

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

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

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

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

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

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

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

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

331
        return QueryBuilder.queryBuilderRegistry["RelationQueryBuilder"](this)
415✔
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 (
473,208✔
372
            this.parentQueryBuilder?.hasParameter(key) ||
945,616✔
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") {
482,391✔
384
            throw new TypeORMError(
6✔
385
                `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`,
386
            )
387
        }
388

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

395
        if (this.parentQueryBuilder) {
482,381✔
396
            this.parentQueryBuilder.setParameter(key, value)
15,541✔
397
        }
398

399
        this.expressionMap.parameters[key] = value
482,381✔
400
        return this
482,381✔
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)) {
9,591✔
408
            this.setParameter(key, value)
10,333✔
409
        }
410

411
        return this
9,585✔
412
    }
413

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

417
        do {
456,244✔
418
            parameterName = `orm_param_${this.parameterIndex++}`
456,912✔
419
        } while (this.hasParameter(parameterName))
420

421
        this.setParameter(parameterName, value)
456,244✔
422

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

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

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

452
        // add discriminator column parameter if it exist
453
        if (
101,542✔
454
            this.expressionMap.mainAlias &&
203,084✔
455
            this.expressionMap.mainAlias.hasMetadata
456
        ) {
457
            const metadata = this.expressionMap.mainAlias!.metadata
98,904✔
458
            if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
98,904✔
459
                const values = metadata.childEntityMetadatas
639✔
460
                    .filter(
461
                        (childMetadata) => childMetadata.discriminatorColumn,
85✔
462
                    )
463
                    .map((childMetadata) => childMetadata.discriminatorValue)
85✔
464
                values.push(metadata.discriminatorValue)
639✔
465
                parameters["discriminatorColumnValues"] = values
639✔
466
            }
467
        }
468

469
        return parameters
101,542✔
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]
223✔
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()
99,945✔
496
        const parameters = this.getParameters()
99,830✔
497
        return this.connection.driver.escapeQueryWithParameters(
99,830✔
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()
9✔
509
        const queryRunner = this.obtainQueryRunner()
9✔
510
        try {
9✔
511
            return await queryRunner.query(sql, parameters) // await is needed here because we are using finally
9✔
512
        } finally {
513
            if (queryRunner !== this.queryRunner) {
9✔
514
                // means we created our own query runner
515
                await queryRunner.release()
9✔
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)(
8,885✔
526
            this.connection,
527
            queryRunner ?? this.queryRunner,
17,767✔
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)
3,474✔
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
55✔
548
        return this
55✔
549
    }
550

551
    /**
552
     * Disables escaping.
553
     */
554
    disableEscaping(): this {
555
        this.expressionMap.disableEscaping = false
23✔
556
        return this
23✔
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
11,257,338✔
564
        return this.connection.driver.escape(name)
11,256,890✔
565
    }
566

567
    /**
568
     * Sets or overrides query builder's QueryRunner.
569
     */
570
    setQueryRunner(queryRunner: QueryRunner): this {
571
        this.queryRunner = queryRunner
4✔
572
        return this
4✔
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
53,729✔
581
        return this
53,729✔
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
6✔
589
        return this
6✔
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({
28✔
601
            queryBuilder,
602
            alias,
603
            options: options || {},
29✔
604
        })
605
        return this
28✔
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
1,111,758✔
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
1,111,792!
622
                return this.escape(i)
1,111,792✔
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)
108,099!
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)
108,099✔
637
            return this.expressionMap.mainAlias.metadata.tablePath
107,278✔
638

639
        return this.expressionMap.mainAlias.tablePath!
821✔
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)) {
171,428✔
655
            const metadata = this.connection.getMetadata(entityTarget)
168,768✔
656

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

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

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

685
            return this.expressionMap.createAlias({
18✔
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
1,069,106✔
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 } } = {}
172,240✔
706

707
        for (const alias of this.expressionMap.aliases) {
172,240✔
708
            if (!alias.hasMetadata) continue
1,117,701✔
709
            const replaceAliasNamePrefix =
710
                this.expressionMap.aliasNamePrefixingEnabled && alias.name
1,114,691✔
711
                    ? `${alias.name}.`
712
                    : ""
713

714
            if (!replacements[replaceAliasNamePrefix]) {
1,114,691✔
715
                replacements[replaceAliasNamePrefix] = {}
1,114,506✔
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) {
1,114,691✔
728
                if (relation.joinColumns.length > 0)
333,465✔
729
                    replacements[replaceAliasNamePrefix][
209,334✔
730
                        relation.propertyPath
731
                    ] = relation.joinColumns[0].databaseName
732
            }
733

734
            for (const relation of alias.metadata.relations) {
1,114,691✔
735
                const allColumns = [
333,465✔
736
                    ...relation.joinColumns,
737
                    ...relation.inverseJoinColumns,
738
                ]
739
                for (const joinColumn of allColumns) {
333,465✔
740
                    const propertyKey = `${relation.propertyPath}.${
302,187✔
741
                        joinColumn.referencedColumn!.propertyPath
742
                    }`
743
                    replacements[replaceAliasNamePrefix][propertyKey] =
302,187✔
744
                        joinColumn.databaseName
745
                }
746
            }
747

748
            for (const column of alias.metadata.columns) {
1,114,691✔
749
                replacements[replaceAliasNamePrefix][column.databaseName] =
3,185,240✔
750
                    column.databaseName
751
            }
752

753
            for (const column of alias.metadata.columns) {
1,114,691✔
754
                replacements[replaceAliasNamePrefix][column.propertyName] =
3,185,240✔
755
                    column.databaseName
756
            }
757

758
            for (const column of alias.metadata.columns) {
1,114,691✔
759
                replacements[replaceAliasNamePrefix][column.propertyPath] =
3,185,240✔
760
                    column.databaseName
761
            }
762
        }
763

764
        const replacementKeys = Object.keys(replacements)
172,240✔
765
        const replaceAliasNamePrefixes = replacementKeys
172,240✔
766
            .map((key) => escapeRegExp(key))
1,114,506✔
767
            .join("|")
768

769
        if (replacementKeys.length > 0) {
172,240✔
770
            statement = statement.replace(
169,583✔
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
169,583✔
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) {
2,053,263✔
787
                        match = matches[0]
2,011,275✔
788
                        pre = matches[1]
2,011,275✔
789
                        p = matches[3]
2,011,275✔
790

791
                        if (replacements[matches[2]][p]) {
2,011,275✔
792
                            return `${pre}${this.escape(
2,011,273✔
793
                                matches[2].substring(0, matches[2].length - 1),
794
                            )}.${this.escape(replacements[matches[2]][p])}`
795
                        }
796
                    } else {
797
                        match = matches[0]
41,988✔
798
                        pre = matches[1]
41,988✔
799
                        p = matches[2]
41,988✔
800

801
                        if (replacements[""][p]) {
41,988✔
802
                            return `${pre}${this.escape(replacements[""][p])}`
5,750✔
803
                        }
804
                    }
805
                    return match
36,240✔
806
                },
807
            )
808
        }
809

810
        return statement
172,240✔
811
    }
812

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

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

837
        return ""
120,611✔
838
    }
839

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

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

850
        if (whereExpression.length > 0 && whereExpression !== "1=1") {
120,611✔
851
            conditionsArray.push(this.replacePropertyNames(whereExpression))
114,824✔
852
        }
853

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

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

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

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

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

893
        let condition = ""
120,611✔
894

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

898
        if (!conditionsArray.length) {
120,611✔
899
            condition += ""
5,590✔
900
        } else if (conditionsArray.length === 1) {
115,021✔
901
            condition += ` WHERE ${conditionsArray[0]}`
112,746✔
902
        } else {
903
            condition += ` WHERE ( ${conditionsArray.join(" ) AND ( ")} )`
2,275✔
904
        }
905

906
        return condition
120,611✔
907
    }
908

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

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

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

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

979
            return columnsExpression
3,120✔
980
        } else if (typeof this.expressionMap.returning === "string") {
53,295✔
981
            return this.expressionMap.returning
8✔
982
        }
983

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

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

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

1045
                return expression
101,991✔
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,
176,552✔
1057
    ): string {
1058
        if (typeof condition === "string") return condition
184,487✔
1059

1060
        if (Array.isArray(condition)) {
102,241✔
1061
            if (condition.length === 0) {
41,788!
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) {
41,788✔
1068
                return this.createWhereClausesExpression(condition)
29,937✔
1069
            }
1070

1071
            return "(" + this.createWhereClausesExpression(condition) + ")"
11,851✔
1072
        }
1073

1074
        const { driver } = this.connection
60,453✔
1075

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

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

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

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

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

1146
    protected createCteExpression(): string {
1147
        if (!this.hasCommonTableExpressions()) {
172,319✔
1148
            return ""
172,288✔
1149
        }
1150
        const databaseRequireRecusiveHint =
1151
            this.connection.driver.cteCapabilities.requiresRecursiveHint
31✔
1152

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

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

1220
        return "WITH " + cteStrings.join(", ") + " "
31✔
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
26,946✔
1230
        const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
26,946✔
1231
            metadata.ensureEntityIdMap(id),
47,937✔
1232
        )
1233

1234
        // using in(...ids) for single primary key entities
1235
        if (!metadata.hasMultiplePrimaryKeys) {
26,946✔
1236
            const primaryColumn = metadata.primaryColumns[0]
23,915✔
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 (
23,915✔
1242
                !primaryColumn.transformer &&
71,673✔
1243
                !primaryColumn.relationMetadata &&
1244
                !primaryColumn.embeddedMetadata
1245
            ) {
1246
                return {
23,777✔
1247
                    [primaryColumn.propertyName]: In(
1248
                        normalized.map((id) =>
1249
                            primaryColumn.getEntityValue(id, false),
44,646✔
1250
                        ),
1251
                    ),
1252
                }
1253
            }
1254
        }
1255

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

1263
    protected getExistsCondition(subQuery: any): [string, any[]] {
1264
        const query = subQuery
42✔
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()]
42✔
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
38,202✔
1286
        const root: string[] = []
38,202✔
1287
        const propertyPathParts = propertyPath.split(".")
38,202✔
1288

1289
        while (propertyPathParts.length > 1) {
38,202✔
1290
            const part = propertyPathParts[0]
1,369✔
1291

1292
            if (!alias?.hasMetadata) {
1,369!
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)) {
1,369✔
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(
1,360✔
1303
                    `${propertyPathParts.shift()}.${propertyPathParts.shift()}`,
1304
                )
1305
                continue
1,360✔
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) {
38,202!
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(".")
38,202✔
1339

1340
        const columns =
1341
            alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath)
38,202✔
1342

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

1347
        return [alias, root, columns]
38,178✔
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 = "",
37,575✔
1357
    ) {
1358
        const paths: string[] = []
38,901✔
1359

1360
        for (const key of Object.keys(entity)) {
38,901✔
1361
            const path = prefix ? `${prefix}.${key}` : key
43,590✔
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 (
43,590✔
1366
                entity[key] === null ||
113,943✔
1367
                typeof entity[key] !== "object" ||
1368
                InstanceChecker.isFindOperator(entity[key])
1369
            ) {
1370
                paths.push(path)
40,401✔
1371
                continue
40,401✔
1372
            }
1373

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

1384
            if (metadata.hasRelationWithPropertyPath(path)) {
1,863✔
1385
                const relation = metadata.findRelationWithPropertyPath(path)!
1,766✔
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,766✔
1395
                    relation.relationType === "one-to-one" ||
3,313✔
1396
                    relation.relationType === "many-to-one"
1397
                ) {
1398
                    const joinColumns = relation.joinColumns
1,762✔
1399
                        .map((j) => j.referencedColumn)
2,232✔
1400
                        .filter((j): j is ColumnMetadata => !!j)
2,232✔
1401

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

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

1414
                if (
55✔
1415
                    relation.relationType === "one-to-many" ||
108✔
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
51✔
1430
                const hasAllPrimaryKeys =
1431
                    primaryColumns.length > 0 &&
51✔
1432
                    primaryColumns.every((column) =>
1433
                        column.getEntityValue(entity[key], false),
51✔
1434
                    )
1435

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

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

1456
        return paths
38,897✔
1457
    }
1458

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

1466
            for (const propertyPath of propertyPaths) {
33,825✔
1467
                const [alias, aliasPropertyPath, columns] =
1468
                    this.findColumnsForPropertyPath(propertyPath)
38,202✔
1469

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

1473
                    for (const part of aliasPropertyPath) {
38,178✔
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
38,178✔
1484
                        .aliasNamePrefixingEnabled
1485
                        ? `${alias.name}.${column.propertyPath}`
1486
                        : column.propertyPath
1487

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

1493
                    yield [aliasPath, parameterValue]
38,178✔
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)) {
52,592✔
1513
            const parameters: any[] = []
24,329✔
1514
            if (parameterValue.useParameter) {
24,329✔
1515
                if (parameterValue.objectLiteralParameters) {
24,265✔
1516
                    this.setParameters(parameterValue.objectLiteralParameters)
42✔
1517
                } else if (parameterValue.multipleParameters) {
24,223✔
1518
                    for (const v of parameterValue.value) {
23,989✔
1519
                        parameters.push(this.createParameter(v))
45,027✔
1520
                    }
1521
                } else {
1522
                    parameters.push(this.createParameter(parameterValue.value))
234✔
1523
                }
1524
            }
1525

1526
            if (parameterValue.type === "raw") {
24,329✔
1527
                if (parameterValue.getSql) {
55✔
1528
                    return parameterValue.getSql(aliasPath)
49✔
1529
                } else {
1530
                    return {
6✔
1531
                        operator: "equal",
1532
                        parameters: [aliasPath, parameterValue.value],
1533
                    }
1534
                }
1535
            } else if (parameterValue.type === "not") {
24,274✔
1536
                if (parameterValue.child) {
111✔
1537
                    return {
93✔
1538
                        operator: parameterValue.type,
1539
                        condition: this.getWherePredicateCondition(
1540
                            aliasPath,
1541
                            parameterValue.child,
1542
                        ),
1543
                    }
1544
                } else {
1545
                    return {
18✔
1546
                        operator: "notEqual",
1547
                        parameters: [aliasPath, ...parameters],
1548
                    }
1549
                }
1550
            } else if (parameterValue.type === "and") {
24,163✔
1551
                const values: FindOperator<any>[] = parameterValue.value
7✔
1552

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

1567
                return {
7✔
1568
                    operator: parameterValue.type,
1569
                    parameters: values.map((operator) =>
1570
                        this.createWhereConditionExpression(
14✔
1571
                            this.getWherePredicateCondition(
1572
                                aliasPath,
1573
                                operator,
1574
                            ),
1575
                        ),
1576
                    ),
1577
                }
1578
            } else {
1579
                return {
24,149✔
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 {
28,263✔
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") {
122,401✔
1609
            return where
80,268✔
1610
        }
1611

1612
        if (InstanceChecker.isBrackets(where)) {
42,133✔
1613
            const whereQueryBuilder = this.createQueryBuilder()
7,939✔
1614

1615
            whereQueryBuilder.parentQueryBuilder = this
7,939✔
1616

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

1626
            whereQueryBuilder.expressionMap.wheres = []
7,939✔
1627

1628
            where.whereFactory(whereQueryBuilder as any)
7,939✔
1629

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

1638
        if (typeof where === "function") {
34,194✔
1639
            return where(this)
454✔
1640
        }
1641

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

1645
        for (const where of wheres) {
33,740✔
1646
            const conditions: WhereClauseCondition = []
33,829✔
1647

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

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

1664
        if (clauses.length === 1) {
33,712✔
1665
            return clauses[0].condition
33,635✔
1666
        }
1667

1668
        return clauses
77✔
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()
56,134✔
1676
    }
1677

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