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

typeorm / typeorm / 20709841055

05 Jan 2026 08:44AM UTC coverage: 80.876% (-0.03%) from 80.904%
20709841055

push

github

web-flow
fix: resolve nameless TableForeignKey on drop foreign key (#10744)

Co-authored-by: jimmytai <jimmytai@ionexenergy.com>

27016 of 32826 branches covered (82.3%)

Branch coverage included in aggregate %.

10 of 61 new or added lines in 7 files covered. (16.39%)

510 existing lines in 7 files now uncovered.

91407 of 113600 relevant lines covered (80.46%)

69458.7 hits per line

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

91.29
/src/driver/sqlserver/SqlServerQueryRunner.ts
1
import { ObjectLiteral } from "../../common/ObjectLiteral"
26 ✔
2
import { TypeORMError } from "../../error"
26 ✔
3
import { QueryFailedError } from "../../error/QueryFailedError"
26 ✔
4
import { QueryRunnerAlreadyReleasedError } from "../../error/QueryRunnerAlreadyReleasedError"
26 ✔
5
import { TransactionNotStartedError } from "../../error/TransactionNotStartedError"
26 ✔
6
import { ReadStream } from "../../platform/PlatformTools"
26 ✔
7
import { BaseQueryRunner } from "../../query-runner/BaseQueryRunner"
26 ✔
8
import { QueryLock } from "../../query-runner/QueryLock"
26 ✔
9
import { QueryResult } from "../../query-runner/QueryResult"
26 ✔
10
import { QueryRunner } from "../../query-runner/QueryRunner"
26 ✔
11
import { TableIndexOptions } from "../../schema-builder/options/TableIndexOptions"
26 ✔
12
import { Table } from "../../schema-builder/table/Table"
26 ✔
13
import { TableCheck } from "../../schema-builder/table/TableCheck"
26 ✔
14
import { TableColumn } from "../../schema-builder/table/TableColumn"
26 ✔
15
import { TableExclusion } from "../../schema-builder/table/TableExclusion"
26 ✔
16
import { TableForeignKey } from "../../schema-builder/table/TableForeignKey"
26 ✔
17
import { TableIndex } from "../../schema-builder/table/TableIndex"
26 ✔
18
import { TableUnique } from "../../schema-builder/table/TableUnique"
26 ✔
19
import { View } from "../../schema-builder/view/View"
26 ✔
20
import { Broadcaster } from "../../subscriber/Broadcaster"
26 ✔
21
import { BroadcasterResult } from "../../subscriber/BroadcasterResult"
26 ✔
22
import { InstanceChecker } from "../../util/InstanceChecker"
26 ✔
23
import { OrmUtils } from "../../util/OrmUtils"
26 ✔
24
import { Query } from "../Query"
26 ✔
25
import { ColumnType } from "../types/ColumnTypes"
26 ✔
26
import { IsolationLevel } from "../types/IsolationLevel"
26 ✔
27
import { MetadataTableType } from "../types/MetadataTableType"
26 ✔
28
import { ReplicationMode } from "../types/ReplicationMode"
26 ✔
29
import { MssqlParameter } from "./MssqlParameter"
26 ✔
30
import { SqlServerDriver } from "./SqlServerDriver"
26 ✔
31

26 ✔
32
/**
26 ✔
33
 * Runs queries on a single SQL Server database connection.
26 ✔
34
 */
26 ✔
35
export class SqlServerQueryRunner
26 ✔
36
    extends BaseQueryRunner
26 ✔
37
    implements QueryRunner
26 ✔
38
{
26 ✔
39
    // -------------------------------------------------------------------------
26 ✔
40
    // Public Implemented Properties
26 ✔
41
    // -------------------------------------------------------------------------
26 ✔
42

26 ✔
43
    /**
26 ✔
44
     * Database driver used by connection.
26 ✔
45
     */
26 ✔
46
    driver: SqlServerDriver
26 ✔
47

26 ✔
48
    // -------------------------------------------------------------------------
26 ✔
49
    // Private Properties
26 ✔
50
    // -------------------------------------------------------------------------
26 ✔
51

26 ✔
52
    private lock: QueryLock = new QueryLock()
26 ✔
53

26 ✔
54
    // -------------------------------------------------------------------------
26 ✔
55
    // Constructor
26 ✔
56
    // -------------------------------------------------------------------------
26 ✔
57

26 ✔
58
    constructor(driver: SqlServerDriver, mode: ReplicationMode) {
26 ✔
59
        super()
24,788 ✔
60
        this.driver = driver
24,788 ✔
61
        this.connection = driver.connection
24,788 ✔
62
        this.broadcaster = new Broadcaster(this)
24,788 ✔
63
        this.mode = mode
24,788 ✔
64
    }
24,788 ✔
65

26 ✔
66
    // -------------------------------------------------------------------------
26 ✔
67
    // Public Methods
26 ✔
68
    // -------------------------------------------------------------------------
26 ✔
69

26 ✔
70
    /**
26 ✔
71
     * Creates/uses database connection from the connection pool to perform further operations.
26 ✔
72
     * Returns obtained database connection.
26 ✔
73
     */
26 ✔
74
    connect(): Promise<void> {
26 ✔
75
        return Promise.resolve()
8 ✔
76
    }
8 ✔
77

26 ✔
78
    /**
26 ✔
79
     * Releases used database connection.
26 ✔
80
     * You cannot use query runner methods once its released.
26 ✔
81
     */
26 ✔
82
    release(): Promise<void> {
26 ✔
83
        this.isReleased = true
24,788 ✔
84
        return Promise.resolve()
24,788 ✔
85
    }
24,788 ✔
86

26 ✔
87
    /**
26 ✔
88
     * Starts transaction.
26 ✔
89
     */
26 ✔
90
    async startTransaction(isolationLevel?: IsolationLevel): Promise<void> {
26 ✔
91
        if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
18,592 !
92

18,592 ✔
93
        this.isTransactionActive = true
18,592 ✔
94
        try {
18,592 ✔
95
            await this.broadcaster.broadcast("BeforeTransactionStart")
18,592 ✔
96
        } catch (err) {
18,592 !
97
            this.isTransactionActive = false
×
98
            throw err
×
99
        }
×
100
        await new Promise<void>(async (ok, fail) => {
18,592 ✔
101
            const transactionCallback = (err: any) => {
18,592 ✔
102
                if (err) {
18,582 !
103
                    this.isTransactionActive = false
×
104
                    return fail(err)
×
105
                }
×
106
                ok()
18,582 ✔
107
            }
18,582 ✔
108

18,592 ✔
109
            if (this.transactionDepth === 0) {
18,592 ✔
110
                const pool = await (this.mode === "slave"
18,582 ✔
111
                    ? this.driver.obtainSlaveConnection()
18,582 !
112
                    : this.driver.obtainMasterConnection())
18,582 ✔
113
                this.databaseConnection = pool.transaction()
18,582 ✔
114
                this.connection.logger.logQuery("BEGIN TRANSACTION")
18,582 ✔
115
                if (isolationLevel) {
18,582 ✔
116
                    this.databaseConnection.begin(
12 ✔
117
                        this.convertIsolationLevel(isolationLevel),
12 ✔
118
                        transactionCallback,
12 ✔
119
                    )
12 ✔
120
                    this.connection.logger.logQuery(
12 ✔
121
                        "SET TRANSACTION ISOLATION LEVEL " + isolationLevel,
12 ✔
122
                    )
12 ✔
123
                } else {
18,582 ✔
124
                    this.databaseConnection.begin(transactionCallback)
18,570 ✔
125
                }
18,570 ✔
126
            } else {
18,592 ✔
127
                await this.query(
10 ✔
128
                    `SAVE TRANSACTION typeorm_${this.transactionDepth}`,
10 ✔
129
                )
10 ✔
130
                ok()
10 ✔
131
            }
10 ✔
132
            this.transactionDepth += 1
18,592 ✔
133
        })
18,592 ✔
134

18,592 ✔
135
        await this.broadcaster.broadcast("AfterTransactionStart")
18,592 ✔
136
    }
18,592 ✔
137

26 ✔
138
    /**
26 ✔
139
     * Commits transaction.
26 ✔
140
     * Error will be thrown if transaction was not started.
26 ✔
141
     */
26 ✔
142
    async commitTransaction(): Promise<void> {
26 ✔
143
        if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
18,544 !
144

18,544 ✔
145
        if (!this.isTransactionActive) throw new TransactionNotStartedError()
18,544 !
146

18,544 ✔
147
        await this.broadcaster.broadcast("BeforeTransactionCommit")
18,544 ✔
148

18,544 ✔
149
        if (this.transactionDepth === 1) {
18,544 ✔
150
            return new Promise<void>((ok, fail) => {
18,540 ✔
151
                this.databaseConnection.commit(async (err: any) => {
18,540 ✔
152
                    if (err) return fail(err)
18,540 !
153
                    this.isTransactionActive = false
18,540 ✔
154
                    this.databaseConnection = null
18,540 ✔
155

18,540 ✔
156
                    await this.broadcaster.broadcast("AfterTransactionCommit")
18,540 ✔
157

18,540 ✔
158
                    ok()
18,540 ✔
159
                    this.connection.logger.logQuery("COMMIT")
18,540 ✔
160
                    this.transactionDepth -= 1
18,540 ✔
161
                })
18,540 ✔
162
            })
18,540 ✔
163
        }
18,540 ✔
164
        this.transactionDepth -= 1
4 ✔
165
    }
4 ✔
166

26 ✔
167
    /**
26 ✔
168
     * Rollbacks transaction.
26 ✔
169
     * Error will be thrown if transaction was not started.
26 ✔
170
     */
26 ✔
171
    async rollbackTransaction(): Promise<void> {
26 ✔
172
        if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
48 !
173

48 ✔
174
        if (!this.isTransactionActive) throw new TransactionNotStartedError()
48 !
175

48 ✔
176
        await this.broadcaster.broadcast("BeforeTransactionRollback")
48 ✔
177

48 ✔
178
        if (this.transactionDepth > 1) {
48 ✔
179
            await this.query(
6 ✔
180
                `ROLLBACK TRANSACTION typeorm_${this.transactionDepth - 1}`,
6 ✔
181
            )
6 ✔
182
            this.transactionDepth -= 1
6 ✔
183
        } else {
48 ✔
184
            return new Promise<void>((ok, fail) => {
42 ✔
185
                this.databaseConnection.rollback(async (err: any) => {
42 ✔
186
                    if (err) return fail(err)
42 ✔
187
                    this.isTransactionActive = false
40 ✔
188
                    this.databaseConnection = null
40 ✔
189

40 ✔
190
                    await this.broadcaster.broadcast("AfterTransactionRollback")
40 ✔
191

40 ✔
192
                    ok()
40 ✔
193
                    this.connection.logger.logQuery("ROLLBACK")
40 ✔
194
                    this.transactionDepth -= 1
40 ✔
195
                })
42 ✔
196
            })
42 ✔
197
        }
42 ✔
198
    }
48 ✔
199

26 ✔
200
    /**
26 ✔
201
     * Executes a given SQL query.
26 ✔
202
     */
26 ✔
203
    async query(
26 ✔
204
        query: string,
108,104 ✔
205
        parameters?: any[],
108,104 ✔
206
        useStructuredResult = false,
108,104 ✔
207
    ): Promise<any> {
108,104 ✔
208
        if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
108,104 !
209

108,104 ✔
210
        const release = await this.lock.acquire()
108,104 ✔
211

108,104 ✔
212
        this.driver.connection.logger.logQuery(query, parameters, this)
108,104 ✔
213
        await this.broadcaster.broadcast("BeforeQuery", query, parameters)
108,104 ✔
214

108,104 ✔
215
        const broadcasterResult = new BroadcasterResult()
108,104 ✔
216

108,104 ✔
217
        try {
108,104 ✔
218
            const pool = await (this.mode === "slave"
108,104 ✔
219
                ? this.driver.obtainSlaveConnection()
108,104 ✔
220
                : this.driver.obtainMasterConnection())
108,104 ✔
221
            const request = new this.driver.mssql.Request(
108,104 ✔
222
                this.isTransactionActive ? this.databaseConnection : pool,
108,104 ✔
223
            )
108,104 ✔
224
            if (parameters && parameters.length) {
108,104 ✔
225
                parameters.forEach((parameter, index) => {
30,042 ✔
226
                    const parameterName = index.toString()
70,744 ✔
227
                    if (InstanceChecker.isMssqlParameter(parameter)) {
70,744 ✔
228
                        const mssqlParameter =
53,058 ✔
229
                            this.mssqlParameterToNativeParameter(parameter)
53,058 ✔
230
                        if (mssqlParameter) {
53,058 ✔
231
                            request.input(
52,994 ✔
232
                                parameterName,
52,994 ✔
233
                                mssqlParameter,
52,994 ✔
234
                                parameter.value,
52,994 ✔
235
                            )
52,994 ✔
236
                        } else {
53,058 ✔
237
                            request.input(parameterName, parameter.value)
64 ✔
238
                        }
64 ✔
239
                    } else {
70,744 ✔
240
                        request.input(parameterName, parameter)
17,686 ✔
241
                    }
17,686 ✔
242
                })
30,042 ✔
243
            }
30,042 ✔
244
            const queryStartTime = Date.now()
108,104 ✔
245

108,104 ✔
246
            const raw = await new Promise<any>((ok, fail) => {
108,104 ✔
247
                request.query(query, (err: any, raw: any) => {
108,104 ✔
248
                    // log slow queries if maxQueryExecution time is set
108,104 ✔
249
                    const maxQueryExecutionTime =
108,104 ✔
250
                        this.driver.options.maxQueryExecutionTime
108,104 ✔
251
                    const queryEndTime = Date.now()
108,104 ✔
252
                    const queryExecutionTime = queryEndTime - queryStartTime
108,104 ✔
253

108,104 ✔
254
                    this.broadcaster.broadcastAfterQueryEvent(
108,104 ✔
255
                        broadcasterResult,
108,104 ✔
256
                        query,
108,104 ✔
257
                        parameters,
108,104 ✔
258
                        true,
108,104 ✔
259
                        queryExecutionTime,
108,104 ✔
260
                        raw,
108,104 ✔
261
                        undefined,
108,104 ✔
262
                    )
108,104 ✔
263

108,104 ✔
264
                    if (
108,104 ✔
265
                        maxQueryExecutionTime &&
108,104 !
266
                        queryExecutionTime > maxQueryExecutionTime
×
267
                    ) {
108,104 !
268
                        this.driver.connection.logger.logQuerySlow(
×
269
                            queryExecutionTime,
×
270
                            query,
×
271
                            parameters,
×
272
                            this,
×
273
                        )
×
274
                    }
×
275

108,104 ✔
276
                    if (err) {
108,104 ✔
277
                        fail(new QueryFailedError(query, parameters, err))
16 ✔
278
                    }
16 ✔
279

108,104 ✔
280
                    ok(raw)
108,104 ✔
281
                })
108,104 ✔
282
            })
108,104 ✔
283

108,088 ✔
284
            const result = new QueryResult()
108,088 ✔
285

108,088 ✔
286
            if (raw?.hasOwnProperty("recordset")) {
108,104 ✔
287
                result.records = raw.recordset
108,088 ✔
288
            }
108,088 ✔
289

108,088 ✔
290
            if (raw?.hasOwnProperty("rowsAffected")) {
108,104 ✔
291
                result.affected = raw.rowsAffected[0]
108,088 ✔
292
            }
108,088 ✔
293

108,088 ✔
294
            const queryType = query.slice(0, query.indexOf(" "))
108,088 ✔
295
            switch (queryType) {
108,088 ✔
296
                case "DELETE":
108,104 ✔
297
                    // for DELETE query additionally return number of affected rows
260 ✔
298
                    result.raw = [raw.recordset, raw.rowsAffected[0]]
260 ✔
299
                    break
260 ✔
300
                default:
108,104 ✔
301
                    result.raw = raw.recordset
107,828 ✔
302
            }
108,104 ✔
303

108,088 ✔
304
            if (useStructuredResult) {
108,104 ✔
305
                return result
31,066 ✔
306
            } else {
108,104 ✔
307
                return result.raw
77,022 ✔
308
            }
77,022 ✔
309
        } catch (err) {
108,104 ✔
310
            this.driver.connection.logger.logQueryError(
16 ✔
311
                err,
16 ✔
312
                query,
16 ✔
313
                parameters,
16 ✔
314
                this,
16 ✔
315
            )
16 ✔
316
            this.broadcaster.broadcastAfterQueryEvent(
16 ✔
317
                broadcasterResult,
16 ✔
318
                query,
16 ✔
319
                parameters,
16 ✔
320
                false,
16 ✔
321
                undefined,
16 ✔
322
                undefined,
16 ✔
323
                err,
16 ✔
324
            )
16 ✔
325

16 ✔
326
            throw err
16 ✔
327
        } finally {
108,104 !
328
            await broadcasterResult.wait()
108,104 ✔
329

108,104 ✔
330
            release()
108,104 ✔
331
        }
108,104 ✔
332
    }
108,104 ✔
333

26 ✔
334
    /**
26 ✔
335
     * Returns raw data stream.
26 ✔
336
     */
26 ✔
337
    async stream(
26 ✔
338
        query: string,
2 ✔
339
        parameters?: any[],
2 ✔
340
        onEnd?: Function,
2 ✔
341
        onError?: Function,
2 ✔
342
    ): Promise<ReadStream> {
2 ✔
343
        if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
2 !
344

2 ✔
345
        const release = await this.lock.acquire()
2 ✔
346

2 ✔
347
        this.driver.connection.logger.logQuery(query, parameters, this)
2 ✔
348
        const pool = await (this.mode === "slave"
2 ✔
349
            ? this.driver.obtainSlaveConnection()
2 !
350
            : this.driver.obtainMasterConnection())
2 ✔
351
        const request = new this.driver.mssql.Request(
2 ✔
352
            this.isTransactionActive ? this.databaseConnection : pool,
2 !
353
        )
2 ✔
354
        if (parameters && parameters.length) {
2 !
355
            parameters.forEach((parameter, index) => {
×
356
                const parameterName = index.toString()
×
357
                if (InstanceChecker.isMssqlParameter(parameter)) {
×
358
                    request.input(
×
359
                        parameterName,
×
360
                        this.mssqlParameterToNativeParameter(parameter),
×
361
                        parameter.value,
×
362
                    )
×
363
                } else {
×
364
                    request.input(parameterName, parameter)
×
365
                }
×
366
            })
×
367
        }
×
368

2 ✔
369
        request.query(query)
2 ✔
370

2 ✔
371
        const streamRequest = request.toReadableStream()
2 ✔
372

2 ✔
373
        streamRequest.on("error", (err: any) => {
2 ✔
374
            release()
×
375
            this.driver.connection.logger.logQueryError(
×
376
                err,
×
377
                query,
×
378
                parameters,
×
379
                this,
×
380
            )
×
381
        })
2 ✔
382

2 ✔
383
        streamRequest.on("end", () => {
2 ✔
384
            release()
2 ✔
385
        })
2 ✔
386

2 ✔
387
        if (onEnd) {
2 !
388
            streamRequest.on("end", onEnd)
×
389
        }
×
390

2 ✔
391
        if (onError) {
2 !
392
            streamRequest.on("error", onError)
×
393
        }
×
394

2 ✔
395
        return streamRequest
2 ✔
396
    }
2 ✔
397

26 ✔
398
    /**
26 ✔
399
     * Returns all available database names including system databases.
26 ✔
400
     */
26 ✔
401
    async getDatabases(): Promise<string[]> {
26 ✔
402
        const results: ObjectLiteral[] = await this.query(`EXEC sp_databases`)
×
403
        return results.map((result) => result["DATABASE_NAME"])
×
404
    }
×
405

26 ✔
406
    /**
26 ✔
407
     * Returns all available schema names including system schemas.
26 ✔
408
     * If database parameter specified, returns schemas of that database.
26 ✔
409
     */
26 ✔
410
    async getSchemas(database?: string): Promise<string[]> {
26 ✔
411
        const query = database
×
412
            ? `SELECT * FROM "${database}"."sys"."schema"`
×
413
            : `SELECT * FROM "sys"."schemas"`
×
414
        const results: ObjectLiteral[] = await this.query(query)
×
415
        return results.map((result) => result["name"])
×
416
    }
×
417

26 ✔
418
    /**
26 ✔
419
     * Checks if database with the given name exist.
26 ✔
420
     */
26 ✔
421
    async hasDatabase(database: string): Promise<boolean> {
26 ✔
422
        const result = await this.query(
2,900 ✔
423
            `SELECT DB_ID('${database}') as "db_id"`,
2,900 ✔
424
        )
2,900 ✔
425
        const dbId = result[0]["db_id"]
2,900 ✔
426
        return !!dbId
2,900 ✔
427
    }
2,900 ✔
428

26 ✔
429
    /**
26 ✔
430
     * Loads currently using database
26 ✔
431
     */
26 ✔
432
    async getCurrentDatabase(): Promise<string> {
26 ✔
433
        const currentDBQuery = await this.query(`SELECT DB_NAME() AS "db_name"`)
3,672 ✔
434
        return currentDBQuery[0]["db_name"]
3,672 ✔
435
    }
3,672 ✔
436

26 ✔
437
    /**
26 ✔
438
     * Checks if schema with the given name exist.
26 ✔
439
     */
26 ✔
440
    async hasSchema(schema: string): Promise<boolean> {
26 ✔
441
        const result = await this.query(
6 ✔
442
            `SELECT SCHEMA_ID('${schema}') as "schema_id"`,
6 ✔
443
        )
6 ✔
444
        const schemaId = result[0]["schema_id"]
6 ✔
445
        return !!schemaId
6 ✔
446
    }
6 ✔
447

26 ✔
448
    /**
26 ✔
449
     * Loads currently using database schema
26 ✔
450
     */
26 ✔
451
    async getCurrentSchema(): Promise<string> {
26 ✔
452
        const currentSchemaQuery = await this.query(
4,572 ✔
453
            `SELECT SCHEMA_NAME() AS "schema_name"`,
4,572 ✔
454
        )
4,572 ✔
455
        return currentSchemaQuery[0]["schema_name"]
4,572 ✔
456
    }
4,572 ✔
457

26 ✔
458
    /**
26 ✔
459
     * Checks if table with the given name exist in the database.
26 ✔
460
     */
26 ✔
461
    async hasTable(tableOrName: Table | string): Promise<boolean> {
26 ✔
462
        const parsedTableName = this.driver.parseTableName(tableOrName)
3,126 ✔
463

3,126 ✔
464
        if (!parsedTableName.database) {
3,126 !
465
            parsedTableName.database = await this.getCurrentDatabase()
×
466
        }
×
467

3,126 ✔
468
        if (!parsedTableName.schema) {
3,126 !
469
            parsedTableName.schema = await this.getCurrentSchema()
×
470
        }
×
471

3,126 ✔
472
        const sql = `SELECT * FROM "${parsedTableName.database}"."INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_NAME" = '${parsedTableName.tableName}' AND "TABLE_SCHEMA" = '${parsedTableName.schema}'`
3,126 ✔
473
        const result = await this.query(sql)
3,126 ✔
474
        return result.length ? true : false
3,126 ✔
475
    }
3,126 ✔
476

26 ✔
477
    /**
26 ✔
478
     * Checks if column exist in the table.
26 ✔
479
     */
26 ✔
480
    async hasColumn(
26 ✔
481
        tableOrName: Table | string,
8 ✔
482
        columnName: string,
8 ✔
483
    ): Promise<boolean> {
8 ✔
484
        const parsedTableName = this.driver.parseTableName(tableOrName)
8 ✔
485

8 ✔
486
        if (!parsedTableName.database) {
8 !
487
            parsedTableName.database = await this.getCurrentDatabase()
×
488
        }
×
489

8 ✔
490
        if (!parsedTableName.schema) {
8 !
491
            parsedTableName.schema = await this.getCurrentSchema()
×
492
        }
×
493

8 ✔
494
        const sql = `SELECT * FROM "${parsedTableName.database}"."INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = '${parsedTableName.tableName}' AND "TABLE_SCHEMA" = '${parsedTableName.schema}' AND "COLUMN_NAME" = '${columnName}'`
8 ✔
495
        const result = await this.query(sql)
8 ✔
496
        return result.length ? true : false
8 ✔
497
    }
8 ✔
498

26 ✔
499
    /**
26 ✔
500
     * Creates a new database.
26 ✔
501
     */
26 ✔
502
    async createDatabase(
26 ✔
503
        database: string,
18 ✔
504
        ifNotExist?: boolean,
18 ✔
505
    ): Promise<void> {
18 ✔
506
        const up = ifNotExist
18 ✔
507
            ? `IF DB_ID('${database}') IS NULL CREATE DATABASE "${database}"`
18 ✔
508
            : `CREATE DATABASE "${database}"`
18 !
509
        const down = `DROP DATABASE "${database}"`
18 ✔
510
        await this.executeQueries(new Query(up), new Query(down))
18 ✔
511
    }
18 ✔
512

26 ✔
513
    /**
26 ✔
514
     * Drops database.
26 ✔
515
     */
26 ✔
516
    async dropDatabase(database: string, ifExist?: boolean): Promise<void> {
26 ✔
517
        const up = ifExist
4 ✔
518
            ? `IF DB_ID('${database}') IS NOT NULL DROP DATABASE "${database}"`
4 ✔
519
            : `DROP DATABASE "${database}"`
4 ✔
520
        const down = `CREATE DATABASE "${database}"`
4 ✔
521
        await this.executeQueries(new Query(up), new Query(down))
4 ✔
522
    }
4 ✔
523

26 ✔
524
    /**
26 ✔
525
     * Creates table schema.
26 ✔
526
     * If database name also specified (e.g. 'dbName.schemaName') schema will be created in specified database.
26 ✔
527
     */
26 ✔
528
    async createSchema(
26 ✔
529
        schemaPath: string,
28 ✔
530
        ifNotExist?: boolean,
28 ✔
531
    ): Promise<void> {
28 ✔
532
        const upQueries: Query[] = []
28 ✔
533
        const downQueries: Query[] = []
28 ✔
534

28 ✔
535
        if (schemaPath.indexOf(".") === -1) {
28 ✔
536
            const upQuery = ifNotExist
14 ✔
537
                ? `IF SCHEMA_ID('${schemaPath}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${schemaPath}"') END`
14 ✔
538
                : `CREATE SCHEMA "${schemaPath}"`
14 !
539
            upQueries.push(new Query(upQuery))
14 ✔
540
            downQueries.push(new Query(`DROP SCHEMA "${schemaPath}"`))
14 ✔
541
        } else {
14 ✔
542
            const dbName = schemaPath.split(".")[0]
14 ✔
543
            const schema = schemaPath.split(".")[1]
14 ✔
544
            const currentDB = await this.getCurrentDatabase()
14 ✔
545
            upQueries.push(new Query(`USE "${dbName}"`))
14 ✔
546
            downQueries.push(new Query(`USE "${currentDB}"`))
14 ✔
547

14 ✔
548
            const upQuery = ifNotExist
14 ✔
549
                ? `IF SCHEMA_ID('${schema}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${schema}"') END`
14 ✔
550
                : `CREATE SCHEMA "${schema}"`
14 !
551
            upQueries.push(new Query(upQuery))
14 ✔
552
            downQueries.push(new Query(`DROP SCHEMA "${schema}"`))
14 ✔
553

14 ✔
554
            upQueries.push(new Query(`USE "${currentDB}"`))
14 ✔
555
            downQueries.push(new Query(`USE "${dbName}"`))
14 ✔
556
        }
14 ✔
557

28 ✔
558
        await this.executeQueries(upQueries, downQueries)
28 ✔
559
    }
28 ✔
560

26 ✔
561
    /**
26 ✔
562
     * Drops table schema.
26 ✔
563
     * If database name also specified (e.g. 'dbName.schemaName') schema will be dropped in specified database.
26 ✔
564
     */
26 ✔
565
    async dropSchema(schemaPath: string, ifExist?: boolean): Promise<void> {
26 ✔
566
        const upQueries: Query[] = []
2 ✔
567
        const downQueries: Query[] = []
2 ✔
568

2 ✔
569
        if (schemaPath.indexOf(".") === -1) {
2 ✔
570
            const upQuery = ifExist
2 ✔
571
                ? `IF SCHEMA_ID('${schemaPath}') IS NULL BEGIN EXEC ('DROP SCHEMA "${schemaPath}"') END`
2 !
572
                : `DROP SCHEMA "${schemaPath}"`
2 ✔
573
            upQueries.push(new Query(upQuery))
2 ✔
574
            downQueries.push(new Query(`CREATE SCHEMA "${schemaPath}"`))
2 ✔
575
        } else {
2 !
576
            const dbName = schemaPath.split(".")[0]
×
577
            const schema = schemaPath.split(".")[1]
×
578
            const currentDB = await this.getCurrentDatabase()
×
579
            upQueries.push(new Query(`USE "${dbName}"`))
×
580
            downQueries.push(new Query(`USE "${currentDB}"`))
×
581

×
582
            const upQuery = ifExist
×
583
                ? `IF SCHEMA_ID('${schema}') IS NULL BEGIN EXEC ('DROP SCHEMA "${schema}"') END`
×
584
                : `DROP SCHEMA "${schema}"`
×
585
            upQueries.push(new Query(upQuery))
×
586
            downQueries.push(new Query(`CREATE SCHEMA "${schema}"`))
×
587

×
588
            upQueries.push(new Query(`USE "${currentDB}"`))
×
589
            downQueries.push(new Query(`USE "${dbName}"`))
×
590
        }
×
591

2 ✔
592
        await this.executeQueries(upQueries, downQueries)
2 ✔
593
    }
2 ✔
594

26 ✔
595
    /**
26 ✔
596
     * Creates a new table.
26 ✔
597
     */
26 ✔
598
    async createTable(
26 ✔
599
        table: Table,
10,168 ✔
600
        ifNotExist: boolean = false,
10,168 ✔
601
        createForeignKeys: boolean = true,
10,168 ✔
602
        createIndices: boolean = true,
10,168 ✔
603
    ): Promise<void> {
10,168 ✔
604
        if (ifNotExist) {
10,168 ✔
605
            const isTableExist = await this.hasTable(table)
66 ✔
606
            if (isTableExist) return Promise.resolve()
66 ✔
607
        }
66 ✔
608
        const upQueries: Query[] = []
10,164 ✔
609
        const downQueries: Query[] = []
10,164 ✔
610

10,164 ✔
611
        upQueries.push(this.createTableSql(table, createForeignKeys))
10,164 ✔
612
        downQueries.push(this.dropTableSql(table))
10,164 ✔
613

10,164 ✔
614
        // if createForeignKeys is true, we must drop created foreign keys in down query.
10,164 ✔
615
        // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
10,164 ✔
616
        if (createForeignKeys)
10,164 ✔
617
            table.foreignKeys.forEach((foreignKey) =>
10,168 ✔
618
                downQueries.push(this.dropForeignKeySql(table, foreignKey)),
110 ✔
619
            )
110 ✔
620

10,164 ✔
621
        if (createIndices) {
10,164 ✔
622
            table.indices.forEach((index) => {
10,164 ✔
623
                // new index may be passed without name. In this case we generate index name manually.
4,444 ✔
624
                if (!index.name)
4,444 ✔
625
                    index.name = this.connection.namingStrategy.indexName(
4,444 ✔
626
                        table,
6 ✔
627
                        index.columnNames,
6 ✔
628
                        index.where,
6 ✔
629
                    )
6 ✔
630
                upQueries.push(this.createIndexSql(table, index))
4,444 ✔
631
                downQueries.push(this.dropIndexSql(table, index))
4,444 ✔
632
            })
10,164 ✔
633
        }
10,164 ✔
634

10,164 ✔
635
        // if table have column with generated type, we must add the expression to the metadata table
10,164 ✔
636
        const generatedColumns = table.columns.filter(
10,164 ✔
637
            (column) => column.generatedType && column.asExpression,
10,164 ✔
638
        )
10,164 ✔
639

10,164 ✔
640
        for (const column of generatedColumns) {
10,168 ✔
641
            const parsedTableName = this.driver.parseTableName(table)
56 ✔
642

56 ✔
643
            if (!parsedTableName.schema) {
56 !
644
                parsedTableName.schema = await this.getCurrentSchema()
×
645
            }
×
646

56 ✔
647
            const insertQuery = this.insertTypeormMetadataSql({
56 ✔
648
                database: parsedTableName.database,
56 ✔
649
                schema: parsedTableName.schema,
56 ✔
650
                table: parsedTableName.tableName,
56 ✔
651
                type: MetadataTableType.GENERATED_COLUMN,
56 ✔
652
                name: column.name,
56 ✔
653
                value: column.asExpression,
56 ✔
654
            })
56 ✔
655

56 ✔
656
            const deleteQuery = this.deleteTypeormMetadataSql({
56 ✔
657
                database: parsedTableName.database,
56 ✔
658
                schema: parsedTableName.schema,
56 ✔
659
                table: parsedTableName.tableName,
56 ✔
660
                type: MetadataTableType.GENERATED_COLUMN,
56 ✔
661
                name: column.name,
56 ✔
662
            })
56 ✔
663

56 ✔
664
            upQueries.push(insertQuery)
56 ✔
665
            downQueries.push(deleteQuery)
56 ✔
666
        }
56 ✔
667

10,164 ✔
668
        await this.executeQueries(upQueries, downQueries)
10,164 ✔
669
    }
10,164 ✔
670

26 ✔
671
    /**
26 ✔
672
     * Drops the table.
26 ✔
673
     */
26 ✔
674
    async dropTable(
26 ✔
675
        tableOrName: Table | string,
24 ✔
676
        ifExist?: boolean,
24 ✔
677
        dropForeignKeys: boolean = true,
24 ✔
678
        dropIndices: boolean = true,
24 ✔
679
    ): Promise<void> {
24 ✔
680
        if (ifExist) {
24 ✔
681
            const isTableExist = await this.hasTable(tableOrName)
4 ✔
682
            if (!isTableExist) return Promise.resolve()
4 !
683
        }
4 ✔
684

24 ✔
685
        // if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
24 ✔
686
        const createForeignKeys: boolean = dropForeignKeys
24 ✔
687
        const table = InstanceChecker.isTable(tableOrName)
24 ✔
688
            ? tableOrName
24 ✔
689
            : await this.getCachedTable(tableOrName)
24 ✔
690
        const upQueries: Query[] = []
16 ✔
691
        const downQueries: Query[] = []
16 ✔
692

16 ✔
693
        // It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
16 ✔
694
        // to perform drop queries for foreign keys and indices.
16 ✔
695

16 ✔
696
        if (dropIndices) {
24 ✔
697
            table.indices.forEach((index) => {
24 ✔
698
                upQueries.push(this.dropIndexSql(table, index))
2 ✔
699
                downQueries.push(this.createIndexSql(table, index))
2 ✔
700
            })
24 ✔
701
        }
24 ✔
702

24 ✔
703
        // if dropForeignKeys is true, we just drop the table, otherwise we also drop table foreign keys.
24 ✔
704
        // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
24 ✔
705
        if (dropForeignKeys)
24 ✔
706
            table.foreignKeys.forEach((foreignKey) =>
24 ✔
707
                upQueries.push(this.dropForeignKeySql(table, foreignKey)),
20 ✔
708
            )
20 ✔
709

24 ✔
710
        upQueries.push(this.dropTableSql(table))
24 ✔
711
        downQueries.push(this.createTableSql(table, createForeignKeys))
24 ✔
712

24 ✔
713
        // if table had columns with generated type, we must remove the expression from the metadata table
24 ✔
714
        const generatedColumns = table.columns.filter(
24 ✔
715
            (column) => column.generatedType && column.asExpression,
24 ✔
716
        )
24 ✔
717

24 ✔
718
        for (const column of generatedColumns) {
24 ✔
719
            const parsedTableName = this.driver.parseTableName(table)
8 ✔
720

8 ✔
721
            if (!parsedTableName.schema) {
8 !
722
                parsedTableName.schema = await this.getCurrentSchema()
×
723
            }
×
724

8 ✔
725
            const deleteQuery = this.deleteTypeormMetadataSql({
8 ✔
726
                database: parsedTableName.database,
8 ✔
727
                schema: parsedTableName.schema,
8 ✔
728
                table: parsedTableName.tableName,
8 ✔
729
                type: MetadataTableType.GENERATED_COLUMN,
8 ✔
730
                name: column.name,
8 ✔
731
            })
8 ✔
732

8 ✔
733
            const insertQuery = this.insertTypeormMetadataSql({
8 ✔
734
                database: parsedTableName.database,
8 ✔
735
                schema: parsedTableName.schema,
8 ✔
736
                table: parsedTableName.tableName,
8 ✔
737
                type: MetadataTableType.GENERATED_COLUMN,
8 ✔
738
                name: column.name,
8 ✔
739
                value: column.asExpression,
8 ✔
740
            })
8 ✔
741

8 ✔
742
            upQueries.push(deleteQuery)
8 ✔
743
            downQueries.push(insertQuery)
8 ✔
744
        }
8 ✔
745

24 ✔
746
        await this.executeQueries(upQueries, downQueries)
24 ✔
747
    }
24 ✔
748

26 ✔
749
    /**
26 ✔
750
     * Creates a new view.
26 ✔
751
     */
26 ✔
752
    async createView(
26 ✔
753
        view: View,
16 ✔
754
        syncWithMetadata: boolean = false,
16 ✔
755
    ): Promise<void> {
16 ✔
756
        const upQueries: Query[] = []
16 ✔
757
        const downQueries: Query[] = []
16 ✔
758
        upQueries.push(this.createViewSql(view))
16 ✔
759
        if (syncWithMetadata)
16 ✔
760
            upQueries.push(await this.insertViewDefinitionSql(view))
16 ✔
761
        downQueries.push(this.dropViewSql(view))
16 ✔
762
        if (syncWithMetadata)
16 ✔
763
            downQueries.push(await this.deleteViewDefinitionSql(view))
16 ✔
764
        await this.executeQueries(upQueries, downQueries)
16 ✔
765
    }
16 ✔
766

26 ✔
767
    /**
26 ✔
768
     * Drops the view.
26 ✔
769
     */
26 ✔
770
    async dropView(target: View | string): Promise<void> {
26 ✔
771
        const viewName = InstanceChecker.isView(target) ? target.name : target
×
772
        const view = await this.getCachedView(viewName)
×
773

×
774
        const upQueries: Query[] = []
×
775
        const downQueries: Query[] = []
×
776
        upQueries.push(await this.deleteViewDefinitionSql(view))
×
777
        upQueries.push(this.dropViewSql(view))
×
778
        downQueries.push(await this.insertViewDefinitionSql(view))
×
779
        downQueries.push(this.createViewSql(view))
×
780
        await this.executeQueries(upQueries, downQueries)
×
781
    }
×
782

26 ✔
783
    /**
26 ✔
784
     * Renames a table.
26 ✔
785
     */
26 ✔
786
    async renameTable(
26 ✔
787
        oldTableOrName: Table | string,
34 ✔
788
        newTableName: string,
34 ✔
789
    ): Promise<void> {
34 ✔
790
        const upQueries: Query[] = []
34 ✔
791
        const downQueries: Query[] = []
34 ✔
792
        const oldTable = InstanceChecker.isTable(oldTableOrName)
34 ✔
793
            ? oldTableOrName
34 ✔
794
            : await this.getCachedTable(oldTableOrName)
34 ✔
795
        const newTable = oldTable.clone()
30 ✔
796

30 ✔
797
        // we need database name and schema name to rename FK constraints
30 ✔
798
        let dbName: string | undefined = undefined
30 ✔
799
        let schemaName: string | undefined = undefined
30 ✔
800
        let oldTableName: string = oldTable.name
30 ✔
801
        const splittedName = oldTable.name.split(".")
30 ✔
802
        if (splittedName.length === 3) {
34 ✔
803
            dbName = splittedName[0]
4 ✔
804
            oldTableName = splittedName[2]
4 ✔
805
            if (splittedName[1] !== "") schemaName = splittedName[1]
4 ✔
806
        } else if (splittedName.length === 2) {
34 !
807
            schemaName = splittedName[0]
×
808
            oldTableName = splittedName[1]
×
809
        }
×
810

34 ✔
811
        newTable.name = this.driver.buildTableName(
34 ✔
812
            newTableName,
34 ✔
813
            schemaName,
34 ✔
814
            dbName,
34 ✔
815
        )
34 ✔
816

34 ✔
817
        // if we have tables with database which differs from database specified in config, we must change currently used database.
34 ✔
818
        // This need because we can not rename objects from another database.
34 ✔
819
        const currentDB = await this.getCurrentDatabase()
34 ✔
820
        if (dbName && dbName !== currentDB) {
34 ✔
821
            upQueries.push(new Query(`USE "${dbName}"`))
4 ✔
822
            downQueries.push(new Query(`USE "${currentDB}"`))
4 ✔
823
        }
4 ✔
824

34 ✔
825
        // rename table
34 ✔
826
        upQueries.push(
34 ✔
827
            new Query(
34 ✔
828
                `EXEC sp_rename "${this.getTablePath(
34 ✔
829
                    oldTable,
34 ✔
830
                )}", "${newTableName}"`,
34 ✔
831
            ),
34 ✔
832
        )
34 ✔
833
        downQueries.push(
34 ✔
834
            new Query(
34 ✔
835
                `EXEC sp_rename "${this.getTablePath(
34 ✔
836
                    newTable,
34 ✔
837
                )}", "${oldTableName}"`,
34 ✔
838
            ),
34 ✔
839
        )
34 ✔
840

34 ✔
841
        // rename primary key constraint
34 ✔
842
        if (
34 ✔
843
            newTable.primaryColumns.length > 0 &&
34 ✔
844
            !newTable.primaryColumns[0].primaryKeyConstraintName
34 ✔
845
        ) {
34 ✔
846
            const columnNames = newTable.primaryColumns.map(
26 ✔
847
                (column) => column.name,
26 ✔
848
            )
26 ✔
849

26 ✔
850
            const oldPkName = this.connection.namingStrategy.primaryKeyName(
26 ✔
851
                oldTable,
26 ✔
852
                columnNames,
26 ✔
853
            )
26 ✔
854
            const newPkName = this.connection.namingStrategy.primaryKeyName(
26 ✔
855
                newTable,
26 ✔
856
                columnNames,
26 ✔
857
            )
26 ✔
858

26 ✔
859
            // rename primary constraint
26 ✔
860
            upQueries.push(
26 ✔
861
                new Query(
26 ✔
862
                    `EXEC sp_rename "${this.getTablePath(
26 ✔
863
                        newTable,
26 ✔
864
                    )}.${oldPkName}", "${newPkName}"`,
26 ✔
865
                ),
26 ✔
866
            )
26 ✔
867
            downQueries.push(
26 ✔
868
                new Query(
26 ✔
869
                    `EXEC sp_rename "${this.getTablePath(
26 ✔
870
                        newTable,
26 ✔
871
                    )}.${newPkName}", "${oldPkName}"`,
26 ✔
872
                ),
26 ✔
873
            )
26 ✔
874
        }
26 ✔
875

34 ✔
876
        // rename unique constraints
34 ✔
877
        newTable.uniques.forEach((unique) => {
34 ✔
878
            const oldUniqueName =
10 ✔
879
                this.connection.namingStrategy.uniqueConstraintName(
10 ✔
880
                    oldTable,
10 ✔
881
                    unique.columnNames,
10 ✔
882
                )
10 ✔
883

10 ✔
884
            // Skip renaming if Unique has user defined constraint name
10 ✔
885
            if (unique.name !== oldUniqueName) return
10 ✔
886

6 ✔
887
            // build new constraint name
6 ✔
888
            const newUniqueName =
6 ✔
889
                this.connection.namingStrategy.uniqueConstraintName(
6 ✔
890
                    newTable,
6 ✔
891
                    unique.columnNames,
6 ✔
892
                )
6 ✔
893

6 ✔
894
            // build queries
6 ✔
895
            upQueries.push(
6 ✔
896
                new Query(
6 ✔
897
                    `EXEC sp_rename "${this.getTablePath(newTable)}.${
6 ✔
898
                        unique.name
6 ✔
899
                    }", "${newUniqueName}"`,
6 ✔
900
                ),
6 ✔
901
            )
6 ✔
902
            downQueries.push(
6 ✔
903
                new Query(
6 ✔
904
                    `EXEC sp_rename "${this.getTablePath(
6 ✔
905
                        newTable,
6 ✔
906
                    )}.${newUniqueName}", "${unique.name}"`,
6 ✔
907
                ),
6 ✔
908
            )
6 ✔
909

6 ✔
910
            // replace constraint name
6 ✔
911
            unique.name = newUniqueName
6 ✔
912
        })
34 ✔
913

34 ✔
914
        // rename index constraints
34 ✔
915
        newTable.indices.forEach((index) => {
34 ✔
916
            const oldIndexName = this.connection.namingStrategy.indexName(
22 ✔
917
                oldTable,
22 ✔
918
                index.columnNames,
22 ✔
919
                index.where,
22 ✔
920
            )
22 ✔
921

22 ✔
922
            // Skip renaming if Index has user defined constraint name
22 ✔
923
            if (index.name !== oldIndexName) return
22 ✔
924

10 ✔
925
            // build new constraint name
10 ✔
926
            const newIndexName = this.connection.namingStrategy.indexName(
10 ✔
927
                newTable,
10 ✔
928
                index.columnNames,
10 ✔
929
                index.where,
10 ✔
930
            )
10 ✔
931

10 ✔
932
            // build queries
10 ✔
933
            upQueries.push(
10 ✔
934
                new Query(
10 ✔
935
                    `EXEC sp_rename "${this.getTablePath(newTable)}.${
10 ✔
936
                        index.name
10 ✔
937
                    }", "${newIndexName}", "INDEX"`,
10 ✔
938
                ),
10 ✔
939
            )
10 ✔
940
            downQueries.push(
10 ✔
941
                new Query(
10 ✔
942
                    `EXEC sp_rename "${this.getTablePath(
10 ✔
943
                        newTable,
10 ✔
944
                    )}.${newIndexName}", "${index.name}", "INDEX"`,
10 ✔
945
                ),
10 ✔
946
            )
10 ✔
947

10 ✔
948
            // replace constraint name
10 ✔
949
            index.name = newIndexName
10 ✔
950
        })
34 ✔
951

34 ✔
952
        // rename foreign key constraints
34 ✔
953
        newTable.foreignKeys.forEach((foreignKey) => {
34 ✔
954
            const oldForeignKeyName =
18 ✔
955
                this.connection.namingStrategy.foreignKeyName(
18 ✔
956
                    oldTable,
18 ✔
957
                    foreignKey.columnNames,
18 ✔
958
                    this.getTablePath(foreignKey),
18 ✔
959
                    foreignKey.referencedColumnNames,
18 ✔
960
                )
18 ✔
961

18 ✔
962
            // Skip renaming if foreign key has user defined constraint name
18 ✔
963
            if (foreignKey.name !== oldForeignKeyName) return
18 ✔
964

2 ✔
965
            // build new constraint name
2 ✔
966
            const newForeignKeyName =
2 ✔
967
                this.connection.namingStrategy.foreignKeyName(
2 ✔
968
                    newTable,
2 ✔
969
                    foreignKey.columnNames,
2 ✔
970
                    this.getTablePath(foreignKey),
2 ✔
971
                    foreignKey.referencedColumnNames,
2 ✔
972
                )
2 ✔
973

2 ✔
974
            // build queries
2 ✔
975
            upQueries.push(
2 ✔
976
                new Query(
2 ✔
977
                    `EXEC sp_rename "${this.buildForeignKeyName(
2 ✔
978
                        foreignKey.name!,
2 ✔
979
                        schemaName,
2 ✔
980
                        dbName,
2 ✔
981
                    )}", "${newForeignKeyName}"`,
2 ✔
982
                ),
2 ✔
983
            )
2 ✔
984
            downQueries.push(
2 ✔
985
                new Query(
2 ✔
986
                    `EXEC sp_rename "${this.buildForeignKeyName(
2 ✔
987
                        newForeignKeyName,
2 ✔
988
                        schemaName,
2 ✔
989
                        dbName,
2 ✔
990
                    )}", "${foreignKey.name}"`,
2 ✔
991
                ),
2 ✔
992
            )
2 ✔
993

2 ✔
994
            // replace constraint name
2 ✔
995
            foreignKey.name = newForeignKeyName
2 ✔
996
        })
34 ✔
997

34 ✔
998
        // change currently used database back to default db.
34 ✔
999
        if (dbName && dbName !== currentDB) {
34 ✔
1000
            upQueries.push(new Query(`USE "${currentDB}"`))
4 ✔
1001
            downQueries.push(new Query(`USE "${dbName}"`))
4 ✔
1002
        }
4 ✔
1003

34 ✔
1004
        await this.executeQueries(upQueries, downQueries)
34 ✔
1005

34 ✔
1006
        // rename old table and replace it in cached tabled;
34 ✔
1007
        oldTable.name = newTable.name
34 ✔
1008
        this.replaceCachedTable(oldTable, newTable)
34 ✔
1009
    }
34 ✔
1010

26 ✔
1011
    /**
26 ✔
1012
     * Creates a new column from the column in the table.
26 ✔
1013
     */
26 ✔
1014
    async addColumn(
26 ✔
1015
        tableOrName: Table | string,
74 ✔
1016
        column: TableColumn,
74 ✔
1017
    ): Promise<void> {
74 ✔
1018
        const table = InstanceChecker.isTable(tableOrName)
74 ✔
1019
            ? tableOrName
74 ✔
1020
            : await this.getCachedTable(tableOrName)
74 ✔
1021
        const clonedTable = table.clone()
4 ✔
1022
        const upQueries: Query[] = []
4 ✔
1023
        const downQueries: Query[] = []
4 ✔
1024

4 ✔
1025
        upQueries.push(
4 ✔
1026
            new Query(
4 ✔
1027
                `ALTER TABLE ${this.escapePath(
4 ✔
1028
                    table,
4 ✔
1029
                )} ADD ${this.buildCreateColumnSql(
4 ✔
1030
                    table,
4 ✔
1031
                    column,
4 ✔
1032
                    false,
4 ✔
1033
                    true,
4 ✔
1034
                )}`,
4 ✔
1035
            ),
4 ✔
1036
        )
4 ✔
1037
        downQueries.push(
4 ✔
1038
            new Query(
4 ✔
1039
                `ALTER TABLE ${this.escapePath(table)} DROP COLUMN "${
4 ✔
1040
                    column.name
4 ✔
1041
                }"`,
4 ✔
1042
            ),
4 ✔
1043
        )
4 ✔
1044

4 ✔
1045
        // create or update primary key constraint
4 ✔
1046
        if (column.isPrimary) {
74 ✔
1047
            const primaryColumns = clonedTable.primaryColumns
14 ✔
1048
            // if table already have primary key, me must drop it and recreate again
14 ✔
1049
            if (primaryColumns.length > 0) {
14 ✔
1050
                const pkName = primaryColumns[0].primaryKeyConstraintName
4 ✔
1051
                    ? primaryColumns[0].primaryKeyConstraintName
4 !
1052
                    : this.connection.namingStrategy.primaryKeyName(
4 ✔
1053
                          clonedTable,
4 ✔
1054
                          primaryColumns.map((column) => column.name),
4 ✔
1055
                      )
4 ✔
1056

4 ✔
1057
                const columnNames = primaryColumns
4 ✔
1058
                    .map((column) => `"${column.name}"`)
4 ✔
1059
                    .join(", ")
4 ✔
1060

4 ✔
1061
                upQueries.push(
4 ✔
1062
                    new Query(
4 ✔
1063
                        `ALTER TABLE ${this.escapePath(
4 ✔
1064
                            table,
4 ✔
1065
                        )} DROP CONSTRAINT "${pkName}"`,
4 ✔
1066
                    ),
4 ✔
1067
                )
4 ✔
1068
                downQueries.push(
4 ✔
1069
                    new Query(
4 ✔
1070
                        `ALTER TABLE ${this.escapePath(
4 ✔
1071
                            table,
4 ✔
1072
                        )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
4 ✔
1073
                    ),
4 ✔
1074
                )
4 ✔
1075
            }
4 ✔
1076

14 ✔
1077
            primaryColumns.push(column)
14 ✔
1078
            const pkName = primaryColumns[0].primaryKeyConstraintName
14 ✔
1079
                ? primaryColumns[0].primaryKeyConstraintName
14 !
1080
                : this.connection.namingStrategy.primaryKeyName(
14 ✔
1081
                      clonedTable,
14 ✔
1082
                      primaryColumns.map((column) => column.name),
14 ✔
1083
                  )
14 ✔
1084

14 ✔
1085
            const columnNames = primaryColumns
14 ✔
1086
                .map((column) => `"${column.name}"`)
14 ✔
1087
                .join(", ")
14 ✔
1088
            upQueries.push(
14 ✔
1089
                new Query(
14 ✔
1090
                    `ALTER TABLE ${this.escapePath(
14 ✔
1091
                        table,
14 ✔
1092
                    )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
14 ✔
1093
                ),
14 ✔
1094
            )
14 ✔
1095
            downQueries.push(
14 ✔
1096
                new Query(
14 ✔
1097
                    `ALTER TABLE ${this.escapePath(
14 ✔
1098
                        table,
14 ✔
1099
                    )} DROP CONSTRAINT "${pkName}"`,
14 ✔
1100
                ),
14 ✔
1101
            )
14 ✔
1102
        }
14 ✔
1103

74 ✔
1104
        // create column index
74 ✔
1105
        const columnIndex = clonedTable.indices.find(
74 ✔
1106
            (index) =>
74 ✔
1107
                index.columnNames.length === 1 &&
2 ✔
1108
                index.columnNames[0] === column.name,
74 ✔
1109
        )
74 ✔
1110
        if (columnIndex) {
74 !
1111
            upQueries.push(this.createIndexSql(table, columnIndex))
×
1112
            downQueries.push(this.dropIndexSql(table, columnIndex))
×
1113
        }
×
1114

74 ✔
1115
        // create unique constraint
74 ✔
1116
        if (column.isUnique) {
74 ✔
1117
            const uniqueConstraint = new TableUnique({
6 ✔
1118
                name: this.connection.namingStrategy.uniqueConstraintName(
6 ✔
1119
                    table,
6 ✔
1120
                    [column.name],
6 ✔
1121
                ),
6 ✔
1122
                columnNames: [column.name],
6 ✔
1123
            })
6 ✔
1124
            clonedTable.uniques.push(uniqueConstraint)
6 ✔
1125
            upQueries.push(
6 ✔
1126
                new Query(
6 ✔
1127
                    `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${
6 ✔
1128
                        uniqueConstraint.name
6 ✔
1129
                    }" UNIQUE ("${column.name}")`,
6 ✔
1130
                ),
6 ✔
1131
            )
6 ✔
1132
            downQueries.push(
6 ✔
1133
                new Query(
6 ✔
1134
                    `ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${
6 ✔
1135
                        uniqueConstraint.name
6 ✔
1136
                    }"`,
6 ✔
1137
                ),
6 ✔
1138
            )
6 ✔
1139
        }
6 ✔
1140

74 ✔
1141
        // remove default constraint
74 ✔
1142
        if (column.default !== null && column.default !== undefined) {
74 ✔
1143
            const defaultName =
10 ✔
1144
                this.connection.namingStrategy.defaultConstraintName(
10 ✔
1145
                    table,
10 ✔
1146
                    column.name,
10 ✔
1147
                )
10 ✔
1148
            downQueries.push(
10 ✔
1149
                new Query(
10 ✔
1150
                    `ALTER TABLE ${this.escapePath(
10 ✔
1151
                        table,
10 ✔
1152
                    )} DROP CONSTRAINT "${defaultName}"`,
10 ✔
1153
                ),
10 ✔
1154
            )
10 ✔
1155
        }
10 ✔
1156

74 ✔
1157
        if (column.generatedType && column.asExpression) {
74 ✔
1158
            const parsedTableName = this.driver.parseTableName(table)
6 ✔
1159

6 ✔
1160
            if (!parsedTableName.schema) {
6 !
1161
                parsedTableName.schema = await this.getCurrentSchema()
×
1162
            }
×
1163

6 ✔
1164
            const insertQuery = this.insertTypeormMetadataSql({
6 ✔
1165
                database: parsedTableName.database,
6 ✔
1166
                schema: parsedTableName.schema,
6 ✔
1167
                table: parsedTableName.tableName,
6 ✔
1168
                type: MetadataTableType.GENERATED_COLUMN,
6 ✔
1169
                name: column.name,
6 ✔
1170
                value: column.asExpression,
6 ✔
1171
            })
6 ✔
1172

6 ✔
1173
            const deleteQuery = this.deleteTypeormMetadataSql({
6 ✔
1174
                database: parsedTableName.database,
6 ✔
1175
                schema: parsedTableName.schema,
6 ✔
1176
                table: parsedTableName.tableName,
6 ✔
1177
                type: MetadataTableType.GENERATED_COLUMN,
6 ✔
1178
                name: column.name,
6 ✔
1179
            })
6 ✔
1180

6 ✔
1181
            upQueries.push(insertQuery)
6 ✔
1182
            downQueries.push(deleteQuery)
6 ✔
1183
        }
6 ✔
1184

74 ✔
1185
        await this.executeQueries(upQueries, downQueries)
74 ✔
1186

70 ✔
1187
        clonedTable.addColumn(column)
70 ✔
1188
        this.replaceCachedTable(table, clonedTable)
70 ✔
1189
    }
70 ✔
1190

26 ✔
1191
    /**
26 ✔
1192
     * Creates a new columns from the column in the table.
26 ✔
1193
     */
26 ✔
1194
    async addColumns(
26 ✔
1195
        tableOrName: Table | string,
12 ✔
1196
        columns: TableColumn[],
12 ✔
1197
    ): Promise<void> {
12 ✔
1198
        for (const column of columns) {
12 ✔
1199
            await this.addColumn(tableOrName, column)
14 ✔
1200
        }
12 ✔
1201
    }
10 ✔
1202

26 ✔
1203
    /**
26 ✔
1204
     * Renames column in the given table.
26 ✔
1205
     */
26 ✔
1206
    async renameColumn(
26 ✔
1207
        tableOrName: Table | string,
28 ✔
1208
        oldTableColumnOrName: TableColumn | string,
28 ✔
1209
        newTableColumnOrName: TableColumn | string,
28 ✔
1210
    ): Promise<void> {
28 ✔
1211
        const table = InstanceChecker.isTable(tableOrName)
28 ✔
1212
            ? tableOrName
28 ✔
1213
            : await this.getCachedTable(tableOrName)
28 ✔
1214
        const oldColumn = InstanceChecker.isTableColumn(oldTableColumnOrName)
4 ✔
1215
            ? oldTableColumnOrName
28 ✔
1216
            : table.columns.find((c) => c.name === oldTableColumnOrName)
28 ✔
1217
        if (!oldColumn)
28 ✔
1218
            throw new TypeORMError(
28 !
1219
                `Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`,
×
1220
            )
×
1221

28 ✔
1222
        let newColumn: TableColumn | undefined = undefined
28 ✔
1223
        if (InstanceChecker.isTableColumn(newTableColumnOrName)) {
28 ✔
1224
            newColumn = newTableColumnOrName
18 ✔
1225
        } else {
28 ✔
1226
            newColumn = oldColumn.clone()
10 ✔
1227
            newColumn.name = newTableColumnOrName
10 ✔
1228
        }
10 ✔
1229

28 ✔
1230
        await this.changeColumn(table, oldColumn, newColumn)
28 ✔
1231
    }
28 ✔
1232

26 ✔
1233
    /**
26 ✔
1234
     * Changes a column in the table.
26 ✔
1235
     */
26 ✔
1236
    async changeColumn(
26 ✔
1237
        tableOrName: Table | string,
102 ✔
1238
        oldTableColumnOrName: TableColumn | string,
102 ✔
1239
        newColumn: TableColumn,
102 ✔
1240
    ): Promise<void> {
102 ✔
1241
        const table = InstanceChecker.isTable(tableOrName)
102 ✔
1242
            ? tableOrName
102 ✔
1243
            : await this.getCachedTable(tableOrName)
102 !
1244
        let clonedTable = table.clone()
×
1245
        const upQueries: Query[] = []
×
1246
        const downQueries: Query[] = []
×
1247

×
1248
        const oldColumn = InstanceChecker.isTableColumn(oldTableColumnOrName)
×
1249
            ? oldTableColumnOrName
102 ✔
1250
            : table.columns.find(
102 !
1251
                  (column) => column.name === oldTableColumnOrName,
×
1252
              )
102 ✔
1253
        if (!oldColumn)
102 ✔
1254
            throw new TypeORMError(
102 !
1255
                `Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`,
×
1256
            )
×
1257

102 ✔
1258
        if (
102 ✔
1259
            (newColumn.isGenerated !== oldColumn.isGenerated &&
102 ✔
1260
                newColumn.generationStrategy !== "uuid") ||
102 ✔
1261
            newColumn.type !== oldColumn.type ||
102 ✔
1262
            newColumn.length !== oldColumn.length ||
102 ✔
1263
            newColumn.asExpression !== oldColumn.asExpression ||
102 ✔
1264
            newColumn.generatedType !== oldColumn.generatedType
52 ✔
1265
        ) {
102 ✔
1266
            // SQL Server does not support changing of IDENTITY column, so we must drop column and recreate it again.
50 ✔
1267
            // Also, we recreate column if column type changed
50 ✔
1268
            await this.dropColumn(table, oldColumn)
50 ✔
1269
            await this.addColumn(table, newColumn)
50 ✔
1270

50 ✔
1271
            // update cloned table
50 ✔
1272
            clonedTable = table.clone()
50 ✔
1273
        } else {
102 ✔
1274
            if (newColumn.name !== oldColumn.name) {
52 ✔
1275
                // we need database name and schema name to rename FK constraints
28 ✔
1276
                let dbName: string | undefined = undefined
28 ✔
1277
                let schemaName: string | undefined = undefined
28 ✔
1278
                const splittedName = table.name.split(".")
28 ✔
1279
                if (splittedName.length === 3) {
28 ✔
1280
                    dbName = splittedName[0]
4 ✔
1281
                    if (splittedName[1] !== "") schemaName = splittedName[1]
4 ✔
1282
                } else if (splittedName.length === 2) {
28 !
1283
                    schemaName = splittedName[0]
×
1284
                }
×
1285

28 ✔
1286
                // if we have tables with database which differs from database specified in config, we must change currently used database.
28 ✔
1287
                // This need because we can not rename objects from another database.
28 ✔
1288
                const currentDB = await this.getCurrentDatabase()
28 ✔
1289
                if (dbName && dbName !== currentDB) {
28 ✔
1290
                    upQueries.push(new Query(`USE "${dbName}"`))
4 ✔
1291
                    downQueries.push(new Query(`USE "${currentDB}"`))
4 ✔
1292
                }
4 ✔
1293

28 ✔
1294
                // rename the column
28 ✔
1295
                upQueries.push(
28 ✔
1296
                    new Query(
28 ✔
1297
                        `EXEC sp_rename "${this.getTablePath(table)}.${
28 ✔
1298
                            oldColumn.name
28 ✔
1299
                        }", "${newColumn.name}"`,
28 ✔
1300
                    ),
28 ✔
1301
                )
28 ✔
1302
                downQueries.push(
28 ✔
1303
                    new Query(
28 ✔
1304
                        `EXEC sp_rename "${this.getTablePath(table)}.${
28 ✔
1305
                            newColumn.name
28 ✔
1306
                        }", "${oldColumn.name}"`,
28 ✔
1307
                    ),
28 ✔
1308
                )
28 ✔
1309

28 ✔
1310
                // rename column primary key constraint
28 ✔
1311
                if (
28 ✔
1312
                    oldColumn.isPrimary === true &&
28 ✔
1313
                    !oldColumn.primaryKeyConstraintName
6 ✔
1314
                ) {
28 ✔
1315
                    const primaryColumns = clonedTable.primaryColumns
2 ✔
1316

2 ✔
1317
                    // build old primary constraint name
2 ✔
1318
                    const columnNames = primaryColumns.map(
2 ✔
1319
                        (column) => column.name,
2 ✔
1320
                    )
2 ✔
1321
                    const oldPkName =
2 ✔
1322
                        this.connection.namingStrategy.primaryKeyName(
2 ✔
1323
                            clonedTable,
2 ✔
1324
                            columnNames,
2 ✔
1325
                        )
2 ✔
1326

2 ✔
1327
                    // replace old column name with new column name
2 ✔
1328
                    columnNames.splice(columnNames.indexOf(oldColumn.name), 1)
2 ✔
1329
                    columnNames.push(newColumn.name)
2 ✔
1330

2 ✔
1331
                    // build new primary constraint name
2 ✔
1332
                    const newPkName =
2 ✔
1333
                        this.connection.namingStrategy.primaryKeyName(
2 ✔
1334
                            clonedTable,
2 ✔
1335
                            columnNames,
2 ✔
1336
                        )
2 ✔
1337

2 ✔
1338
                    // rename primary constraint
2 ✔
1339
                    upQueries.push(
2 ✔
1340
                        new Query(
2 ✔
1341
                            `EXEC sp_rename "${this.getTablePath(
2 ✔
1342
                                clonedTable,
2 ✔
1343
                            )}.${oldPkName}", "${newPkName}"`,
2 ✔
1344
                        ),
2 ✔
1345
                    )
2 ✔
1346
                    downQueries.push(
2 ✔
1347
                        new Query(
2 ✔
1348
                            `EXEC sp_rename "${this.getTablePath(
2 ✔
1349
                                clonedTable,
2 ✔
1350
                            )}.${newPkName}", "${oldPkName}"`,
2 ✔
1351
                        ),
2 ✔
1352
                    )
2 ✔
1353
                }
2 ✔
1354

28 ✔
1355
                // rename index constraints
28 ✔
1356
                clonedTable.findColumnIndices(oldColumn).forEach((index) => {
28 ✔
1357
                    const oldIndexName =
6 ✔
1358
                        this.connection.namingStrategy.indexName(
6 ✔
1359
                            clonedTable,
6 ✔
1360
                            index.columnNames,
6 ✔
1361
                            index.where,
6 ✔
1362
                        )
6 ✔
1363

6 ✔
1364
                    // Skip renaming if Index has user defined constraint name
6 ✔
1365
                    if (index.name !== oldIndexName) return
6 ✔
1366

2 ✔
1367
                    // build new constraint name
2 ✔
1368
                    index.columnNames.splice(
2 ✔
1369
                        index.columnNames.indexOf(oldColumn.name),
2 ✔
1370
                        1,
2 ✔
1371
                    )
2 ✔
1372
                    index.columnNames.push(newColumn.name)
2 ✔
1373
                    const newIndexName =
2 ✔
1374
                        this.connection.namingStrategy.indexName(
2 ✔
1375
                            clonedTable,
2 ✔
1376
                            index.columnNames,
2 ✔
1377
                            index.where,
2 ✔
1378
                        )
2 ✔
1379

2 ✔
1380
                    // build queries
2 ✔
1381
                    upQueries.push(
2 ✔
1382
                        new Query(
2 ✔
1383
                            `EXEC sp_rename "${this.getTablePath(
2 ✔
1384
                                clonedTable,
2 ✔
1385
                            )}.${index.name}", "${newIndexName}", "INDEX"`,
2 ✔
1386
                        ),
2 ✔
1387
                    )
2 ✔
1388
                    downQueries.push(
2 ✔
1389
                        new Query(
2 ✔
1390
                            `EXEC sp_rename "${this.getTablePath(
2 ✔
1391
                                clonedTable,
2 ✔
1392
                            )}.${newIndexName}", "${index.name}", "INDEX"`,
2 ✔
1393
                        ),
2 ✔
1394
                    )
2 ✔
1395

2 ✔
1396
                    // replace constraint name
2 ✔
1397
                    index.name = newIndexName
2 ✔
1398
                })
28 ✔
1399

28 ✔
1400
                // rename foreign key constraints
28 ✔
1401
                clonedTable
28 ✔
1402
                    .findColumnForeignKeys(oldColumn)
28 ✔
1403
                    .forEach((foreignKey) => {
28 ✔
1404
                        const foreignKeyName =
2 ✔
1405
                            this.connection.namingStrategy.foreignKeyName(
2 ✔
1406
                                clonedTable,
2 ✔
1407
                                foreignKey.columnNames,
2 ✔
1408
                                this.getTablePath(foreignKey),
2 ✔
1409
                                foreignKey.referencedColumnNames,
2 ✔
1410
                            )
2 ✔
1411

2 ✔
1412
                        // Skip renaming if foreign key has user defined constraint name
2 ✔
1413
                        if (foreignKey.name !== foreignKeyName) return
2 !
1414

2 ✔
1415
                        // build new constraint name
2 ✔
1416
                        foreignKey.columnNames.splice(
2 ✔
1417
                            foreignKey.columnNames.indexOf(oldColumn.name),
2 ✔
1418
                            1,
2 ✔
1419
                        )
2 ✔
1420
                        foreignKey.columnNames.push(newColumn.name)
2 ✔
1421
                        const newForeignKeyName =
2 ✔
1422
                            this.connection.namingStrategy.foreignKeyName(
2 ✔
1423
                                clonedTable,
2 ✔
1424
                                foreignKey.columnNames,
2 ✔
1425
                                this.getTablePath(foreignKey),
2 ✔
1426
                                foreignKey.referencedColumnNames,
2 ✔
1427
                            )
2 ✔
1428

2 ✔
1429
                        // build queries
2 ✔
1430
                        upQueries.push(
2 ✔
1431
                            new Query(
2 ✔
1432
                                `EXEC sp_rename "${this.buildForeignKeyName(
2 ✔
1433
                                    foreignKey.name!,
2 ✔
1434
                                    schemaName,
2 ✔
1435
                                    dbName,
2 ✔
1436
                                )}", "${newForeignKeyName}"`,
2 ✔
1437
                            ),
2 ✔
1438
                        )
2 ✔
1439
                        downQueries.push(
2 ✔
1440
                            new Query(
2 ✔
1441
                                `EXEC sp_rename "${this.buildForeignKeyName(
2 ✔
1442
                                    newForeignKeyName,
2 ✔
1443
                                    schemaName,
2 ✔
1444
                                    dbName,
2 ✔
1445
                                )}", "${foreignKey.name}"`,
2 ✔
1446
                            ),
2 ✔
1447
                        )
2 ✔
1448

2 ✔
1449
                        // replace constraint name
2 ✔
1450
                        foreignKey.name = newForeignKeyName
2 ✔
1451
                    })
28 ✔
1452

28 ✔
1453
                // rename check constraints
28 ✔
1454
                clonedTable.findColumnChecks(oldColumn).forEach((check) => {
28 ✔
1455
                    // build new constraint name
×
1456
                    check.columnNames!.splice(
×
1457
                        check.columnNames!.indexOf(oldColumn.name),
×
1458
                        1,
×
1459
                    )
×
1460
                    check.columnNames!.push(newColumn.name)
×
1461
                    const newCheckName =
×
1462
                        this.connection.namingStrategy.checkConstraintName(
×
1463
                            clonedTable,
×
1464
                            check.expression!,
×
1465
                        )
×
1466

×
1467
                    // build queries
×
1468
                    upQueries.push(
×
1469
                        new Query(
×
1470
                            `EXEC sp_rename "${this.getTablePath(
×
1471
                                clonedTable,
×
1472
                            )}.${check.name}", "${newCheckName}"`,
×
1473
                        ),
×
1474
                    )
×
1475
                    downQueries.push(
×
1476
                        new Query(
×
1477
                            `EXEC sp_rename "${this.getTablePath(
×
1478
                                clonedTable,
×
1479
                            )}.${newCheckName}", "${check.name}"`,
×
1480
                        ),
×
1481
                    )
×
1482

×
1483
                    // replace constraint name
×
1484
                    check.name = newCheckName
×
1485
                })
28 ✔
1486

28 ✔
1487
                // rename unique constraints
28 ✔
1488
                clonedTable.findColumnUniques(oldColumn).forEach((unique) => {
28 ✔
1489
                    const oldUniqueName =
12 ✔
1490
                        this.connection.namingStrategy.uniqueConstraintName(
12 ✔
1491
                            clonedTable,
12 ✔
1492
                            unique.columnNames,
12 ✔
1493
                        )
12 ✔
1494

12 ✔
1495
                    // Skip renaming if Unique has user defined constraint name
12 ✔
1496
                    if (unique.name !== oldUniqueName) return
12 ✔
1497

8 ✔
1498
                    // build new constraint name
8 ✔
1499
                    unique.columnNames.splice(
8 ✔
1500
                        unique.columnNames.indexOf(oldColumn.name),
8 ✔
1501
                        1,
8 ✔
1502
                    )
8 ✔
1503
                    unique.columnNames.push(newColumn.name)
8 ✔
1504
                    const newUniqueName =
8 ✔
1505
                        this.connection.namingStrategy.uniqueConstraintName(
8 ✔
1506
                            clonedTable,
8 ✔
1507
                            unique.columnNames,
8 ✔
1508
                        )
8 ✔
1509

8 ✔
1510
                    // build queries
8 ✔
1511
                    upQueries.push(
8 ✔
1512
                        new Query(
8 ✔
1513
                            `EXEC sp_rename "${this.getTablePath(
8 ✔
1514
                                clonedTable,
8 ✔
1515
                            )}.${unique.name}", "${newUniqueName}"`,
8 ✔
1516
                        ),
8 ✔
1517
                    )
8 ✔
1518
                    downQueries.push(
8 ✔
1519
                        new Query(
8 ✔
1520
                            `EXEC sp_rename "${this.getTablePath(
8 ✔
1521
                                clonedTable,
8 ✔
1522
                            )}.${newUniqueName}", "${unique.name}"`,
8 ✔
1523
                        ),
8 ✔
1524
                    )
8 ✔
1525

8 ✔
1526
                    // replace constraint name
8 ✔
1527
                    unique.name = newUniqueName
8 ✔
1528
                })
28 ✔
1529

28 ✔
1530
                // rename default constraints
28 ✔
1531
                if (
28 ✔
1532
                    oldColumn.default !== null &&
28 ✔
1533
                    oldColumn.default !== undefined
28 ✔
1534
                ) {
28 ✔
1535
                    const oldDefaultName =
4 ✔
1536
                        this.connection.namingStrategy.defaultConstraintName(
4 ✔
1537
                            table,
4 ✔
1538
                            oldColumn.name,
4 ✔
1539
                        )
4 ✔
1540
                    const newDefaultName =
4 ✔
1541
                        this.connection.namingStrategy.defaultConstraintName(
4 ✔
1542
                            table,
4 ✔
1543
                            newColumn.name,
4 ✔
1544
                        )
4 ✔
1545

4 ✔
1546
                    upQueries.push(
4 ✔
1547
                        new Query(
4 ✔
1548
                            `ALTER TABLE ${this.escapePath(
4 ✔
1549
                                table,
4 ✔
1550
                            )} DROP CONSTRAINT "${oldDefaultName}"`,
4 ✔
1551
                        ),
4 ✔
1552
                    )
4 ✔
1553
                    downQueries.push(
4 ✔
1554
                        new Query(
4 ✔
1555
                            `ALTER TABLE ${this.escapePath(
4 ✔
1556
                                table,
4 ✔
1557
                            )} ADD CONSTRAINT "${oldDefaultName}" DEFAULT ${
4 ✔
1558
                                oldColumn.default
4 ✔
1559
                            } FOR "${newColumn.name}"`,
4 ✔
1560
                        ),
4 ✔
1561
                    )
4 ✔
1562

4 ✔
1563
                    upQueries.push(
4 ✔
1564
                        new Query(
4 ✔
1565
                            `ALTER TABLE ${this.escapePath(
4 ✔
1566
                                table,
4 ✔
1567
                            )} ADD CONSTRAINT "${newDefaultName}" DEFAULT ${
4 ✔
1568
                                oldColumn.default
4 ✔
1569
                            } FOR "${newColumn.name}"`,
4 ✔
1570
                        ),
4 ✔
1571
                    )
4 ✔
1572
                    downQueries.push(
4 ✔
1573
                        new Query(
4 ✔
1574
                            `ALTER TABLE ${this.escapePath(
4 ✔
1575
                                table,
4 ✔
1576
                            )} DROP CONSTRAINT "${newDefaultName}"`,
4 ✔
1577
                        ),
4 ✔
1578
                    )
4 ✔
1579
                }
4 ✔
1580

28 ✔
1581
                // change currently used database back to default db.
28 ✔
1582
                if (dbName && dbName !== currentDB) {
28 ✔
1583
                    upQueries.push(new Query(`USE "${currentDB}"`))
4 ✔
1584
                    downQueries.push(new Query(`USE "${dbName}"`))
4 ✔
1585
                }
4 ✔
1586

28 ✔
1587
                // rename old column in the Table object
28 ✔
1588
                const oldTableColumn = clonedTable.columns.find(
28 ✔
1589
                    (column) => column.name === oldColumn.name,
28 ✔
1590
                )
28 ✔
1591
                clonedTable.columns[
28 ✔
1592
                    clonedTable.columns.indexOf(oldTableColumn!)
28 ✔
1593
                ].name = newColumn.name
28 ✔
1594
                oldColumn.name = newColumn.name
28 ✔
1595
            }
28 ✔
1596

52 ✔
1597
            if (
52 ✔
1598
                this.isColumnChanged(oldColumn, newColumn, false, false, false)
52 ✔
1599
            ) {
52 !
1600
                upQueries.push(
×
1601
                    new Query(
×
1602
                        `ALTER TABLE ${this.escapePath(
×
1603
                            table,
×
1604
                        )} ALTER COLUMN ${this.buildCreateColumnSql(
×
1605
                            table,
×
1606
                            newColumn,
×
1607
                            true,
×
1608
                            false,
×
1609
                            true,
×
1610
                        )}`,
×
1611
                    ),
×
1612
                )
×
1613
                downQueries.push(
×
1614
                    new Query(
×
1615
                        `ALTER TABLE ${this.escapePath(
×
1616
                            table,
×
1617
                        )} ALTER COLUMN ${this.buildCreateColumnSql(
×
1618
                            table,
×
1619
                            oldColumn,
×
1620
                            true,
×
1621
                            false,
×
1622
                            true,
×
1623
                        )}`,
×
1624
                    ),
×
1625
                )
×
1626
            }
×
1627

52 ✔
1628
            if (this.isEnumChanged(oldColumn, newColumn)) {
52 ✔
1629
                const oldExpression = this.getEnumExpression(oldColumn)
2 ✔
1630
                const oldCheck = new TableCheck({
2 ✔
1631
                    name: this.connection.namingStrategy.checkConstraintName(
2 ✔
1632
                        table,
2 ✔
1633
                        oldExpression,
2 ✔
1634
                        true,
2 ✔
1635
                    ),
2 ✔
1636
                    expression: oldExpression,
2 ✔
1637
                })
2 ✔
1638

2 ✔
1639
                const newExpression = this.getEnumExpression(newColumn)
2 ✔
1640
                const newCheck = new TableCheck({
2 ✔
1641
                    name: this.connection.namingStrategy.checkConstraintName(
2 ✔
1642
                        table,
2 ✔
1643
                        newExpression,
2 ✔
1644
                        true,
2 ✔
1645
                    ),
2 ✔
1646
                    expression: newExpression,
2 ✔
1647
                })
2 ✔
1648

2 ✔
1649
                upQueries.push(this.dropCheckConstraintSql(table, oldCheck))
2 ✔
1650
                upQueries.push(this.createCheckConstraintSql(table, newCheck))
2 ✔
1651

2 ✔
1652
                downQueries.push(this.dropCheckConstraintSql(table, newCheck))
2 ✔
1653
                downQueries.push(this.createCheckConstraintSql(table, oldCheck))
2 ✔
1654
            }
2 ✔
1655

52 ✔
1656
            if (newColumn.isPrimary !== oldColumn.isPrimary) {
52 ✔
1657
                const primaryColumns = clonedTable.primaryColumns
6 ✔
1658

6 ✔
1659
                // if primary column state changed, we must always drop existed constraint.
6 ✔
1660
                if (primaryColumns.length > 0) {
6 ✔
1661
                    const pkName = primaryColumns[0].primaryKeyConstraintName
6 ✔
1662
                        ? primaryColumns[0].primaryKeyConstraintName
6 !
1663
                        : this.connection.namingStrategy.primaryKeyName(
6 ✔
1664
                              clonedTable,
6 ✔
1665
                              primaryColumns.map((column) => column.name),
6 ✔
1666
                          )
6 ✔
1667

6 ✔
1668
                    const columnNames = primaryColumns
6 ✔
1669
                        .map((column) => `"${column.name}"`)
6 ✔
1670
                        .join(", ")
6 ✔
1671
                    upQueries.push(
6 ✔
1672
                        new Query(
6 ✔
1673
                            `ALTER TABLE ${this.escapePath(
6 ✔
1674
                                table,
6 ✔
1675
                            )} DROP CONSTRAINT "${pkName}"`,
6 ✔
1676
                        ),
6 ✔
1677
                    )
6 ✔
1678
                    downQueries.push(
6 ✔
1679
                        new Query(
6 ✔
1680
                            `ALTER TABLE ${this.escapePath(
6 ✔
1681
                                table,
6 ✔
1682
                            )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
6 ✔
1683
                        ),
6 ✔
1684
                    )
6 ✔
1685
                }
6 ✔
1686

6 ✔
1687
                if (newColumn.isPrimary === true) {
6 ✔
1688
                    primaryColumns.push(newColumn)
2 ✔
1689
                    // update column in table
2 ✔
1690
                    const column = clonedTable.columns.find(
2 ✔
1691
                        (column) => column.name === newColumn.name,
2 ✔
1692
                    )
2 ✔
1693
                    column!.isPrimary = true
2 ✔
1694
                    const pkName = primaryColumns[0].primaryKeyConstraintName
2 ✔
1695
                        ? primaryColumns[0].primaryKeyConstraintName
2 !
1696
                        : this.connection.namingStrategy.primaryKeyName(
2 ✔
1697
                              clonedTable,
2 ✔
1698
                              primaryColumns.map((column) => column.name),
2 ✔
1699
                          )
2 ✔
1700

2 ✔
1701
                    const columnNames = primaryColumns
2 ✔
1702
                        .map((column) => `"${column.name}"`)
2 ✔
1703
                        .join(", ")
2 ✔
1704
                    upQueries.push(
2 ✔
1705
                        new Query(
2 ✔
1706
                            `ALTER TABLE ${this.escapePath(
2 ✔
1707
                                table,
2 ✔
1708
                            )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
2 ✔
1709
                        ),
2 ✔
1710
                    )
2 ✔
1711
                    downQueries.push(
2 ✔
1712
                        new Query(
2 ✔
1713
                            `ALTER TABLE ${this.escapePath(
2 ✔
1714
                                table,
2 ✔
1715
                            )} DROP CONSTRAINT "${pkName}"`,
2 ✔
1716
                        ),
2 ✔
1717
                    )
2 ✔
1718
                } else {
6 ✔
1719
                    const primaryColumn = primaryColumns.find(
4 ✔
1720
                        (c) => c.name === newColumn.name,
4 ✔
1721
                    )
4 ✔
1722
                    primaryColumns.splice(
4 ✔
1723
                        primaryColumns.indexOf(primaryColumn!),
4 ✔
1724
                        1,
4 ✔
1725
                    )
4 ✔
1726

4 ✔
1727
                    // update column in table
4 ✔
1728
                    const column = clonedTable.columns.find(
4 ✔
1729
                        (column) => column.name === newColumn.name,
4 ✔
1730
                    )
4 ✔
1731
                    column!.isPrimary = false
4 ✔
1732

4 ✔
1733
                    // if we have another primary keys, we must recreate constraint.
4 ✔
1734
                    if (primaryColumns.length > 0) {
4 ✔
1735
                        const pkName = primaryColumns[0]
2 ✔
1736
                            .primaryKeyConstraintName
2 ✔
1737
                            ? primaryColumns[0].primaryKeyConstraintName
2 !
1738
                            : this.connection.namingStrategy.primaryKeyName(
2 ✔
1739
                                  clonedTable,
2 ✔
1740
                                  primaryColumns.map((column) => column.name),
2 ✔
1741
                              )
2 ✔
1742

2 ✔
1743
                        const columnNames = primaryColumns
2 ✔
1744
                            .map((column) => `"${column.name}"`)
2 ✔
1745
                            .join(", ")
2 ✔
1746
                        upQueries.push(
2 ✔
1747
                            new Query(
2 ✔
1748
                                `ALTER TABLE ${this.escapePath(
2 ✔
1749
                                    table,
2 ✔
1750
                                )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
2 ✔
1751
                            ),
2 ✔
1752
                        )
2 ✔
1753
                        downQueries.push(
2 ✔
1754
                            new Query(
2 ✔
1755
                                `ALTER TABLE ${this.escapePath(
2 ✔
1756
                                    table,
2 ✔
1757
                                )} DROP CONSTRAINT "${pkName}"`,
2 ✔
1758
                            ),
2 ✔
1759
                        )
2 ✔
1760
                    }
2 ✔
1761
                }
4 ✔
1762
            }
6 ✔
1763

52 ✔
1764
            if (newColumn.isUnique !== oldColumn.isUnique) {
52 ✔
1765
                if (newColumn.isUnique === true) {
2 ✔
1766
                    const uniqueConstraint = new TableUnique({
2 ✔
1767
                        name: this.connection.namingStrategy.uniqueConstraintName(
2 ✔
1768
                            table,
2 ✔
1769
                            [newColumn.name],
2 ✔
1770
                        ),
2 ✔
1771
                        columnNames: [newColumn.name],
2 ✔
1772
                    })
2 ✔
1773
                    clonedTable.uniques.push(uniqueConstraint)
2 ✔
1774
                    upQueries.push(
2 ✔
1775
                        new Query(
2 ✔
1776
                            `ALTER TABLE ${this.escapePath(
2 ✔
1777
                                table,
2 ✔
1778
                            )} ADD CONSTRAINT "${
2 ✔
1779
                                uniqueConstraint.name
2 ✔
1780
                            }" UNIQUE ("${newColumn.name}")`,
2 ✔
1781
                        ),
2 ✔
1782
                    )
2 ✔
1783
                    downQueries.push(
2 ✔
1784
                        new Query(
2 ✔
1785
                            `ALTER TABLE ${this.escapePath(
2 ✔
1786
                                table,
2 ✔
1787
                            )} DROP CONSTRAINT "${uniqueConstraint.name}"`,
2 ✔
1788
                        ),
2 ✔
1789
                    )
2 ✔
1790
                } else {
2 !
1791
                    const uniqueConstraint = clonedTable.uniques.find(
×
1792
                        (unique) => {
×
1793
                            return (
×
1794
                                unique.columnNames.length === 1 &&
×
1795
                                !!unique.columnNames.find(
×
1796
                                    (columnName) =>
×
1797
                                        columnName === newColumn.name,
×
1798
                                )
×
1799
                            )
×
1800
                        },
×
1801
                    )
×
1802
                    clonedTable.uniques.splice(
×
1803
                        clonedTable.uniques.indexOf(uniqueConstraint!),
×
1804
                        1,
×
1805
                    )
×
1806
                    upQueries.push(
×
1807
                        new Query(
×
1808
                            `ALTER TABLE ${this.escapePath(
×
1809
                                table,
×
1810
                            )} DROP CONSTRAINT "${uniqueConstraint!.name}"`,
×
1811
                        ),
×
1812
                    )
×
1813
                    downQueries.push(
×
1814
                        new Query(
×
1815
                            `ALTER TABLE ${this.escapePath(
×
1816
                                table,
×
1817
                            )} ADD CONSTRAINT "${
×
1818
                                uniqueConstraint!.name
×
1819
                            }" UNIQUE ("${newColumn.name}")`,
×
1820
                        ),
×
1821
                    )
×
1822
                }
×
1823
            }
2 ✔
1824

52 ✔
1825
            if (newColumn.default !== oldColumn.default) {
52 ✔
1826
                // (note) if there is a previous default, we need to drop its constraint first
4 ✔
1827
                if (
4 ✔
1828
                    oldColumn.default !== null &&
4 ✔
1829
                    oldColumn.default !== undefined
4 ✔
1830
                ) {
4 ✔
1831
                    const defaultName =
2 ✔
1832
                        this.connection.namingStrategy.defaultConstraintName(
2 ✔
1833
                            table,
2 ✔
1834
                            oldColumn.name,
2 ✔
1835
                        )
2 ✔
1836
                    upQueries.push(
2 ✔
1837
                        new Query(
2 ✔
1838
                            `ALTER TABLE ${this.escapePath(
2 ✔
1839
                                table,
2 ✔
1840
                            )} DROP CONSTRAINT "${defaultName}"`,
2 ✔
1841
                        ),
2 ✔
1842
                    )
2 ✔
1843
                    downQueries.push(
2 ✔
1844
                        new Query(
2 ✔
1845
                            `ALTER TABLE ${this.escapePath(
2 ✔
1846
                                table,
2 ✔
1847
                            )} ADD CONSTRAINT "${defaultName}" DEFAULT ${
2 ✔
1848
                                oldColumn.default
2 ✔
1849
                            } FOR "${oldColumn.name}"`,
2 ✔
1850
                        ),
2 ✔
1851
                    )
2 ✔
1852
                }
2 ✔
1853

4 ✔
1854
                if (
4 ✔
1855
                    newColumn.default !== null &&
4 ✔
1856
                    newColumn.default !== undefined
4 ✔
1857
                ) {
4 ✔
1858
                    const defaultName =
4 ✔
1859
                        this.connection.namingStrategy.defaultConstraintName(
4 ✔
1860
                            table,
4 ✔
1861
                            newColumn.name,
4 ✔
1862
                        )
4 ✔
1863
                    upQueries.push(
4 ✔
1864
                        new Query(
4 ✔
1865
                            `ALTER TABLE ${this.escapePath(
4 ✔
1866
                                table,
4 ✔
1867
                            )} ADD CONSTRAINT "${defaultName}" DEFAULT ${
4 ✔
1868
                                newColumn.default
4 ✔
1869
                            } FOR "${newColumn.name}"`,
4 ✔
1870
                        ),
4 ✔
1871
                    )
4 ✔
1872
                    downQueries.push(
4 ✔
1873
                        new Query(
4 ✔
1874
                            `ALTER TABLE ${this.escapePath(
4 ✔
1875
                                table,
4 ✔
1876
                            )} DROP CONSTRAINT "${defaultName}"`,
4 ✔
1877
                        ),
4 ✔
1878
                    )
4 ✔
1879
                }
4 ✔
1880
            }
4 ✔
1881

52 ✔
1882
            await this.executeQueries(upQueries, downQueries)
52 ✔
1883
            this.replaceCachedTable(table, clonedTable)
52 ✔
1884
        }
52 ✔
1885
    }
102 ✔
1886

26 ✔
1887
    /**
26 ✔
1888
     * Changes a column in the table.
26 ✔
1889
     */
26 ✔
1890
    async changeColumns(
26 ✔
1891
        tableOrName: Table | string,
44 ✔
1892
        changedColumns: { newColumn: TableColumn; oldColumn: TableColumn }[],
44 ✔
1893
    ): Promise<void> {
44 ✔
1894
        for (const { oldColumn, newColumn } of changedColumns) {
44 ✔
1895
            await this.changeColumn(tableOrName, oldColumn, newColumn)
62 ✔
1896
        }
62 ✔
1897
    }
44 ✔
1898

26 ✔
1899
    /**
26 ✔
1900
     * Drops column in the table.
26 ✔
1901
     */
26 ✔
1902
    async dropColumn(
26 ✔
1903
        tableOrName: Table | string,
86 ✔
1904
        columnOrName: TableColumn | string,
86 ✔
1905
    ): Promise<void> {
86 ✔
1906
        const table = InstanceChecker.isTable(tableOrName)
86 ✔
1907
            ? tableOrName
86 ✔
1908
            : await this.getCachedTable(tableOrName)
86 ✔
1909
        const column = InstanceChecker.isTableColumn(columnOrName)
6 ✔
1910
            ? columnOrName
86 ✔
1911
            : table.findColumnByName(columnOrName)
86 ✔
1912
        if (!column)
86 ✔
1913
            throw new TypeORMError(
86 ✔
1914
                `Column "${columnOrName}" was not found in table "${table.name}"`,
2 ✔
1915
            )
2 ✔
1916

84 ✔
1917
        const clonedTable = table.clone()
84 ✔
1918
        const upQueries: Query[] = []
84 ✔
1919
        const downQueries: Query[] = []
84 ✔
1920

84 ✔
1921
        // drop primary key constraint
84 ✔
1922
        if (column.isPrimary) {
86 ✔
1923
            const pkName = column.primaryKeyConstraintName
14 ✔
1924
                ? column.primaryKeyConstraintName
14 !
1925
                : this.connection.namingStrategy.primaryKeyName(
14 ✔
1926
                      clonedTable,
14 ✔
1927
                      clonedTable.primaryColumns.map((column) => column.name),
14 ✔
1928
                  )
14 ✔
1929

14 ✔
1930
            const columnNames = clonedTable.primaryColumns
14 ✔
1931
                .map((primaryColumn) => `"${primaryColumn.name}"`)
14 ✔
1932
                .join(", ")
14 ✔
1933

14 ✔
1934
            upQueries.push(
14 ✔
1935
                new Query(
14 ✔
1936
                    `ALTER TABLE ${this.escapePath(
14 ✔
1937
                        clonedTable,
14 ✔
1938
                    )} DROP CONSTRAINT "${pkName}"`,
14 ✔
1939
                ),
14 ✔
1940
            )
14 ✔
1941
            downQueries.push(
14 ✔
1942
                new Query(
14 ✔
1943
                    `ALTER TABLE ${this.escapePath(
14 ✔
1944
                        clonedTable,
14 ✔
1945
                    )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
14 ✔
1946
                ),
14 ✔
1947
            )
14 ✔
1948

14 ✔
1949
            // update column in table
14 ✔
1950
            const tableColumn = clonedTable.findColumnByName(column.name)
14 ✔
1951
            tableColumn!.isPrimary = false
14 ✔
1952

14 ✔
1953
            // if primary key have multiple columns, we must recreate it without dropped column
14 ✔
1954
            if (clonedTable.primaryColumns.length > 0) {
14 ✔
1955
                const pkName = clonedTable.primaryColumns[0]
2 ✔
1956
                    .primaryKeyConstraintName
2 ✔
1957
                    ? clonedTable.primaryColumns[0].primaryKeyConstraintName
2 !
1958
                    : this.connection.namingStrategy.primaryKeyName(
2 ✔
1959
                          clonedTable,
2 ✔
1960
                          clonedTable.primaryColumns.map(
2 ✔
1961
                              (column) => column.name,
2 ✔
1962
                          ),
2 ✔
1963
                      )
2 ✔
1964

2 ✔
1965
                const columnNames = clonedTable.primaryColumns
2 ✔
1966
                    .map((primaryColumn) => `"${primaryColumn.name}"`)
2 ✔
1967
                    .join(", ")
2 ✔
1968
                upQueries.push(
2 ✔
1969
                    new Query(
2 ✔
1970
                        `ALTER TABLE ${this.escapePath(
2 ✔
1971
                            clonedTable,
2 ✔
1972
                        )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`,
2 ✔
1973
                    ),
2 ✔
1974
                )
2 ✔
1975
                downQueries.push(
2 ✔
1976
                    new Query(
2 ✔
1977
                        `ALTER TABLE ${this.escapePath(
2 ✔
1978
                            clonedTable,
2 ✔
1979
                        )} DROP CONSTRAINT "${pkName}"`,
2 ✔
1980
                    ),
2 ✔
1981
                )
2 ✔
1982
            }
2 ✔
1983
        }
14 ✔
1984

84 ✔
1985
        // drop column index
84 ✔
1986
        const columnIndex = clonedTable.indices.find(
84 ✔
1987
            (index) =>
84 ✔
1988
                index.columnNames.length === 1 &&
2 ✔
1989
                index.columnNames[0] === column.name,
84 ✔
1990
        )
84 ✔
1991
        if (columnIndex) {
86 !
1992
            clonedTable.indices.splice(
×
1993
                clonedTable.indices.indexOf(columnIndex),
×
1994
                1,
×
1995
            )
×
1996
            upQueries.push(this.dropIndexSql(table, columnIndex))
×
1997
            downQueries.push(this.createIndexSql(table, columnIndex))
×
1998
        }
×
1999

84 ✔
2000
        // drop column check
84 ✔
2001
        const columnCheck = clonedTable.checks.find(
84 ✔
2002
            (check) =>
84 ✔
2003
                !!check.columnNames &&
32 ✔
2004
                check.columnNames.length === 1 &&
32 ✔
2005
                check.columnNames[0] === column.name,
84 ✔
2006
        )
84 ✔
2007
        if (columnCheck) {
86 ✔
2008
            clonedTable.checks.splice(
4 ✔
2009
                clonedTable.checks.indexOf(columnCheck),
4 ✔
2010
                1,
4 ✔
2011
            )
4 ✔
2012
            upQueries.push(this.dropCheckConstraintSql(table, columnCheck))
4 ✔
2013
            downQueries.push(this.createCheckConstraintSql(table, columnCheck))
4 ✔
2014
        }
4 ✔
2015

84 ✔
2016
        // drop column unique
84 ✔
2017
        const columnUnique = clonedTable.uniques.find(
84 ✔
2018
            (unique) =>
84 ✔
2019
                unique.columnNames.length === 1 &&
60 ✔
2020
                unique.columnNames[0] === column.name,
84 ✔
2021
        )
84 ✔
2022
        if (columnUnique) {
86 ✔
2023
            clonedTable.uniques.splice(
6 ✔
2024
                clonedTable.uniques.indexOf(columnUnique),
6 ✔
2025
                1,
6 ✔
2026
            )
6 ✔
2027
            upQueries.push(this.dropUniqueConstraintSql(table, columnUnique))
6 ✔
2028
            downQueries.push(
6 ✔
2029
                this.createUniqueConstraintSql(table, columnUnique),
6 ✔
2030
            )
6 ✔
2031
        }
6 ✔
2032

84 ✔
2033
        // drop default constraint
84 ✔
2034
        if (column.default !== null && column.default !== undefined) {
86 ✔
2035
            const defaultName =
12 ✔
2036
                this.connection.namingStrategy.defaultConstraintName(
12 ✔
2037
                    table,
12 ✔
2038
                    column.name,
12 ✔
2039
                )
12 ✔
2040
            upQueries.push(
12 ✔
2041
                new Query(
12 ✔
2042
                    `ALTER TABLE ${this.escapePath(
12 ✔
2043
                        table,
12 ✔
2044
                    )} DROP CONSTRAINT "${defaultName}"`,
12 ✔
2045
                ),
12 ✔
2046
            )
12 ✔
2047
            downQueries.push(
12 ✔
2048
                new Query(
12 ✔
2049
                    `ALTER TABLE ${this.escapePath(
12 ✔
2050
                        table,
12 ✔
2051
                    )} ADD CONSTRAINT "${defaultName}" DEFAULT ${
12 ✔
2052
                        column.default
12 ✔
2053
                    } FOR "${column.name}"`,
12 ✔
2054
                ),
12 ✔
2055
            )
12 ✔
2056
        }
12 ✔
2057

84 ✔
2058
        if (column.generatedType && column.asExpression) {
86 ✔
2059
            const parsedTableName = this.driver.parseTableName(table)
8 ✔
2060

8 ✔
2061
            if (!parsedTableName.schema) {
8 !
2062
                parsedTableName.schema = await this.getCurrentSchema()
×
2063
            }
×
2064

8 ✔
2065
            const deleteQuery = this.deleteTypeormMetadataSql({
8 ✔
2066
                database: parsedTableName.database,
8 ✔
2067
                schema: parsedTableName.schema,
8 ✔
2068
                table: parsedTableName.tableName,
8 ✔
2069
                type: MetadataTableType.GENERATED_COLUMN,
8 ✔
2070
                name: column.name,
8 ✔
2071
            })
8 ✔
2072
            const insertQuery = this.insertTypeormMetadataSql({
8 ✔
2073
                database: parsedTableName.database,
8 ✔
2074
                schema: parsedTableName.schema,
8 ✔
2075
                table: parsedTableName.tableName,
8 ✔
2076
                type: MetadataTableType.GENERATED_COLUMN,
8 ✔
2077
                name: column.name,
8 ✔
2078
                value: column.asExpression,
8 ✔
2079
            })
8 ✔
2080

8 ✔
2081
            upQueries.push(deleteQuery)
8 ✔
2082
            downQueries.push(insertQuery)
8 ✔
2083
        }
8 ✔
2084

84 ✔
2085
        upQueries.push(
84 ✔
2086
            new Query(
84 ✔
2087
                `ALTER TABLE ${this.escapePath(table)} DROP COLUMN "${
84 ✔
2088
                    column.name
84 ✔
2089
                }"`,
84 ✔
2090
            ),
84 ✔
2091
        )
84 ✔
2092
        downQueries.push(
84 ✔
2093
            new Query(
84 ✔
2094
                `ALTER TABLE ${this.escapePath(
84 ✔
2095
                    table,
84 ✔
2096
                )} ADD ${this.buildCreateColumnSql(
84 ✔
2097
                    table,
84 ✔
2098
                    column,
84 ✔
2099
                    false,
84 ✔
2100
                    false,
84 ✔
2101
                )}`,
84 ✔
2102
            ),
84 ✔
2103
        )
84 ✔
2104

84 ✔
2105
        await this.executeQueries(upQueries, downQueries)
84 ✔
2106

84 ✔
2107
        clonedTable.removeColumn(column)
84 ✔
2108
        this.replaceCachedTable(table, clonedTable)
84 ✔
2109
    }
84 ✔
2110

26 ✔
2111
    /**
26 ✔
2112
     * Drops the columns in the table.
26 ✔
2113
     */
26 ✔
2114
    async dropColumns(
26 ✔
2115
        tableOrName: Table | string,
10 ✔
2116
        columns: TableColumn[] | string[],
10 ✔
2117
    ): Promise<void> {
10 ✔
2118
        for (const column of [...columns]) {
10 ✔
2119
            await this.dropColumn(tableOrName, column)
26 ✔
2120
        }
26 ✔
2121
    }
10 ✔
2122

26 ✔
2123
    /**
26 ✔
2124
     * Creates a new primary key.
26 ✔
2125
     */
26 ✔
2126
    async createPrimaryKey(
26 ✔
2127
        tableOrName: Table | string,
4 ✔
2128
        columnNames: string[],
4 ✔
2129
        constraintName?: string,
4 ✔
2130
    ): Promise<void> {
4 ✔
2131
        const table = InstanceChecker.isTable(tableOrName)
4 ✔
2132
            ? tableOrName
4 !
2133
            : await this.getCachedTable(tableOrName)
4 ✔
2134
        const clonedTable = table.clone()
4 ✔
2135

4 ✔
2136
        const up = this.createPrimaryKeySql(table, columnNames, constraintName)
4 ✔
2137

4 ✔
2138
        // mark columns as primary, because dropPrimaryKeySql build constraint name from table primary column names.
4 ✔
2139
        clonedTable.columns.forEach((column) => {
4 ✔
2140
            if (columnNames.find((columnName) => columnName === column.name))
10 ✔
2141
                column.isPrimary = true
10 ✔
2142
        })
4 ✔
2143
        const down = this.dropPrimaryKeySql(clonedTable)
4 ✔
2144

4 ✔
2145
        await this.executeQueries(up, down)
4 ✔
2146
        this.replaceCachedTable(table, clonedTable)
4 ✔
2147
    }
4 ✔
2148

26 ✔
2149
    /**
26 ✔
2150
     * Updates composite primary keys.
26 ✔
2151
     */
26 ✔
2152
    async updatePrimaryKeys(
26 ✔
2153
        tableOrName: Table | string,
6 ✔
2154
        columns: TableColumn[],
6 ✔
2155
    ): Promise<void> {
6 ✔
2156
        const table = InstanceChecker.isTable(tableOrName)
6 ✔
2157
            ? tableOrName
6 ✔
2158
            : await this.getCachedTable(tableOrName)
6 !
2159
        const clonedTable = table.clone()
×
2160
        const columnNames = columns.map((column) => column.name)
✔
2161
        const upQueries: Query[] = []
×
2162
        const downQueries: Query[] = []
×
2163

×
2164
        // if table already have primary columns, we must drop them.
×
2165
        const primaryColumns = clonedTable.primaryColumns
×
2166
        if (primaryColumns.length > 0) {
6 ✔
2167
            const pkName = primaryColumns[0].primaryKeyConstraintName
6 ✔
2168
                ? primaryColumns[0].primaryKeyConstraintName
6 !
2169
                : this.connection.namingStrategy.primaryKeyName(
6 ✔
2170
                      clonedTable,
6 ✔
2171
                      primaryColumns.map((column) => column.name),
6 ✔
2172
                  )
6 ✔
2173

6 ✔
2174
            const columnNamesString = primaryColumns
6 ✔
2175
                .map((column) => `"${column.name}"`)
6 ✔
2176
                .join(", ")
6 ✔
2177

6 ✔
2178
            upQueries.push(
6 ✔
2179
                new Query(
6 ✔
2180
                    `ALTER TABLE ${this.escapePath(
6 ✔
2181
                        table,
6 ✔
2182
                    )} DROP CONSTRAINT "${pkName}"`,
6 ✔
2183
                ),
6 ✔
2184
            )
6 ✔
2185
            downQueries.push(
6 ✔
2186
                new Query(
6 ✔
2187
                    `ALTER TABLE ${this.escapePath(
6 ✔
2188
                        table,
6 ✔
2189
                    )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNamesString})`,
6 ✔
2190
                ),
6 ✔
2191
            )
6 ✔
2192
        }
6 ✔
2193

6 ✔
2194
        // update columns in table.
6 ✔
2195
        clonedTable.columns
6 ✔
2196
            .filter((column) => columnNames.indexOf(column.name) !== -1)
6 ✔
2197
            .forEach((column) => (column.isPrimary = true))
6 ✔
2198

6 ✔
2199
        const pkName = primaryColumns[0].primaryKeyConstraintName
6 ✔
2200
            ? primaryColumns[0].primaryKeyConstraintName
6 !
2201
            : this.connection.namingStrategy.primaryKeyName(
6 ✔
2202
                  clonedTable,
6 ✔
2203
                  columnNames,
6 ✔
2204
              )
6 ✔
2205

6 ✔
2206
        const columnNamesString = columnNames
6 ✔
2207
            .map((columnName) => `"${columnName}"`)
6 ✔
2208
            .join(", ")
6 ✔
2209

6 ✔
2210
        upQueries.push(
6 ✔
2211
            new Query(
6 ✔
2212
                `ALTER TABLE ${this.escapePath(
6 ✔
2213
                    table,
6 ✔
2214
                )} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNamesString})`,
6 ✔
2215
            ),
6 ✔
2216
        )
6 ✔
2217
        downQueries.push(
6 ✔
2218
            new Query(
6 ✔
2219
                `ALTER TABLE ${this.escapePath(
6 ✔
2220
                    table,
6 ✔
2221
                )} DROP CONSTRAINT "${pkName}"`,
6 ✔
2222
            ),
6 ✔
2223
        )
6 ✔
2224

6 ✔
2225
        await this.executeQueries(upQueries, downQueries)
6 ✔
2226
        this.replaceCachedTable(table, clonedTable)
6 ✔
2227
    }
6 ✔
2228

26 ✔
2229
    /**
26 ✔
2230
     * Drops a primary key.
26 ✔
2231
     */
26 ✔
2232
    async dropPrimaryKey(
26 ✔
2233
        tableOrName: Table | string,
6 ✔
2234
        constraintName?: string,
6 ✔
2235
    ): Promise<void> {
6 ✔
2236
        const table = InstanceChecker.isTable(tableOrName)
6 ✔
2237
            ? tableOrName
6 ✔
2238
            : await this.getCachedTable(tableOrName)
6 !
2239
        const up = this.dropPrimaryKeySql(table)
×
2240
        const down = this.createPrimaryKeySql(
×
2241
            table,
×
2242
            table.primaryColumns.map((column) => column.name),
✔
2243
            constraintName,
×
2244
        )
×
2245
        await this.executeQueries(up, down)
×
2246
        table.primaryColumns.forEach((column) => {
6 ✔
2247
            column.isPrimary = false
6 ✔
2248
        })
6 ✔
2249
    }
6 ✔
2250

26 ✔
2251
    /**
26 ✔
2252
     * Creates a new unique constraint.
26 ✔
2253
     */
26 ✔
2254
    async createUniqueConstraint(
26 ✔
2255
        tableOrName: Table | string,
16 ✔
2256
        uniqueConstraint: TableUnique,
16 ✔
2257
    ): Promise<void> {
16 ✔
2258
        const table = InstanceChecker.isTable(tableOrName)
16 ✔
2259
            ? tableOrName
16 ✔
2260
            : await this.getCachedTable(tableOrName)
16 ✔
2261

12 ✔
2262
        // new unique constraint may be passed without name. In this case we generate unique name manually.
12 ✔
2263
        if (!uniqueConstraint.name)
12 ✔
2264
            uniqueConstraint.name =
16 ✔
2265
                this.connection.namingStrategy.uniqueConstraintName(
4 ✔
2266
                    table,
4 ✔
2267
                    uniqueConstraint.columnNames,
4 ✔
2268
                )
4 ✔
2269

16 ✔
2270
        const up = this.createUniqueConstraintSql(table, uniqueConstraint)
16 ✔
2271
        const down = this.dropUniqueConstraintSql(table, uniqueConstraint)
16 ✔
2272
        await this.executeQueries(up, down)
16 ✔
2273
        table.addUniqueConstraint(uniqueConstraint)
16 ✔
2274
    }
16 ✔
2275

26 ✔
2276
    /**
26 ✔
2277
     * Creates a new unique constraints.
26 ✔
2278
     */
26 ✔
2279
    async createUniqueConstraints(
26 ✔
2280
        tableOrName: Table | string,
6 ✔
2281
        uniqueConstraints: TableUnique[],
6 ✔
2282
    ): Promise<void> {
6 ✔
2283
        const promises = uniqueConstraints.map((uniqueConstraint) =>
6 ✔
2284
            this.createUniqueConstraint(tableOrName, uniqueConstraint),
6 ✔
2285
        )
6 ✔
2286
        await Promise.all(promises)
6 ✔
2287
    }
6 ✔
2288

26 ✔
2289
    /**
26 ✔
2290
     * Drops unique constraint.
26 ✔
2291
     */
26 ✔
2292
    async dropUniqueConstraint(
26 ✔
2293
        tableOrName: Table | string,
16 ✔
2294
        uniqueOrName: TableUnique | string,
16 ✔
2295
    ): Promise<void> {
16 ✔
2296
        const table = InstanceChecker.isTable(tableOrName)
16 ✔
2297
            ? tableOrName
16 ✔
2298
            : await this.getCachedTable(tableOrName)
16 ✔
2299
        const uniqueConstraint = InstanceChecker.isTableUnique(uniqueOrName)
8 ✔
2300
            ? uniqueOrName
16 ✔
2301
            : table.uniques.find((u) => u.name === uniqueOrName)
16 !
2302
        if (!uniqueConstraint)
16 ✔
2303
            throw new TypeORMError(
16 !
2304
                `Supplied unique constraint was not found in table ${table.name}`,
×
2305
            )
×
2306

16 ✔
2307
        const up = this.dropUniqueConstraintSql(table, uniqueConstraint)
16 ✔
2308
        const down = this.createUniqueConstraintSql(table, uniqueConstraint)
16 ✔
2309
        await this.executeQueries(up, down)
16 ✔
2310
        table.removeUniqueConstraint(uniqueConstraint)
16 ✔
2311
    }
16 ✔
2312

26 ✔
2313
    /**
26 ✔
2314
     * Drops unique constraints.
26 ✔
2315
     */
26 ✔
2316
    async dropUniqueConstraints(
26 ✔
2317
        tableOrName: Table | string,
8 ✔
2318
        uniqueConstraints: TableUnique[],
8 ✔
2319
    ): Promise<void> {
8 ✔
2320
        const promises = uniqueConstraints.map((uniqueConstraint) =>
8 ✔
2321
            this.dropUniqueConstraint(tableOrName, uniqueConstraint),
8 ✔
2322
        )
8 ✔
2323
        await Promise.all(promises)
8 ✔
2324
    }
8 ✔
2325

26 ✔
2326
    /**
26 ✔
2327
     * Creates a new check constraint.
26 ✔
2328
     */
26 ✔
2329
    async createCheckConstraint(
26 ✔
2330
        tableOrName: Table | string,
10 ✔
2331
        checkConstraint: TableCheck,
10 ✔
2332
    ): Promise<void> {
10 ✔
2333
        const table = InstanceChecker.isTable(tableOrName)
10 ✔
2334
            ? tableOrName
10 ✔
2335
            : await this.getCachedTable(tableOrName)
10 ✔
2336

6 ✔
2337
        // new unique constraint may be passed without name. In this case we generate unique name manually.
6 ✔
2338
        if (!checkConstraint.name)
6 ✔
2339
            checkConstraint.name =
6 ✔
2340
                this.connection.namingStrategy.checkConstraintName(
6 ✔
2341
                    table,
6 ✔
2342
                    checkConstraint.expression!,
6 ✔
2343
                )
6 ✔
2344

10 ✔
2345
        const up = this.createCheckConstraintSql(table, checkConstraint)
10 ✔
2346
        const down = this.dropCheckConstraintSql(table, checkConstraint)
10 ✔
2347
        await this.executeQueries(up, down)
10 ✔
2348
        table.addCheckConstraint(checkConstraint)
10 ✔
2349
    }
10 ✔
2350

26 ✔
2351
    /**
26 ✔
2352
     * Creates a new check constraints.
26 ✔
2353
     */
26 ✔
2354
    async createCheckConstraints(
26 ✔
2355
        tableOrName: Table | string,
4 ✔
2356
        checkConstraints: TableCheck[],
4 ✔
2357
    ): Promise<void> {
4 ✔
2358
        const promises = checkConstraints.map((checkConstraint) =>
4 ✔
2359
            this.createCheckConstraint(tableOrName, checkConstraint),
4 ✔
2360
        )
4 ✔
2361
        await Promise.all(promises)
4 ✔
2362
    }
4 ✔
2363

26 ✔
2364
    /**
26 ✔
2365
     * Drops check constraint.
26 ✔
2366
     */
26 ✔
2367
    async dropCheckConstraint(
26 ✔
2368
        tableOrName: Table | string,
6 ✔
2369
        checkOrName: TableCheck | string,
6 ✔
2370
    ): Promise<void> {
6 ✔
2371
        const table = InstanceChecker.isTable(tableOrName)
6 ✔
2372
            ? tableOrName
6 ✔
2373
            : await this.getCachedTable(tableOrName)
6 !
2374
        const checkConstraint = InstanceChecker.isTableCheck(checkOrName)
×
2375
            ? checkOrName
6 ✔
2376
            : table.checks.find((c) => c.name === checkOrName)
6 !
2377
        if (!checkConstraint)
6 ✔
2378
            throw new TypeORMError(
6 !
2379
                `Supplied check constraint was not found in table ${table.name}`,
×
2380
            )
×
2381

6 ✔
2382
        const up = this.dropCheckConstraintSql(table, checkConstraint)
6 ✔
2383
        const down = this.createCheckConstraintSql(table, checkConstraint)
6 ✔
2384
        await this.executeQueries(up, down)
6 ✔
2385
        table.removeCheckConstraint(checkConstraint)
6 ✔
2386
    }
6 ✔
2387

26 ✔
2388
    /**
26 ✔
2389
     * Drops check constraints.
26 ✔
2390
     */
26 ✔
2391
    async dropCheckConstraints(
26 ✔
2392
        tableOrName: Table | string,
4 ✔
2393
        checkConstraints: TableCheck[],
4 ✔
2394
    ): Promise<void> {
4 ✔
2395
        const promises = checkConstraints.map((checkConstraint) =>
4 ✔
2396
            this.dropCheckConstraint(tableOrName, checkConstraint),
4 ✔
2397
        )
4 ✔
2398
        await Promise.all(promises)
4 ✔
2399
    }
4 ✔
2400

26 ✔
2401
    /**
26 ✔
2402
     * Creates a new exclusion constraint.
26 ✔
2403
     */
26 ✔
2404
    async createExclusionConstraint(
26 ✔
2405
        tableOrName: Table | string,
×
2406
        exclusionConstraint: TableExclusion,
×
2407
    ): Promise<void> {
×
2408
        throw new TypeORMError(
×
2409
            `SqlServer does not support exclusion constraints.`,
×
2410
        )
×
2411
    }
×
2412

26 ✔
2413
    /**
26 ✔
2414
     * Creates a new exclusion constraints.
26 ✔
2415
     */
26 ✔
2416
    async createExclusionConstraints(
26 ✔
2417
        tableOrName: Table | string,
×
2418
        exclusionConstraints: TableExclusion[],
×
2419
    ): Promise<void> {
×
2420
        throw new TypeORMError(
×
2421
            `SqlServer does not support exclusion constraints.`,
×
2422
        )
×
2423
    }
×
2424

26 ✔
2425
    /**
26 ✔
2426
     * Drops exclusion constraint.
26 ✔
2427
     */
26 ✔
2428
    async dropExclusionConstraint(
26 ✔
2429
        tableOrName: Table | string,
×
2430
        exclusionOrName: TableExclusion | string,
×
2431
    ): Promise<void> {
×
2432
        throw new TypeORMError(
×
2433
            `SqlServer does not support exclusion constraints.`,
×
2434
        )
×
2435
    }
×
2436

26 ✔
2437
    /**
26 ✔
2438
     * Drops exclusion constraints.
26 ✔
2439
     */
26 ✔
2440
    async dropExclusionConstraints(
26 ✔
2441
        tableOrName: Table | string,
×
2442
        exclusionConstraints: TableExclusion[],
×
2443
    ): Promise<void> {
×
2444
        throw new TypeORMError(
×
2445
            `SqlServer does not support exclusion constraints.`,
×
2446
        )
×
2447
    }
×
2448

26 ✔
2449
    /**
26 ✔
2450
     * Creates a new foreign key.
26 ✔
2451
     */
26 ✔
2452
    async createForeignKey(
26 ✔
2453
        tableOrName: Table | string,
6,766 ✔
2454
        foreignKey: TableForeignKey,
6,766 ✔
2455
    ): Promise<void> {
6,766 ✔
2456
        const table = InstanceChecker.isTable(tableOrName)
6,766 ✔
2457
            ? tableOrName
6,766 ✔
2458
            : await this.getCachedTable(tableOrName)
6,766 ✔
2459
        const metadata = this.connection.hasMetadata(table.name)
10 ✔
2460
            ? this.connection.getMetadata(table.name)
6,766 ✔
2461
            : undefined
6,766 ✔
2462

6,766 ✔
2463
        if (
6,766 ✔
2464
            metadata &&
6,766 ✔
2465
            metadata.treeParentRelation &&
6,766 ✔
2466
            metadata.treeParentRelation!.isTreeParent &&
6,766 ✔
2467
            metadata.foreignKeys.find(
776 ✔
2468
                (foreignKey) => foreignKey.onDelete !== "NO ACTION",
776 ✔
2469
            )
6,766 ✔
2470
        )
6,766 ✔
2471
            throw new TypeORMError(
6,766 !
2472
                "SqlServer does not support options in TreeParent.",
×
2473
            )
×
2474

6,766 ✔
2475
        // new FK may be passed without name. In this case we generate FK name manually.
6,766 ✔
2476
        if (!foreignKey.name)
6,766 ✔
2477
            foreignKey.name = this.connection.namingStrategy.foreignKeyName(
6,766 ✔
2478
                table,
2 ✔
2479
                foreignKey.columnNames,
2 ✔
2480
                this.getTablePath(foreignKey),
2 ✔
2481
                foreignKey.referencedColumnNames,
2 ✔
2482
            )
2 ✔
2483

6,766 ✔
2484
        const up = this.createForeignKeySql(table, foreignKey)
6,766 ✔
2485
        const down = this.dropForeignKeySql(table, foreignKey)
6,766 ✔
2486
        await this.executeQueries(up, down)
6,766 ✔
2487
        table.addForeignKey(foreignKey)
6,766 ✔
2488
    }
6,766 ✔
2489

26 ✔
2490
    /**
26 ✔
2491
     * Creates a new foreign keys.
26 ✔
2492
     */
26 ✔
2493
    async createForeignKeys(
26 ✔
2494
        tableOrName: Table | string,
4,132 ✔
2495
        foreignKeys: TableForeignKey[],
4,132 ✔
2496
    ): Promise<void> {
4,132 ✔
2497
        const promises = foreignKeys.map((foreignKey) =>
4,132 ✔
2498
            this.createForeignKey(tableOrName, foreignKey),
4,132 ✔
2499
        )
4,132 ✔
2500
        await Promise.all(promises)
4,132 ✔
2501
    }
4,132 ✔
2502

26 ✔
2503
    /**
26 ✔
2504
     * Drops a foreign key from the table.
26 ✔
2505
     */
26 ✔
2506
    async dropForeignKey(
26 ✔
2507
        tableOrName: Table | string,
22 ✔
2508
        foreignKeyOrName: TableForeignKey | string,
22 ✔
2509
    ): Promise<void> {
22 ✔
2510
        const table = InstanceChecker.isTable(tableOrName)
22 ✔
2511
            ? tableOrName
22 ✔
2512
            : await this.getCachedTable(tableOrName)
22 ✔
2513
        const foreignKey = InstanceChecker.isTableForeignKey(foreignKeyOrName)
8 ✔
2514
            ? foreignKeyOrName
22 ✔
2515
            : table.foreignKeys.find((fk) => fk.name === foreignKeyOrName)
22 !
2516
        if (!foreignKey)
22 ✔
2517
            throw new TypeORMError(
22 !
2518
                `Supplied foreign key was not found in table ${table.name}`,
×
2519
            )
×
2520

22 ✔
2521
        if (!foreignKey.name) {
22 !
NEW
UNCOV
2522
            foreignKey.name = this.connection.namingStrategy.foreignKeyName(
×
NEW
UNCOV
2523
                table,
×
NEW
UNCOV
2524
                foreignKey.columnNames,
×
NEW
UNCOV
2525
                this.getTablePath(foreignKey),
×
NEW
UNCOV
2526
                foreignKey.referencedColumnNames,
×
NEW
UNCOV
2527
            )
×
NEW
UNCOV
2528
        }
×
2529

22 ✔
2530
        const up = this.dropForeignKeySql(table, foreignKey)
22 ✔
2531
        const down = this.createForeignKeySql(table, foreignKey)
22 ✔
2532
        await this.executeQueries(up, down)
22 ✔
2533
        table.removeForeignKey(foreignKey)
22 ✔
2534
    }
22 ✔
2535

26 ✔
2536
    /**
26 ✔
2537
     * Drops a foreign keys from the table.
26 ✔
2538
     */
26 ✔
2539
    async dropForeignKeys(
26 ✔
2540
        tableOrName: Table | string,
14 ✔
2541
        foreignKeys: TableForeignKey[],
14 ✔
2542
    ): Promise<void> {
14 ✔
2543
        const promises = foreignKeys.map((foreignKey) =>
14 ✔
2544
            this.dropForeignKey(tableOrName, foreignKey),
14 ✔
2545
        )
14 ✔
2546
        await Promise.all(promises)
14 ✔
2547
    }
14 ✔
2548

26 ✔
2549
    /**
26 ✔
2550
     * Creates a new index.
26 ✔
2551
     */
26 ✔
2552
    async createIndex(
26 ✔
2553
        tableOrName: Table | string,
28 ✔
2554
        index: TableIndex,
28 ✔
2555
    ): Promise<void> {
28 ✔
2556
        const table = InstanceChecker.isTable(tableOrName)
28 ✔
2557
            ? tableOrName
28 ✔
2558
            : await this.getCachedTable(tableOrName)
28 ✔
2559

14 ✔
2560
        // new index may be passed without name. In this case we generate index name manually.
14 ✔
2561
        if (!index.name) index.name = this.generateIndexName(table, index)
28 ✔
2562

28 ✔
2563
        const up = this.createIndexSql(table, index)
28 ✔
2564
        const down = this.dropIndexSql(table, index)
28 ✔
2565
        await this.executeQueries(up, down)
28 ✔
2566
        table.addIndex(index)
28 ✔
2567
    }
28 ✔
2568

26 ✔
2569
    /**
26 ✔
2570
     * Creates a new indices
26 ✔
2571
     */
26 ✔
2572
    async createIndices(
26 ✔
2573
        tableOrName: Table | string,
14 ✔
2574
        indices: TableIndex[],
14 ✔
2575
    ): Promise<void> {
14 ✔
2576
        const promises = indices.map((index) =>
14 ✔
2577
            this.createIndex(tableOrName, index),
14 ✔
2578
        )
14 ✔
2579
        await Promise.all(promises)
14 ✔
2580
    }
14 ✔
2581

26 ✔
2582
    /**
26 ✔
2583
     * Drops an index.
26 ✔
2584
     */
26 ✔
2585
    async dropIndex(
26 ✔
2586
        tableOrName: Table | string,
32 ✔
2587
        indexOrName: TableIndex | string,
32 ✔
2588
    ): Promise<void> {
32 ✔
2589
        const table = InstanceChecker.isTable(tableOrName)
32 ✔
2590
            ? tableOrName
32 ✔
2591
            : await this.getCachedTable(tableOrName)
32 ✔
2592
        const index = InstanceChecker.isTableIndex(indexOrName)
10 ✔
2593
            ? indexOrName
32 ✔
2594
            : table.indices.find((i) => i.name === indexOrName)
32 !
2595
        if (!index)
32 ✔
2596
            throw new TypeORMError(
32 !
UNCOV
2597
                `Supplied index was not found in table ${table.name}`,
×
UNCOV
2598
            )
×
2599

32 ✔
2600
        // old index may be passed without name. In this case we generate index name manually.
32 ✔
2601
        if (!index.name) index.name = this.generateIndexName(table, index)
32 ✔
2602

32 ✔
2603
        const up = this.dropIndexSql(table, index)
32 ✔
2604
        const down = this.createIndexSql(table, index)
32 ✔
2605
        await this.executeQueries(up, down)
32 ✔
2606
        table.removeIndex(index)
32 ✔
2607
    }
32 ✔
2608

26 ✔
2609
    /**
26 ✔
2610
     * Drops an indices from the table.
26 ✔
2611
     */
26 ✔
2612
    async dropIndices(
26 ✔
2613
        tableOrName: Table | string,
4 ✔
2614
        indices: TableIndex[],
4 ✔
2615
    ): Promise<void> {
4 ✔
2616
        const promises = indices.map((index) =>
4 ✔
2617
            this.dropIndex(tableOrName, index),
4 ✔
2618
        )
4 ✔
2619
        await Promise.all(promises)
4 ✔
2620
    }
4 ✔
2621

26 ✔
2622
    /**
26 ✔
2623
     * Clears all table contents.
26 ✔
2624
     * Note: this operation uses SQL's TRUNCATE query which cannot be reverted in transactions.
26 ✔
2625
     */
26 ✔
2626
    async clearTable(tablePath: string): Promise<void> {
26 ✔
2627
        await this.query(`TRUNCATE TABLE ${this.escapePath(tablePath)}`)
4 ✔
2628
    }
4 ✔
2629

26 ✔
2630
    /**
26 ✔
2631
     * Removes all tables from the currently connected database.
26 ✔
2632
     */
26 ✔
2633
    async clearDatabase(database?: string): Promise<void> {
26 ✔
2634
        if (database) {
2,894 ✔
2635
            const isDatabaseExist = await this.hasDatabase(database)
2,894 ✔
2636
            if (!isDatabaseExist) return Promise.resolve()
2,894 !
2637
        }
2,894 ✔
2638

2,894 ✔
2639
        const isAnotherTransactionActive = this.isTransactionActive
2,894 ✔
2640
        if (!isAnotherTransactionActive) await this.startTransaction()
2,894 ✔
2641
        try {
2,894 ✔
2642
            const allViewsSql = database
2,894 ✔
2643
                ? `SELECT * FROM "${database}"."INFORMATION_SCHEMA"."VIEWS"`
2,894 ✔
2644
                : `SELECT * FROM "INFORMATION_SCHEMA"."VIEWS"`
2,894 !
2645
            const allViewsResults: ObjectLiteral[] =
2,894 ✔
2646
                await this.query(allViewsSql)
2,894 ✔
2647

2,894 ✔
2648
            await Promise.all(
2,894 ✔
2649
                allViewsResults.map((viewResult) => {
2,894 ✔
2650
                    // 'DROP VIEW' does not allow specifying the database name as a prefix to the object name.
16 ✔
2651
                    const dropTableSql = `DROP VIEW "${viewResult["TABLE_SCHEMA"]}"."${viewResult["TABLE_NAME"]}"`
16 ✔
2652
                    return this.query(dropTableSql)
16 ✔
2653
                }),
2,894 ✔
2654
            )
2,894 ✔
2655

2,894 ✔
2656
            const allTablesSql = database
2,894 ✔
2657
                ? `SELECT * FROM "${database}"."INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" = 'BASE TABLE'`
2,894 ✔
2658
                : `SELECT * FROM "INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" = 'BASE TABLE'`
2,894 !
2659
            const allTablesResults: ObjectLiteral[] =
2,894 ✔
2660
                await this.query(allTablesSql)
2,894 ✔
2661

2,894 ✔
2662
            if (allTablesResults.length > 0) {
2,894 ✔
2663
                const tablesByCatalog: {
2,852 ✔
2664
                    [key: string]: {
2,852 ✔
2665
                        TABLE_NAME: string
2,852 ✔
2666
                        TABLE_SCHEMA: string
2,852 ✔
2667
                    }[]
2,852 ✔
2668
                } = allTablesResults.reduce(
2,852 ✔
2669
                    (c, { TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME }) => {
2,852 ✔
2670
                        c[TABLE_CATALOG] = c[TABLE_CATALOG] || []
10,096 ✔
2671
                        c[TABLE_CATALOG].push({ TABLE_SCHEMA, TABLE_NAME })
10,096 ✔
2672
                        return c
10,096 ✔
2673
                    },
2,852 ✔
2674
                    {},
2,852 ✔
2675
                )
2,852 ✔
2676

2,852 ✔
2677
                const foreignKeysSql = Object.entries(tablesByCatalog)
2,852 ✔
2678
                    .map(([TABLE_CATALOG, tables]) => {
2,852 ✔
2679
                        const conditions = tables
2,852 ✔
2680
                            .map(({ TABLE_SCHEMA, TABLE_NAME }) => {
2,852 ✔
2681
                                return `("fk"."referenced_object_id" = OBJECT_ID('"${TABLE_CATALOG}"."${TABLE_SCHEMA}"."${TABLE_NAME}"'))`
10,096 ✔
2682
                            })
2,852 ✔
2683
                            .join(" OR ")
2,852 ✔
2684

2,852 ✔
2685
                        return `
2,852 ✔
2686
                        SELECT DISTINCT '${TABLE_CATALOG}' AS                                              "TABLE_CATALOG",
2,852 ✔
2687
                                        OBJECT_SCHEMA_NAME("fk"."parent_object_id",
2,852 ✔
2688
                                                           DB_ID('${TABLE_CATALOG}')) AS                   "TABLE_SCHEMA",
2,852 ✔
2689
                                        OBJECT_NAME("fk"."parent_object_id", DB_ID('${TABLE_CATALOG}')) AS "TABLE_NAME",
2,852 ✔
2690
                                        "fk"."name" AS                                                     "CONSTRAINT_NAME"
2,852 ✔
2691
                        FROM "${TABLE_CATALOG}"."sys"."foreign_keys" AS "fk"
2,852 ✔
2692
                        WHERE (${conditions})
2,852 ✔
2693
                    `
2,852 ✔
2694
                    })
2,852 ✔
2695
                    .join(" UNION ALL ")
2,852 ✔
2696

2,852 ✔
2697
                const foreignKeys: {
2,852 ✔
2698
                    TABLE_CATALOG: string
2,852 ✔
2699
                    TABLE_SCHEMA: string
2,852 ✔
2700
                    TABLE_NAME: string
2,852 ✔
2701
                    CONSTRAINT_NAME: string
2,852 ✔
2702
                }[] = await this.query(foreignKeysSql)
2,852 ✔
2703

2,852 ✔
2704
                await Promise.all(
2,852 ✔
2705
                    foreignKeys.map(
2,852 ✔
2706
                        async ({
2,852 ✔
2707
                            TABLE_CATALOG,
6,732 ✔
2708
                            TABLE_SCHEMA,
6,732 ✔
2709
                            TABLE_NAME,
6,732 ✔
2710
                            CONSTRAINT_NAME,
6,732 ✔
2711
                        }) => {
6,732 ✔
2712
                            // Disable the constraint first.
6,732 ✔
2713
                            await this.query(
6,732 ✔
2714
                                `ALTER TABLE "${TABLE_CATALOG}"."${TABLE_SCHEMA}"."${TABLE_NAME}" ` +
6,732 ✔
2715
                                    `NOCHECK CONSTRAINT "${CONSTRAINT_NAME}"`,
6,732 ✔
2716
                            )
6,732 ✔
2717

6,732 ✔
2718
                            await this.query(
6,732 ✔
2719
                                `ALTER TABLE "${TABLE_CATALOG}"."${TABLE_SCHEMA}"."${TABLE_NAME}" ` +
6,732 ✔
2720
                                    `DROP CONSTRAINT "${CONSTRAINT_NAME}" -- FROM CLEAR`,
6,732 ✔
2721
                            )
6,732 ✔
2722
                        },
2,852 ✔
2723
                    ),
2,852 ✔
2724
                )
2,852 ✔
2725

2,852 ✔
2726
                await Promise.all(
2,852 ✔
2727
                    allTablesResults.map(async (tablesResult) => {
2,852 ✔
2728
                        if (tablesResult["TABLE_NAME"].startsWith("#")) {
10,096 !
UNCOV
2729
                            // don't try to drop temporary tables
×
UNCOV
2730
                            return
×
UNCOV
2731
                        }
×
2732

10,096 ✔
2733
                        const dropTableSql = `DROP TABLE "${tablesResult["TABLE_CATALOG"]}"."${tablesResult["TABLE_SCHEMA"]}"."${tablesResult["TABLE_NAME"]}"`
10,096 ✔
2734
                        return this.query(dropTableSql)
10,096 ✔
2735
                    }),
2,852 ✔
2736
                )
2,852 ✔
2737
            }
2,852 ✔
2738

2,894 ✔
2739
            if (!isAnotherTransactionActive) await this.commitTransaction()
2,894 ✔
2740
        } catch (error) {
2,894 !
UNCOV
2741
            try {
×
UNCOV
2742
                // we throw original error even if rollback thrown an error
×
UNCOV
2743
                if (!isAnotherTransactionActive)
×
UNCOV
2744
                    await this.rollbackTransaction()
×
UNCOV
2745
            } catch (rollbackError) {}
×
UNCOV
2746
            throw error
×
UNCOV
2747
        }
×
2748
    }
2,894 ✔
2749

26 ✔
2750
    // -------------------------------------------------------------------------
26 ✔
2751
    // Protected Methods
26 ✔
2752
    // -------------------------------------------------------------------------
26 ✔
2753

26 ✔
2754
    protected async loadViews(viewPaths?: string[]): Promise<View[]> {
26 ✔
2755
        const hasTable = await this.hasTable(this.getTypeormMetadataTableName())
3,006 ✔
2756
        if (!hasTable) {
3,006 ✔
2757
            return []
2,976 ✔
2758
        }
2,976 ✔
2759

30 ✔
2760
        if (!viewPaths) {
3,006 !
UNCOV
2761
            viewPaths = []
×
UNCOV
2762
        }
×
2763

30 ✔
2764
        const currentSchema = await this.getCurrentSchema()
30 ✔
2765
        const currentDatabase = await this.getCurrentDatabase()
30 ✔
2766

30 ✔
2767
        const dbNames = viewPaths
30 ✔
2768
            .map((viewPath) => this.driver.parseTableName(viewPath).database)
30 ✔
2769
            .filter((database) => database)
30 ✔
2770

30 ✔
2771
        if (
30 ✔
2772
            this.driver.database &&
30 ✔
2773
            !dbNames.find((dbName) => dbName === this.driver.database)
30 ✔
2774
        )
3,006 ✔
2775
            dbNames.push(this.driver.database)
3,006 ✔
2776

30 ✔
2777
        const viewsCondition = viewPaths
30 ✔
2778
            .map((viewPath) => {
30 ✔
2779
                let { schema, tableName: name } =
22 ✔
2780
                    this.driver.parseTableName(viewPath)
22 ✔
2781

22 ✔
2782
                if (!schema) {
22 !
UNCOV
2783
                    schema = currentSchema
×
UNCOV
2784
                }
×
2785
                return `("T"."SCHEMA" = '${schema}' AND "T"."NAME" = '${name}')`
22 ✔
2786
            })
30 ✔
2787
            .join(" OR ")
30 ✔
2788

30 ✔
2789
        const query = dbNames
30 ✔
2790
            .map((dbName) => {
30 ✔
2791
                return (
38 ✔
2792
                    `SELECT "T".*, "V"."CHECK_OPTION" FROM ${this.escapePath(
38 ✔
2793
                        this.getTypeormMetadataTableName(),
38 ✔
2794
                    )} "t" ` +
38 ✔
2795
                    `INNER JOIN "${dbName}"."INFORMATION_SCHEMA"."VIEWS" "V" ON "V"."TABLE_SCHEMA" = "T"."SCHEMA" AND "v"."TABLE_NAME" = "T"."NAME" WHERE "T"."TYPE" = '${
38 ✔
2796
                        MetadataTableType.VIEW
38 ✔
2797
                    }' ${viewsCondition ? `AND (${viewsCondition})` : ""}`
38 ✔
2798
                )
38 ✔
2799
            })
30 ✔
2800
            .join(" UNION ALL ")
30 ✔
2801

30 ✔
2802
        const dbViews = await this.query(query)
30 ✔
2803
        return dbViews.map((dbView: any) => {
30 ✔
2804
            const view = new View()
6 ✔
2805
            const db =
6 ✔
2806
                dbView["TABLE_CATALOG"] === currentDatabase
6 ✔
2807
                    ? undefined
6 !
2808
                    : dbView["TABLE_CATALOG"]
6 ✔
2809
            const schema =
6 ✔
2810
                dbView["schema"] === currentSchema &&
6 ✔
2811
                !this.driver.options.schema
6 ✔
2812
                    ? undefined
6 ✔
2813
                    : dbView["schema"]
6 !
2814
            view.database = dbView["TABLE_CATALOG"]
6 ✔
2815
            view.schema = dbView["schema"]
6 ✔
2816
            view.name = this.driver.buildTableName(dbView["name"], schema, db)
6 ✔
2817
            view.expression = dbView["value"]
6 ✔
2818
            return view
6 ✔
2819
        })
30 ✔
2820
    }
30 ✔
2821

26 ✔
2822
    /**
26 ✔
2823
     * Loads all tables (with given names) from the database and creates a Table from them.
26 ✔
2824
     */
26 ✔
2825
    protected async loadTables(tableNames?: string[]): Promise<Table[]> {
26 ✔
2826
        // if no tables given then no need to proceed
3,580 ✔
2827
        if (tableNames && tableNames.length === 0) {
3,580 ✔
2828
            return []
14 ✔
2829
        }
14 ✔
2830

3,566 ✔
2831
        const currentSchema = await this.getCurrentSchema()
3,566 ✔
2832
        const currentDatabase = await this.getCurrentDatabase()
3,566 ✔
2833

3,566 ✔
2834
        const dbTables: {
3,566 ✔
2835
            TABLE_CATALOG: string
3,566 ✔
2836
            TABLE_SCHEMA: string
3,566 ✔
2837
            TABLE_NAME: string
3,566 ✔
2838
        }[] = []
3,566 ✔
2839

3,566 ✔
2840
        if (!tableNames) {
3,580 !
2841
            const databasesSql =
×
2842
                `SELECT DISTINCT "name" ` +
×
2843
                `FROM "master"."dbo"."sysdatabases" ` +
×
2844
                `WHERE "name" NOT IN ('master', 'model', 'msdb')`
×
2845
            const dbDatabases: { name: string }[] =
×
2846
                await this.query(databasesSql)
×
2847

×
2848
            const tablesSql = dbDatabases
×
2849
                .map(({ name }) => {
×
2850
                    return `
×
2851
                    SELECT DISTINCT
×
2852
                        "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME"
×
2853
                    FROM "${name}"."INFORMATION_SCHEMA"."TABLES"
×
2854
                    WHERE
×
2855
                      "TABLE_TYPE" = 'BASE TABLE'
×
UNCOV
2856
                      AND
×
UNCOV
2857
                      "TABLE_CATALOG" = '${name}'
×
UNCOV
2858
                      AND
×
UNCOV
2859
                      ISNULL(Objectproperty(Object_id("TABLE_CATALOG" + '.' + "TABLE_SCHEMA" + '.' + "TABLE_NAME"), 'IsMSShipped'), 0) = 0
×
UNCOV
2860
                `
×
UNCOV
2861
                })
×
UNCOV
2862
                .join(" UNION ALL ")
×
UNCOV
2863

×
UNCOV
2864
            dbTables.push(...(await this.query(tablesSql)))
×
2865
        } else {
3,580 ✔
2866
            const tableNamesByCatalog = tableNames
3,566 ✔
2867
                .map((tableName) => this.driver.parseTableName(tableName))
3,566 ✔
2868
                .reduce(
3,566 ✔
2869
                    (c, { database, ...other }) => {
3,566 ✔
2870
                        database = database || currentDatabase
11,094 !
2871
                        c[database] = c[database] || []
11,094 ✔
2872
                        c[database].push({
11,094 ✔
2873
                            schema: other.schema || currentSchema,
11,094 !
2874
                            tableName: other.tableName,
11,094 ✔
2875
                        })
11,094 ✔
2876
                        return c
11,094 ✔
2877
                    },
3,566 ✔
2878
                    {} as {
3,566 ✔
2879
                        [key: string]: { schema: string; tableName: string }[]
3,566 ✔
2880
                    },
3,566 ✔
2881
                )
3,566 ✔
2882

3,566 ✔
2883
            const tablesSql = Object.entries(tableNamesByCatalog)
3,566 ✔
2884
                .map(([database, tables]) => {
3,566 ✔
2885
                    const tablesCondition = tables
3,574 ✔
2886
                        .map(({ schema, tableName }) => {
3,574 ✔
2887
                            return `("TABLE_SCHEMA" = '${schema}' AND "TABLE_NAME" = '${tableName}')`
11,094 ✔
2888
                        })
3,574 ✔
2889
                        .join(" OR ")
3,574 ✔
2890

3,574 ✔
2891
                    return `
3,574 ✔
2892
                    SELECT DISTINCT
3,574 ✔
2893
                        "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME"
3,574 ✔
2894
                    FROM "${database}"."INFORMATION_SCHEMA"."TABLES"
3,574 ✔
2895
                    WHERE
3,574 ✔
2896
                          "TABLE_TYPE" = 'BASE TABLE' AND
3,574 ✔
2897
                          "TABLE_CATALOG" = '${database}' AND
3,574 ✔
2898
                          ${tablesCondition}
3,574 ✔
2899
                `
3,574 ✔
2900
                })
3,566 ✔
2901
                .join(" UNION ALL ")
3,566 ✔
2902

3,566 ✔
2903
            dbTables.push(...(await this.query(tablesSql)))
3,566 ✔
2904
        }
3,566 ✔
2905

3,566 ✔
2906
        // if tables were not found in the db, no need to proceed
3,566 ✔
2907
        if (dbTables.length === 0) {
3,580 ✔
2908
            return []
2,900 ✔
2909
        }
2,900 ✔
2910

666 ✔
2911
        const dbTablesByCatalog = dbTables.reduce(
666 ✔
2912
            (c, { TABLE_CATALOG, ...other }) => {
666 ✔
2913
                c[TABLE_CATALOG] = c[TABLE_CATALOG] || []
990 ✔
2914
                c[TABLE_CATALOG].push(other)
990 ✔
2915
                return c
990 ✔
2916
            },
666 ✔
2917
            {} as {
666 ✔
2918
                [key: string]: { TABLE_NAME: string; TABLE_SCHEMA: string }[]
666 ✔
2919
            },
666 ✔
2920
        )
666 ✔
2921

666 ✔
2922
        const columnsSql = Object.entries(dbTablesByCatalog)
666 ✔
2923
            .map(([TABLE_CATALOG, tables]) => {
666 ✔
2924
                const condition = tables
666 ✔
2925
                    .map(
666 ✔
2926
                        ({ TABLE_SCHEMA, TABLE_NAME }) =>
666 ✔
2927
                            `("TABLE_SCHEMA" = '${TABLE_SCHEMA}' AND "TABLE_NAME" = '${TABLE_NAME}')`,
666 ✔
2928
                    )
666 ✔
2929
                    .join("OR")
666 ✔
2930

666 ✔
2931
                return (
666 ✔
2932
                    `SELECT "COLUMNS".*, "cc"."is_persisted", "cc"."definition" ` +
666 ✔
2933
                    `FROM "${TABLE_CATALOG}"."INFORMATION_SCHEMA"."COLUMNS" ` +
666 ✔
2934
                    `LEFT JOIN "sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` +
666 ✔
2935
                    `WHERE (${condition})`
666 ✔
2936
                )
666 ✔
2937
            })
666 ✔
2938
            .join(" UNION ALL ")
666 ✔
2939

666 ✔
2940
        const constraintsSql = Object.entries(dbTablesByCatalog)
666 ✔
2941
            .map(([TABLE_CATALOG, tables]) => {
666 ✔
2942
                const conditions = tables
666 ✔
2943
                    .map(
666 ✔
2944
                        ({ TABLE_NAME, TABLE_SCHEMA }) =>
666 ✔
2945
                            `("columnUsages"."TABLE_SCHEMA" = '${TABLE_SCHEMA}' AND "columnUsages"."TABLE_NAME" = '${TABLE_NAME}')`,
666 ✔
2946
                    )
666 ✔
2947
                    .join(" OR ")
666 ✔
2948

666 ✔
2949
                return (
666 ✔
2950
                    `SELECT "columnUsages".*, "tableConstraints"."CONSTRAINT_TYPE", "chk"."definition" ` +
666 ✔
2951
                    `FROM "${TABLE_CATALOG}"."INFORMATION_SCHEMA"."CONSTRAINT_COLUMN_USAGE" "columnUsages" ` +
666 ✔
2952
                    `INNER JOIN "${TABLE_CATALOG}"."INFORMATION_SCHEMA"."TABLE_CONSTRAINTS" "tableConstraints" ` +
666 ✔
2953
                    `ON ` +
666 ✔
2954
                    `"tableConstraints"."CONSTRAINT_NAME" = "columnUsages"."CONSTRAINT_NAME" AND ` +
666 ✔
2955
                    `"tableConstraints"."TABLE_SCHEMA" = "columnUsages"."TABLE_SCHEMA" AND ` +
666 ✔
2956
                    `"tableConstraints"."TABLE_NAME" = "columnUsages"."TABLE_NAME" ` +
666 ✔
2957
                    `LEFT JOIN "${TABLE_CATALOG}"."sys"."check_constraints" "chk" ` +
666 ✔
2958
                    `ON ` +
666 ✔
2959
                    `"chk"."object_id" = OBJECT_ID("columnUsages"."TABLE_CATALOG" + '.' + "columnUsages"."TABLE_SCHEMA" + '.' + "columnUsages"."CONSTRAINT_NAME") ` +
666 ✔
2960
                    `WHERE ` +
666 ✔
2961
                    `(${conditions}) AND ` +
666 ✔
2962
                    `"tableConstraints"."CONSTRAINT_TYPE" IN ('PRIMARY KEY', 'UNIQUE', 'CHECK')`
666 ✔
2963
                )
666 ✔
2964
            })
666 ✔
2965
            .join(" UNION ALL ")
666 ✔
2966

666 ✔
2967
        const foreignKeysSql = Object.entries(dbTablesByCatalog)
666 ✔
2968
            .map(([TABLE_CATALOG, tables]) => {
666 ✔
2969
                const conditions = tables
666 ✔
2970
                    .map(
666 ✔
2971
                        ({ TABLE_NAME, TABLE_SCHEMA }) =>
666 ✔
2972
                            `("s1"."name" = '${TABLE_SCHEMA}' AND "t1"."name" = '${TABLE_NAME}')`,
666 ✔
2973
                    )
666 ✔
2974
                    .join(" OR ")
666 ✔
2975

666 ✔
2976
                return (
666 ✔
2977
                    `SELECT "fk"."name" AS "FK_NAME", '${TABLE_CATALOG}' AS "TABLE_CATALOG", "s1"."name" AS "TABLE_SCHEMA", "t1"."name" AS "TABLE_NAME", ` +
666 ✔
2978
                    `"col1"."name" AS "COLUMN_NAME", "s2"."name" AS "REF_SCHEMA", "t2"."name" AS "REF_TABLE", "col2"."name" AS "REF_COLUMN", ` +
666 ✔
2979
                    `"fk"."delete_referential_action_desc" AS "ON_DELETE", "fk"."update_referential_action_desc" AS "ON_UPDATE" ` +
666 ✔
2980
                    `FROM "${TABLE_CATALOG}"."sys"."foreign_keys" "fk" ` +
666 ✔
2981
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."foreign_key_columns" "fkc" ON "fkc"."constraint_object_id" = "fk"."object_id" ` +
666 ✔
2982
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."tables" "t1" ON "t1"."object_id" = "fk"."parent_object_id" ` +
666 ✔
2983
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."schemas" "s1" ON "s1"."schema_id" = "t1"."schema_id" ` +
666 ✔
2984
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."tables" "t2" ON "t2"."object_id" = "fk"."referenced_object_id" ` +
666 ✔
2985
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."schemas" "s2" ON "s2"."schema_id" = "t2"."schema_id" ` +
666 ✔
2986
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."columns" "col1" ON "col1"."column_id" = "fkc"."parent_column_id" AND "col1"."object_id" = "fk"."parent_object_id" ` +
666 ✔
2987
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."columns" "col2" ON "col2"."column_id" = "fkc"."referenced_column_id" AND "col2"."object_id" = "fk"."referenced_object_id" ` +
666 ✔
2988
                    `WHERE (${conditions})`
666 ✔
2989
                )
666 ✔
2990
            })
666 ✔
2991
            .join(" UNION ALL ")
666 ✔
2992

666 ✔
2993
        const identityColumnsSql = Object.entries(dbTablesByCatalog)
666 ✔
2994
            .map(([TABLE_CATALOG, tables]) => {
666 ✔
2995
                const conditions = tables
666 ✔
2996
                    .map(
666 ✔
2997
                        ({ TABLE_NAME, TABLE_SCHEMA }) =>
666 ✔
2998
                            `("TABLE_SCHEMA" = '${TABLE_SCHEMA}' AND "TABLE_NAME" = '${TABLE_NAME}')`,
666 ✔
2999
                    )
666 ✔
3000
                    .join(" OR ")
666 ✔
3001

666 ✔
3002
                return (
666 ✔
3003
                    `SELECT "TABLE_CATALOG", "TABLE_SCHEMA", "COLUMN_NAME", "TABLE_NAME" ` +
666 ✔
3004
                    `FROM "${TABLE_CATALOG}"."INFORMATION_SCHEMA"."COLUMNS" ` +
666 ✔
3005
                    `WHERE ` +
666 ✔
3006
                    `EXISTS(SELECT 1 FROM "${TABLE_CATALOG}"."sys"."columns" "S" WHERE OBJECT_ID("TABLE_CATALOG" + '.' + "TABLE_SCHEMA" + '.' + "TABLE_NAME") = "S"."OBJECT_ID" AND "COLUMN_NAME" = "S"."NAME" AND "S"."is_identity" = 1) AND ` +
666 ✔
3007
                    `(${conditions})`
666 ✔
3008
                )
666 ✔
3009
            })
666 ✔
3010
            .join(" UNION ALL ")
666 ✔
3011

666 ✔
3012
        const dbCollationsSql = `SELECT "NAME", "COLLATION_NAME" FROM "sys"."databases"`
666 ✔
3013

666 ✔
3014
        const indicesSql = Object.entries(dbTablesByCatalog)
666 ✔
3015
            .map(([TABLE_CATALOG, tables]) => {
666 ✔
3016
                const conditions = tables
666 ✔
3017
                    .map(
666 ✔
3018
                        ({ TABLE_NAME, TABLE_SCHEMA }) =>
666 ✔
3019
                            `("s"."name" = '${TABLE_SCHEMA}' AND "t"."name" = '${TABLE_NAME}')`,
666 ✔
3020
                    )
666 ✔
3021
                    .join(" OR ")
666 ✔
3022

666 ✔
3023
                return (
666 ✔
3024
                    `SELECT '${TABLE_CATALOG}' AS "TABLE_CATALOG", "s"."name" AS "TABLE_SCHEMA", "t"."name" AS "TABLE_NAME", ` +
666 ✔
3025
                    `"ind"."name" AS "INDEX_NAME", "col"."name" AS "COLUMN_NAME", "ind"."is_unique" AS "IS_UNIQUE", "ind"."filter_definition" as "CONDITION" ` +
666 ✔
3026
                    `FROM "${TABLE_CATALOG}"."sys"."indexes" "ind" ` +
666 ✔
3027
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."index_columns" "ic" ON "ic"."object_id" = "ind"."object_id" AND "ic"."index_id" = "ind"."index_id" ` +
666 ✔
3028
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."columns" "col" ON "col"."object_id" = "ic"."object_id" AND "col"."column_id" = "ic"."column_id" ` +
666 ✔
3029
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."tables" "t" ON "t"."object_id" = "ind"."object_id" ` +
666 ✔
3030
                    `INNER JOIN "${TABLE_CATALOG}"."sys"."schemas" "s" ON "s"."schema_id" = "t"."schema_id" ` +
666 ✔
3031
                    `WHERE ` +
666 ✔
3032
                    `"ind"."is_primary_key" = 0 AND "ind"."is_unique_constraint" = 0 AND "t"."is_ms_shipped" = 0 AND ` +
666 ✔
3033
                    `(${conditions})`
666 ✔
3034
                )
666 ✔
3035
            })
666 ✔
3036
            .join(" UNION ALL ")
666 ✔
3037

666 ✔
3038
        const [
666 ✔
3039
            dbColumns,
666 ✔
3040
            dbConstraints,
666 ✔
3041
            dbForeignKeys,
666 ✔
3042
            dbIdentityColumns,
666 ✔
3043
            dbCollations,
666 ✔
3044
            dbIndices,
666 ✔
3045
        ]: ObjectLiteral[][] = await Promise.all([
666 ✔
3046
            this.query(columnsSql),
666 ✔
3047
            this.query(constraintsSql),
666 ✔
3048
            this.query(foreignKeysSql),
666 ✔
3049
            this.query(identityColumnsSql),
666 ✔
3050
            this.query(dbCollationsSql),
666 ✔
3051
            this.query(indicesSql),
666 ✔
3052
        ])
666 ✔
3053

666 ✔
3054
        // create table schemas for loaded tables
666 ✔
3055
        return await Promise.all(
666 ✔
3056
            dbTables.map(async (dbTable) => {
666 ✔
3057
                const table = new Table()
990 ✔
3058

990 ✔
3059
                const getSchemaFromKey = (dbObject: any, key: string) => {
990 ✔
3060
                    return dbObject[key] === currentSchema &&
1,328 ✔
3061
                        (!this.driver.options.schema ||
1,238 ✔
3062
                            this.driver.options.schema === currentSchema)
1,238 ✔
3063
                        ? undefined
1,328 ✔
3064
                        : dbObject[key]
1,328 ✔
3065
                }
1,328 ✔
3066

990 ✔
3067
                // We do not need to join schema and database names, when db or schema is by default.
990 ✔
3068
                const db =
990 ✔
3069
                    dbTable["TABLE_CATALOG"] === currentDatabase
990 ✔
3070
                        ? undefined
990 ✔
3071
                        : dbTable["TABLE_CATALOG"]
990 ✔
3072
                const schema = getSchemaFromKey(dbTable, "TABLE_SCHEMA")
990 ✔
3073
                table.database = dbTable["TABLE_CATALOG"]
990 ✔
3074
                table.schema = dbTable["TABLE_SCHEMA"]
990 ✔
3075
                table.name = this.driver.buildTableName(
990 ✔
3076
                    dbTable["TABLE_NAME"],
990 ✔
3077
                    schema,
990 ✔
3078
                    db,
990 ✔
3079
                )
990 ✔
3080

990 ✔
3081
                const defaultCollation = dbCollations.find(
990 ✔
3082
                    (dbCollation) =>
990 ✔
3083
                        dbCollation["NAME"] === dbTable["TABLE_CATALOG"],
990 ✔
3084
                )!
990 ✔
3085

990 ✔
3086
                // create columns from the loaded columns
990 ✔
3087
                table.columns = await Promise.all(
990 ✔
3088
                    dbColumns
990 ✔
3089
                        .filter(
990 ✔
3090
                            (dbColumn) =>
990 ✔
3091
                                dbColumn["TABLE_NAME"] ===
10,700 ✔
3092
                                    dbTable["TABLE_NAME"] &&
10,700 ✔
3093
                                dbColumn["TABLE_SCHEMA"] ===
3,546 ✔
3094
                                    dbTable["TABLE_SCHEMA"] &&
10,700 ✔
3095
                                dbColumn["TABLE_CATALOG"] ===
3,546 ✔
3096
                                    dbTable["TABLE_CATALOG"],
990 ✔
3097
                        )
990 ✔
3098
                        .map(async (dbColumn) => {
990 ✔
3099
                            const columnConstraints = dbConstraints.filter(
3,546 ✔
3100
                                (dbConstraint) =>
3,546 ✔
3101
                                    dbConstraint["TABLE_NAME"] ===
18,730 ✔
3102
                                        dbColumn["TABLE_NAME"] &&
18,730 ✔
3103
                                    dbConstraint["TABLE_SCHEMA"] ===
7,836 ✔
3104
                                        dbColumn["TABLE_SCHEMA"] &&
18,730 ✔
3105
                                    dbConstraint["TABLE_CATALOG"] ===
7,836 ✔
3106
                                        dbColumn["TABLE_CATALOG"] &&
18,730 ✔
3107
                                    dbConstraint["COLUMN_NAME"] ===
7,836 ✔
3108
                                        dbColumn["COLUMN_NAME"],
3,546 ✔
3109
                            )
3,546 ✔
3110

3,546 ✔
3111
                            const uniqueConstraints = columnConstraints.filter(
3,546 ✔
3112
                                (constraint) =>
3,546 ✔
3113
                                    constraint["CONSTRAINT_TYPE"] === "UNIQUE",
3,546 ✔
3114
                            )
3,546 ✔
3115
                            const isConstraintComposite =
3,546 ✔
3116
                                uniqueConstraints.every((uniqueConstraint) => {
3,546 ✔
3117
                                    return dbConstraints.some(
590 ✔
3118
                                        (dbConstraint) =>
590 ✔
3119
                                            dbConstraint["CONSTRAINT_TYPE"] ===
2,456 ✔
3120
                                                "UNIQUE" &&
2,456 ✔
3121
                                            dbConstraint["CONSTRAINT_NAME"] ===
1,214 ✔
3122
                                                uniqueConstraint[
1,214 ✔
3123
                                                    "CONSTRAINT_NAME"
1,214 ✔
3124
                                                ] &&
2,456 ✔
3125
                                            dbConstraint["TABLE_SCHEMA"] ===
762 ✔
3126
                                                dbColumn["TABLE_SCHEMA"] &&
2,456 ✔
3127
                                            dbConstraint["TABLE_CATALOG"] ===
762 ✔
3128
                                                dbColumn["TABLE_CATALOG"] &&
2,456 ✔
3129
                                            dbConstraint["COLUMN_NAME"] !==
762 ✔
3130
                                                dbColumn["COLUMN_NAME"],
590 ✔
3131
                                    )
590 ✔
3132
                                })
3,546 ✔
3133

3,546 ✔
3134
                            const isGenerated = !!dbIdentityColumns.find(
3,546 ✔
3135
                                (column) =>
3,546 ✔
3136
                                    column["TABLE_NAME"] ===
5,696 ✔
3137
                                        dbColumn["TABLE_NAME"] &&
5,696 ✔
3138
                                    column["TABLE_SCHEMA"] ===
1,770 ✔
3139
                                        dbColumn["TABLE_SCHEMA"] &&
5,696 ✔
3140
                                    column["TABLE_CATALOG"] ===
1,770 ✔
3141
                                        dbColumn["TABLE_CATALOG"] &&
5,696 ✔
3142
                                    column["COLUMN_NAME"] ===
1,770 ✔
3143
                                        dbColumn["COLUMN_NAME"],
3,546 ✔
3144
                            )
3,546 ✔
3145

3,546 ✔
3146
                            const tableColumn = new TableColumn()
3,546 ✔
3147
                            tableColumn.name = dbColumn["COLUMN_NAME"]
3,546 ✔
3148
                            tableColumn.type =
3,546 ✔
3149
                                dbColumn["DATA_TYPE"].toLowerCase()
3,546 ✔
3150

3,546 ✔
3151
                            // check only columns that have length property
3,546 ✔
3152
                            if (
3,546 ✔
3153
                                this.driver.withLengthColumnTypes.indexOf(
3,546 ✔
3154
                                    tableColumn.type as ColumnType,
3,546 ✔
3155
                                ) !== -1 &&
3,546 ✔
3156
                                dbColumn["CHARACTER_MAXIMUM_LENGTH"]
1,928 ✔
3157
                            ) {
3,546 ✔
3158
                                const length =
1,928 ✔
3159
                                    dbColumn[
1,928 ✔
3160
                                        "CHARACTER_MAXIMUM_LENGTH"
1,928 ✔
3161
                                    ].toString()
1,928 ✔
3162
                                if (length === "-1") {
1,928 ✔
3163
                                    tableColumn.length = "MAX"
8 ✔
3164
                                } else {
1,928 ✔
3165
                                    if (tableColumn.type === "vector") {
1,920 ✔
3166
                                        const len = +length
2 ✔
3167
                                        // NOTE: real returned length is (N*4 + 8) where N is desired dimensions
2 ✔
3168
                                        if (!Number.isNaN(len)) {
2 ✔
3169
                                            tableColumn.length = String(
2 ✔
3170
                                                (len - 8) / 4,
2 ✔
3171
                                            )
2 ✔
3172
                                        }
2 ✔
3173
                                    } else {
1,920 ✔
3174
                                        tableColumn.length =
1,918 ✔
3175
                                            !this.isDefaultColumnLength(
1,918 ✔
3176
                                                table,
1,918 ✔
3177
                                                tableColumn,
1,918 ✔
3178
                                                length,
1,918 ✔
3179
                                            )
1,918 ✔
3180
                                                ? length
1,918 ✔
3181
                                                : ""
1,918 ✔
3182
                                    }
1,918 ✔
3183
                                }
1,920 ✔
3184
                            }
1,928 ✔
3185

3,546 ✔
3186
                            if (
3,546 ✔
3187
                                tableColumn.type === "decimal" ||
3,546 ✔
3188
                                tableColumn.type === "numeric"
3,536 ✔
3189
                            ) {
3,546 ✔
3190
                                if (
14 ✔
3191
                                    dbColumn["NUMERIC_PRECISION"] !== null &&
14 ✔
3192
                                    !this.isDefaultColumnPrecision(
14 ✔
3193
                                        table,
14 ✔
3194
                                        tableColumn,
14 ✔
3195
                                        dbColumn["NUMERIC_PRECISION"],
14 ✔
3196
                                    )
14 ✔
3197
                                )
14 ✔
3198
                                    tableColumn.precision =
14 ✔
3199
                                        dbColumn["NUMERIC_PRECISION"]
8 ✔
3200
                                if (
14 ✔
3201
                                    dbColumn["NUMERIC_SCALE"] !== null &&
14 ✔
3202
                                    !this.isDefaultColumnScale(
14 ✔
3203
                                        table,
14 ✔
3204
                                        tableColumn,
14 ✔
3205
                                        dbColumn["NUMERIC_SCALE"],
14 ✔
3206
                                    )
14 ✔
3207
                                )
14 ✔
3208
                                    tableColumn.scale =
14 ✔
3209
                                        dbColumn["NUMERIC_SCALE"]
8 ✔
3210
                            }
14 ✔
3211

3,546 ✔
3212
                            if (tableColumn.type === "nvarchar") {
3,546 ✔
3213
                                // Check if this is an enum
1,594 ✔
3214
                                const columnCheckConstraints =
1,594 ✔
3215
                                    columnConstraints.filter(
1,594 ✔
3216
                                        (constraint) =>
1,594 ✔
3217
                                            constraint["CONSTRAINT_TYPE"] ===
518 ✔
3218
                                            "CHECK",
1,594 ✔
3219
                                    )
1,594 ✔
3220
                                if (columnCheckConstraints.length) {
1,594 ✔
3221
                                    // const isEnumRegexp = new RegExp("^\\(\\[" + tableColumn.name + "\\]='[^']+'(?: OR \\[" + tableColumn.name + "\\]='[^']+')*\\)$");
22 ✔
3222
                                    for (const checkConstraint of columnCheckConstraints) {
22 ✔
3223
                                        if (
22 ✔
3224
                                            this.isEnumCheckConstraint(
22 ✔
3225
                                                checkConstraint[
22 ✔
3226
                                                    "CONSTRAINT_NAME"
22 ✔
3227
                                                ],
22 ✔
3228
                                            )
22 ✔
3229
                                        ) {
22 ✔
3230
                                            // This is an enum constraint, make column into an enum
10 ✔
3231
                                            tableColumn.enum = []
10 ✔
3232
                                            const enumValueRegexp = new RegExp(
10 ✔
3233
                                                "\\[" +
10 ✔
3234
                                                    tableColumn.name +
10 ✔
3235
                                                    "\\]='([^']+)'",
10 ✔
3236
                                                "g",
10 ✔
3237
                                            )
10 ✔
3238
                                            let result
10 ✔
3239
                                            while (
10 ✔
3240
                                                (result = enumValueRegexp.exec(
10 ✔
3241
                                                    checkConstraint[
10 ✔
3242
                                                        "definition"
10 ✔
3243
                                                    ],
10 ✔
3244
                                                )) !== null
10 ✔
3245
                                            ) {
10 ✔
3246
                                                tableColumn.enum.unshift(
26 ✔
3247
                                                    result[1],
26 ✔
3248
                                                )
26 ✔
3249
                                            }
26 ✔
3250
                                            // Skip other column constraints
10 ✔
3251
                                            break
10 ✔
3252
                                        }
10 ✔
3253
                                    }
22 ✔
3254
                                }
22 ✔
3255
                            }
1,594 ✔
3256

3,546 ✔
3257
                            const primaryConstraint = columnConstraints.find(
3,546 ✔
3258
                                (constraint) =>
3,546 ✔
3259
                                    constraint["CONSTRAINT_TYPE"] ===
1,796 ✔
3260
                                    "PRIMARY KEY",
3,546 ✔
3261
                            )
3,546 ✔
3262
                            if (primaryConstraint) {
3,546 ✔
3263
                                tableColumn.isPrimary = true
1,028 ✔
3264
                                // find another columns involved in primary key constraint
1,028 ✔
3265
                                const anotherPrimaryConstraints =
1,028 ✔
3266
                                    dbConstraints.filter(
1,028 ✔
3267
                                        (constraint) =>
1,028 ✔
3268
                                            constraint["TABLE_NAME"] ===
5,468 ✔
3269
                                                dbColumn["TABLE_NAME"] &&
5,468 ✔
3270
                                            constraint["TABLE_SCHEMA"] ===
1,930 ✔
3271
                                                dbColumn["TABLE_SCHEMA"] &&
5,468 ✔
3272
                                            constraint["TABLE_CATALOG"] ===
1,930 ✔
3273
                                                dbColumn["TABLE_CATALOG"] &&
5,468 ✔
3274
                                            constraint["COLUMN_NAME"] !==
1,930 ✔
3275
                                                dbColumn["COLUMN_NAME"] &&
5,468 ✔
3276
                                            constraint["CONSTRAINT_TYPE"] ===
882 ✔
3277
                                                "PRIMARY KEY",
1,028 ✔
3278
                                    )
1,028 ✔
3279

1,028 ✔
3280
                                // collect all column names
1,028 ✔
3281
                                const columnNames =
1,028 ✔
3282
                                    anotherPrimaryConstraints.map(
1,028 ✔
3283
                                        (constraint) =>
1,028 ✔
3284
                                            constraint["COLUMN_NAME"],
1,028 ✔
3285
                                    )
1,028 ✔
3286
                                columnNames.push(dbColumn["COLUMN_NAME"])
1,028 ✔
3287

1,028 ✔
3288
                                // build default primary key constraint name
1,028 ✔
3289
                                const pkName =
1,028 ✔
3290
                                    this.connection.namingStrategy.primaryKeyName(
1,028 ✔
3291
                                        table,
1,028 ✔
3292
                                        columnNames,
1,028 ✔
3293
                                    )
1,028 ✔
3294

1,028 ✔
3295
                                // if primary key has user-defined constraint name, write it in table column
1,028 ✔
3296
                                if (
1,028 ✔
3297
                                    primaryConstraint["CONSTRAINT_NAME"] !==
1,028 ✔
3298
                                    pkName
1,028 ✔
3299
                                ) {
1,028 ✔
3300
                                    tableColumn.primaryKeyConstraintName =
52 ✔
3301
                                        primaryConstraint["CONSTRAINT_NAME"]
52 ✔
3302
                                }
52 ✔
3303
                            }
1,028 ✔
3304

3,546 ✔
3305
                            tableColumn.default =
3,546 ✔
3306
                                dbColumn["COLUMN_DEFAULT"] !== null &&
3,546 ✔
3307
                                dbColumn["COLUMN_DEFAULT"] !== undefined
212 ✔
3308
                                    ? this.removeParenthesisFromDefault(
3,546 ✔
3309
                                          dbColumn["COLUMN_DEFAULT"],
212 ✔
3310
                                      )
3,546 ✔
3311
                                    : undefined
3,546 ✔
3312
                            tableColumn.isNullable =
3,546 ✔
3313
                                dbColumn["IS_NULLABLE"] === "YES"
3,546 ✔
3314
                            tableColumn.isUnique =
3,546 ✔
3315
                                uniqueConstraints.length > 0 &&
3,546 ✔
3316
                                !isConstraintComposite
590 ✔
3317
                            tableColumn.isGenerated = isGenerated
3,546 ✔
3318
                            if (isGenerated)
3,546 ✔
3319
                                tableColumn.generationStrategy = "increment"
3,546 ✔
3320
                            if (tableColumn.default === "newsequentialid()") {
3,546 ✔
3321
                                tableColumn.isGenerated = true
14 ✔
3322
                                tableColumn.generationStrategy = "uuid"
14 ✔
3323
                                tableColumn.default = undefined
14 ✔
3324
                            }
14 ✔
3325

3,546 ✔
3326
                            // todo: unable to get default charset
3,546 ✔
3327
                            // tableColumn.charset = dbColumn["CHARACTER_SET_NAME"];
3,546 ✔
3328
                            if (dbColumn["COLLATION_NAME"])
3,546 ✔
3329
                                tableColumn.collation =
3,546 ✔
3330
                                    dbColumn["COLLATION_NAME"] ===
1,880 ✔
3331
                                    defaultCollation["COLLATION_NAME"]
1,880 ✔
3332
                                        ? undefined
1,880 ✔
3333
                                        : dbColumn["COLLATION_NAME"]
1,880 ✔
3334

3,546 ✔
3335
                            if (
3,546 ✔
3336
                                tableColumn.type === "datetime2" ||
3,546 ✔
3337
                                tableColumn.type === "time" ||
3,546 ✔
3338
                                tableColumn.type === "datetimeoffset"
3,518 ✔
3339
                            ) {
3,546 ✔
3340
                                tableColumn.precision =
32 ✔
3341
                                    !this.isDefaultColumnPrecision(
32 ✔
3342
                                        table,
32 ✔
3343
                                        tableColumn,
32 ✔
3344
                                        dbColumn["DATETIME_PRECISION"],
32 ✔
3345
                                    )
32 ✔
3346
                                        ? dbColumn["DATETIME_PRECISION"]
32 ✔
3347
                                        : undefined
32 ✔
3348
                            }
32 ✔
3349

3,546 ✔
3350
                            if (
3,546 ✔
3351
                                dbColumn["is_persisted"] !== null &&
3,546 ✔
3352
                                dbColumn["is_persisted"] !== undefined &&
3,546 ✔
3353
                                dbColumn["definition"]
94 ✔
3354
                            ) {
3,546 ✔
3355
                                tableColumn.generatedType =
94 ✔
3356
                                    dbColumn["is_persisted"] === true
94 ✔
3357
                                        ? "STORED"
94 ✔
3358
                                        : "VIRTUAL"
94 ✔
3359
                                // We cannot relay on information_schema.columns.generation_expression, because it is formatted different.
94 ✔
3360
                                const asExpressionQuery =
94 ✔
3361
                                    this.selectTypeormMetadataSql({
94 ✔
3362
                                        database: dbTable["TABLE_CATALOG"],
94 ✔
3363
                                        schema: dbTable["TABLE_SCHEMA"],
94 ✔
3364
                                        table: dbTable["TABLE_NAME"],
94 ✔
3365
                                        type: MetadataTableType.GENERATED_COLUMN,
94 ✔
3366
                                        name: tableColumn.name,
94 ✔
3367
                                    })
94 ✔
3368

94 ✔
3369
                                const results = await this.query(
94 ✔
3370
                                    asExpressionQuery.query,
94 ✔
3371
                                    asExpressionQuery.parameters,
94 ✔
3372
                                )
94 ✔
3373
                                if (results[0] && results[0].value) {
94 ✔
3374
                                    tableColumn.asExpression = results[0].value
94 ✔
3375
                                } else {
94 !
UNCOV
3376
                                    tableColumn.asExpression = ""
×
UNCOV
3377
                                }
×
3378
                            }
94 ✔
3379

3,546 ✔
3380
                            return tableColumn
3,546 ✔
3381
                        }),
990 ✔
3382
                )
990 ✔
3383

990 ✔
3384
                // find unique constraints of table, group them by constraint name and build TableUnique.
990 ✔
3385
                const tableUniqueConstraints = OrmUtils.uniq(
990 ✔
3386
                    dbConstraints.filter(
990 ✔
3387
                        (dbConstraint) =>
990 ✔
3388
                            dbConstraint["TABLE_NAME"] ===
5,330 ✔
3389
                                dbTable["TABLE_NAME"] &&
5,330 ✔
3390
                            dbConstraint["TABLE_SCHEMA"] ===
1,816 ✔
3391
                                dbTable["TABLE_SCHEMA"] &&
5,330 ✔
3392
                            dbConstraint["TABLE_CATALOG"] ===
1,816 ✔
3393
                                dbTable["TABLE_CATALOG"] &&
5,330 ✔
3394
                            dbConstraint["CONSTRAINT_TYPE"] === "UNIQUE",
990 ✔
3395
                    ),
990 ✔
3396
                    (dbConstraint) => dbConstraint["CONSTRAINT_NAME"],
990 ✔
3397
                )
990 ✔
3398

990 ✔
3399
                table.uniques = tableUniqueConstraints.map((constraint) => {
990 ✔
3400
                    const uniques = dbConstraints.filter(
414 ✔
3401
                        (dbC) =>
414 ✔
3402
                            dbC["CONSTRAINT_NAME"] ===
2,602 ✔
3403
                            constraint["CONSTRAINT_NAME"],
414 ✔
3404
                    )
414 ✔
3405
                    return new TableUnique({
414 ✔
3406
                        name: constraint["CONSTRAINT_NAME"],
414 ✔
3407
                        columnNames: uniques.map((u) => u["COLUMN_NAME"]),
414 ✔
3408
                    })
414 ✔
3409
                })
990 ✔
3410

990 ✔
3411
                // find check constraints of table, group them by constraint name and build TableCheck.
990 ✔
3412
                const tableCheckConstraints = OrmUtils.uniq(
990 ✔
3413
                    dbConstraints.filter(
990 ✔
3414
                        (dbConstraint) =>
990 ✔
3415
                            dbConstraint["TABLE_NAME"] ===
5,330 ✔
3416
                                dbTable["TABLE_NAME"] &&
5,330 ✔
3417
                            dbConstraint["TABLE_SCHEMA"] ===
1,816 ✔
3418
                                dbTable["TABLE_SCHEMA"] &&
5,330 ✔
3419
                            dbConstraint["TABLE_CATALOG"] ===
1,816 ✔
3420
                                dbTable["TABLE_CATALOG"] &&
5,330 ✔
3421
                            dbConstraint["CONSTRAINT_TYPE"] === "CHECK",
990 ✔
3422
                    ),
990 ✔
3423
                    (dbConstraint) => dbConstraint["CONSTRAINT_NAME"],
990 ✔
3424
                )
990 ✔
3425

990 ✔
3426
                table.checks = tableCheckConstraints
990 ✔
3427
                    .filter(
990 ✔
3428
                        (constraint) =>
990 ✔
3429
                            !this.isEnumCheckConstraint(
184 ✔
3430
                                constraint["CONSTRAINT_NAME"],
184 ✔
3431
                            ),
990 ✔
3432
                    )
990 ✔
3433
                    .map((constraint) => {
990 ✔
3434
                        const checks = dbConstraints.filter(
174 ✔
3435
                            (dbC) =>
174 ✔
3436
                                dbC["CONSTRAINT_NAME"] ===
1,220 ✔
3437
                                constraint["CONSTRAINT_NAME"],
174 ✔
3438
                        )
174 ✔
3439
                        return new TableCheck({
174 ✔
3440
                            name: constraint["CONSTRAINT_NAME"],
174 ✔
3441
                            columnNames: checks.map((c) => c["COLUMN_NAME"]),
174 ✔
3442
                            expression: constraint["definition"],
174 ✔
3443
                        })
174 ✔
3444
                    })
990 ✔
3445

990 ✔
3446
                // find foreign key constraints of table, group them by constraint name and build TableForeignKey.
990 ✔
3447
                const tableForeignKeyConstraints = OrmUtils.uniq(
990 ✔
3448
                    dbForeignKeys.filter(
990 ✔
3449
                        (dbForeignKey) =>
990 ✔
3450
                            dbForeignKey["TABLE_NAME"] ===
1,280 ✔
3451
                                dbTable["TABLE_NAME"] &&
1,280 ✔
3452
                            dbForeignKey["TABLE_SCHEMA"] ===
346 ✔
3453
                                dbTable["TABLE_SCHEMA"] &&
1,280 ✔
3454
                            dbForeignKey["TABLE_CATALOG"] ===
346 ✔
3455
                                dbTable["TABLE_CATALOG"],
990 ✔
3456
                    ),
990 ✔
3457
                    (dbForeignKey) => dbForeignKey["FK_NAME"],
990 ✔
3458
                )
990 ✔
3459

990 ✔
3460
                table.foreignKeys = tableForeignKeyConstraints.map(
990 ✔
3461
                    (dbForeignKey) => {
990 ✔
3462
                        const foreignKeys = dbForeignKeys.filter(
338 ✔
3463
                            (dbFk) =>
338 ✔
3464
                                dbFk["FK_NAME"] === dbForeignKey["FK_NAME"],
338 ✔
3465
                        )
338 ✔
3466

338 ✔
3467
                        // if referenced table located in currently used db and schema, we don't need to concat db and schema names to table name.
338 ✔
3468
                        const db =
338 ✔
3469
                            dbForeignKey["TABLE_CATALOG"] === currentDatabase
338 ✔
3470
                                ? undefined
338 ✔
3471
                                : dbForeignKey["TABLE_CATALOG"]
338 ✔
3472
                        const schema = getSchemaFromKey(
338 ✔
3473
                            dbForeignKey,
338 ✔
3474
                            "REF_SCHEMA",
338 ✔
3475
                        )
338 ✔
3476
                        const referencedTableName = this.driver.buildTableName(
338 ✔
3477
                            dbForeignKey["REF_TABLE"],
338 ✔
3478
                            schema,
338 ✔
3479
                            db,
338 ✔
3480
                        )
338 ✔
3481

338 ✔
3482
                        return new TableForeignKey({
338 ✔
3483
                            name: dbForeignKey["FK_NAME"],
338 ✔
3484
                            columnNames: foreignKeys.map(
338 ✔
3485
                                (dbFk) => dbFk["COLUMN_NAME"],
338 ✔
3486
                            ),
338 ✔
3487
                            referencedDatabase: dbForeignKey["TABLE_CATALOG"],
338 ✔
3488
                            referencedSchema: dbForeignKey["REF_SCHEMA"],
338 ✔
3489
                            referencedTableName: referencedTableName,
338 ✔
3490
                            referencedColumnNames: foreignKeys.map(
338 ✔
3491
                                (dbFk) => dbFk["REF_COLUMN"],
338 ✔
3492
                            ),
338 ✔
3493
                            onDelete: dbForeignKey["ON_DELETE"].replace(
338 ✔
3494
                                "_",
338 ✔
3495
                                " ",
338 ✔
3496
                            ), // SqlServer returns NO_ACTION, instead of NO ACTION
338 ✔
3497
                            onUpdate: dbForeignKey["ON_UPDATE"].replace(
338 ✔
3498
                                "_",
338 ✔
3499
                                " ",
338 ✔
3500
                            ), // SqlServer returns NO_ACTION, instead of NO ACTION
338 ✔
3501
                        })
338 ✔
3502
                    },
990 ✔
3503
                )
990 ✔
3504

990 ✔
3505
                // find index constraints of table, group them by constraint name and build TableIndex.
990 ✔
3506
                const tableIndexConstraints = OrmUtils.uniq(
990 ✔
3507
                    dbIndices.filter(
990 ✔
3508
                        (dbIndex) =>
990 ✔
3509
                            dbIndex["TABLE_NAME"] === dbTable["TABLE_NAME"] &&
722 ✔
3510
                            dbIndex["TABLE_SCHEMA"] ===
332 ✔
3511
                                dbTable["TABLE_SCHEMA"] &&
722 ✔
3512
                            dbIndex["TABLE_CATALOG"] ===
332 ✔
3513
                                dbTable["TABLE_CATALOG"],
990 ✔
3514
                    ),
990 ✔
3515
                    (dbIndex) => dbIndex["INDEX_NAME"],
990 ✔
3516
                )
990 ✔
3517

990 ✔
3518
                table.indices = tableIndexConstraints.map((constraint) => {
990 ✔
3519
                    const indices = dbIndices.filter((index) => {
288 ✔
3520
                        return (
964 ✔
3521
                            index["TABLE_CATALOG"] ===
964 ✔
3522
                                constraint["TABLE_CATALOG"] &&
964 ✔
3523
                            index["TABLE_SCHEMA"] ===
964 ✔
3524
                                constraint["TABLE_SCHEMA"] &&
964 ✔
3525
                            index["TABLE_NAME"] === constraint["TABLE_NAME"] &&
964 ✔
3526
                            index["INDEX_NAME"] === constraint["INDEX_NAME"]
694 ✔
3527
                        )
964 ✔
3528
                    })
288 ✔
3529
                    return new TableIndex(<TableIndexOptions>{
288 ✔
3530
                        table: table,
288 ✔
3531
                        name: constraint["INDEX_NAME"],
288 ✔
3532
                        columnNames: indices.map((i) => i["COLUMN_NAME"]),
288 ✔
3533
                        isUnique: constraint["IS_UNIQUE"],
288 ✔
3534
                        where: constraint["CONDITION"],
288 ✔
3535
                    })
288 ✔
3536
                })
990 ✔
3537

990 ✔
3538
                return table
990 ✔
3539
            }),
666 ✔
3540
        )
666 ✔
3541
    }
666 ✔
3542

26 ✔
3543
    /**
26 ✔
3544
     * Builds and returns SQL for create table.
26 ✔
3545
     */
26 ✔
3546
    protected createTableSql(table: Table, createForeignKeys?: boolean): Query {
26 ✔
3547
        const columnDefinitions = table.columns
10,188 ✔
3548
            .map((column) =>
10,188 ✔
3549
                this.buildCreateColumnSql(table, column, false, true),
10,188 ✔
3550
            )
10,188 ✔
3551
            .join(", ")
10,188 ✔
3552
        let sql = `CREATE TABLE ${this.escapePath(table)} (${columnDefinitions}`
10,188 ✔
3553

10,188 ✔
3554
        table.columns
10,188 ✔
3555
            .filter((column) => column.isUnique)
10,188 ✔
3556
            .forEach((column) => {
10,188 ✔
3557
                const isUniqueExist = table.uniques.some(
642 ✔
3558
                    (unique) =>
642 ✔
3559
                        unique.columnNames.length === 1 &&
776 ✔
3560
                        unique.columnNames[0] === column.name,
642 ✔
3561
                )
642 ✔
3562
                if (!isUniqueExist)
642 ✔
3563
                    table.uniques.push(
642 ✔
3564
                        new TableUnique({
8 ✔
3565
                            name: this.connection.namingStrategy.uniqueConstraintName(
8 ✔
3566
                                table,
8 ✔
3567
                                [column.name],
8 ✔
3568
                            ),
8 ✔
3569
                            columnNames: [column.name],
8 ✔
3570
                        }),
8 ✔
3571
                    )
8 ✔
3572
            })
10,188 ✔
3573

10,188 ✔
3574
        if (table.uniques.length > 0) {
10,188 ✔
3575
            const uniquesSql = table.uniques
596 ✔
3576
                .map((unique) => {
596 ✔
3577
                    const uniqueName = unique.name
868 ✔
3578
                        ? unique.name
868 ✔
3579
                        : this.connection.namingStrategy.uniqueConstraintName(
868 ✔
3580
                              table,
4 ✔
3581
                              unique.columnNames,
4 ✔
3582
                          )
868 ✔
3583
                    const columnNames = unique.columnNames
868 ✔
3584
                        .map((columnName) => `"${columnName}"`)
868 ✔
3585
                        .join(", ")
868 ✔
3586
                    return `CONSTRAINT "${uniqueName}" UNIQUE (${columnNames})`
868 ✔
3587
                })
596 ✔
3588
                .join(", ")
596 ✔
3589

596 ✔
3590
            sql += `, ${uniquesSql}`
596 ✔
3591
        }
596 ✔
3592

10,188 ✔
3593
        if (table.checks.length > 0) {
10,188 ✔
3594
            const checksSql = table.checks
146 ✔
3595
                .map((check) => {
146 ✔
3596
                    const checkName = check.name
148 ✔
3597
                        ? check.name
148 ✔
3598
                        : this.connection.namingStrategy.checkConstraintName(
148 ✔
3599
                              table,
2 ✔
3600
                              check.expression!,
2 ✔
3601
                          )
148 ✔
3602
                    return `CONSTRAINT "${checkName}" CHECK (${check.expression})`
148 ✔
3603
                })
146 ✔
3604
                .join(", ")
146 ✔
3605

146 ✔
3606
            sql += `, ${checksSql}`
146 ✔
3607
        }
146 ✔
3608

10,188 ✔
3609
        if (table.foreignKeys.length > 0 && createForeignKeys) {
10,188 ✔
3610
            const foreignKeysSql = table.foreignKeys
8 ✔
3611
                .map((fk) => {
8 ✔
3612
                    const columnNames = fk.columnNames
10 ✔
3613
                        .map((columnName) => `"${columnName}"`)
10 ✔
3614
                        .join(", ")
10 ✔
3615
                    if (!fk.name)
10 ✔
3616
                        fk.name = this.connection.namingStrategy.foreignKeyName(
10 ✔
3617
                            table,
6 ✔
3618
                            fk.columnNames,
6 ✔
3619
                            this.getTablePath(fk),
6 ✔
3620
                            fk.referencedColumnNames,
6 ✔
3621
                        )
6 ✔
3622
                    const referencedColumnNames = fk.referencedColumnNames
10 ✔
3623
                        .map((columnName) => `"${columnName}"`)
10 ✔
3624
                        .join(", ")
10 ✔
3625

10 ✔
3626
                    let constraint = `CONSTRAINT "${
10 ✔
3627
                        fk.name
10 ✔
3628
                    }" FOREIGN KEY (${columnNames}) REFERENCES ${this.escapePath(
10 ✔
3629
                        this.getTablePath(fk),
10 ✔
3630
                    )} (${referencedColumnNames})`
10 ✔
3631
                    if (fk.onDelete) constraint += ` ON DELETE ${fk.onDelete}`
10 ✔
3632
                    if (fk.onUpdate) constraint += ` ON UPDATE ${fk.onUpdate}`
10 ✔
3633

10 ✔
3634
                    return constraint
10 ✔
3635
                })
8 ✔
3636
                .join(", ")
8 ✔
3637

8 ✔
3638
            sql += `, ${foreignKeysSql}`
8 ✔
3639
        }
8 ✔
3640

10,188 ✔
3641
        const primaryColumns = table.columns.filter(
10,188 ✔
3642
            (column) => column.isPrimary,
10,188 ✔
3643
        )
10,188 ✔
3644
        if (primaryColumns.length > 0) {
10,188 ✔
3645
            const primaryKeyName = primaryColumns[0].primaryKeyConstraintName
10,162 ✔
3646
                ? primaryColumns[0].primaryKeyConstraintName
10,162 ✔
3647
                : this.connection.namingStrategy.primaryKeyName(
10,162 ✔
3648
                      table,
10,130 ✔
3649
                      primaryColumns.map((column) => column.name),
10,130 ✔
3650
                  )
10,162 ✔
3651

10,162 ✔
3652
            const columnNames = primaryColumns
10,162 ✔
3653
                .map((column) => `"${column.name}"`)
10,162 ✔
3654
                .join(", ")
10,162 ✔
3655
            sql += `, CONSTRAINT "${primaryKeyName}" PRIMARY KEY (${columnNames})`
10,162 ✔
3656
        }
10,162 ✔
3657

10,188 ✔
3658
        sql += `)`
10,188 ✔
3659

10,188 ✔
3660
        return new Query(sql)
10,188 ✔
3661
    }
10,188 ✔
3662

26 ✔
3663
    /**
26 ✔
3664
     * Builds drop table sql.
26 ✔
3665
     */
26 ✔
3666
    protected dropTableSql(
26 ✔
3667
        tableOrName: Table | string,
10,188 ✔
3668
        ifExist?: boolean,
10,188 ✔
3669
    ): Query {
10,188 ✔
3670
        const query = ifExist
10,188 ✔
3671
            ? `DROP TABLE IF EXISTS ${this.escapePath(tableOrName)}`
10,188 !
3672
            : `DROP TABLE ${this.escapePath(tableOrName)}`
10,188 ✔
3673
        return new Query(query)
10,188 ✔
3674
    }
10,188 ✔
3675

26 ✔
3676
    protected createViewSql(view: View): Query {
26 ✔
3677
        const parsedName = this.driver.parseTableName(view)
16 ✔
3678

16 ✔
3679
        // Can't use `escapePath` here because `CREATE VIEW` does not accept database names.
16 ✔
3680
        const viewIdentifier = parsedName.schema
16 ✔
3681
            ? `"${parsedName.schema}"."${parsedName.tableName}"`
16 ✔
3682
            : `"${parsedName.tableName}"`
16 !
3683

16 ✔
3684
        if (typeof view.expression === "string") {
16 ✔
3685
            return new Query(
4 ✔
3686
                `CREATE VIEW ${viewIdentifier} AS ${view.expression}`,
4 ✔
3687
            )
4 ✔
3688
        } else {
16 ✔
3689
            return new Query(
12 ✔
3690
                `CREATE VIEW ${viewIdentifier} AS ${view
12 ✔
3691
                    .expression(this.connection)
12 ✔
3692
                    .getQuery()}`,
12 ✔
3693
            )
12 ✔
3694
        }
12 ✔
3695
    }
16 ✔
3696

26 ✔
3697
    protected async insertViewDefinitionSql(view: View): Promise<Query> {
26 ✔
3698
        const parsedTableName = this.driver.parseTableName(view)
16 ✔
3699

16 ✔
3700
        if (!parsedTableName.schema) {
16 !
UNCOV
3701
            parsedTableName.schema = await this.getCurrentSchema()
×
UNCOV
3702
        }
×
3703

16 ✔
3704
        const expression =
16 ✔
3705
            typeof view.expression === "string"
16 ✔
3706
                ? view.expression.trim()
16 ✔
3707
                : view.expression(this.connection).getQuery()
16 ✔
3708
        return this.insertTypeormMetadataSql({
16 ✔
3709
            type: MetadataTableType.VIEW,
16 ✔
3710
            database: parsedTableName.database,
16 ✔
3711
            schema: parsedTableName.schema,
16 ✔
3712
            name: parsedTableName.tableName,
16 ✔
3713
            value: expression,
16 ✔
3714
        })
16 ✔
3715
    }
16 ✔
3716

26 ✔
3717
    /**
26 ✔
3718
     * Builds drop view sql.
26 ✔
3719
     */
26 ✔
3720
    protected dropViewSql(viewOrPath: View | string): Query {
26 ✔
3721
        return new Query(`DROP VIEW ${this.escapePath(viewOrPath)}`)
16 ✔
3722
    }
16 ✔
3723

26 ✔
3724
    /**
26 ✔
3725
     * Builds remove view sql.
26 ✔
3726
     */
26 ✔
3727
    protected async deleteViewDefinitionSql(
26 ✔
3728
        viewOrPath: View | string,
16 ✔
3729
    ): Promise<Query> {
16 ✔
3730
        const parsedTableName = this.driver.parseTableName(viewOrPath)
16 ✔
3731

16 ✔
3732
        if (!parsedTableName.schema) {
16 !
UNCOV
3733
            parsedTableName.schema = await this.getCurrentSchema()
×
UNCOV
3734
        }
×
3735

16 ✔
3736
        return this.deleteTypeormMetadataSql({
16 ✔
3737
            type: MetadataTableType.VIEW,
16 ✔
3738
            database: parsedTableName.database,
16 ✔
3739
            schema: parsedTableName.schema,
16 ✔
3740
            name: parsedTableName.tableName,
16 ✔
3741
        })
16 ✔
3742
    }
16 ✔
3743

26 ✔
3744
    /**
26 ✔
3745
     * Builds create index sql.
26 ✔
3746
     */
26 ✔
3747
    protected createIndexSql(table: Table, index: TableIndex): Query {
26 ✔
3748
        const columns = index.columnNames
4,506 ✔
3749
            .map((columnName) => `"${columnName}"`)
4,506 ✔
3750
            .join(", ")
4,506 ✔
3751
        return new Query(
4,506 ✔
3752
            `CREATE ${index.isUnique ? "UNIQUE " : ""}INDEX "${
4,506 ✔
3753
                index.name
4,506 ✔
3754
            }" ON ${this.escapePath(table)} (${columns}) ${
4,506 ✔
3755
                index.where ? "WHERE " + index.where : ""
4,506 ✔
3756
            }`,
4,506 ✔
3757
        )
4,506 ✔
3758
    }
4,506 ✔
3759

26 ✔
3760
    /**
26 ✔
3761
     * Builds drop index sql.
26 ✔
3762
     */
26 ✔
3763
    protected dropIndexSql(
26 ✔
3764
        table: Table,
4,506 ✔
3765
        indexOrName: TableIndex | string,
4,506 ✔
3766
    ): Query {
4,506 ✔
3767
        const indexName = InstanceChecker.isTableIndex(indexOrName)
4,506 ✔
3768
            ? indexOrName.name
4,506 ✔
3769
            : indexOrName
4,506 !
3770
        return new Query(
4,506 ✔
3771
            `DROP INDEX "${indexName}" ON ${this.escapePath(table)}`,
4,506 ✔
3772
        )
4,506 ✔
3773
    }
4,506 ✔
3774

26 ✔
3775
    /**
26 ✔
3776
     * Builds create primary key sql.
26 ✔
3777
     */
26 ✔
3778
    protected createPrimaryKeySql(
26 ✔
3779
        table: Table,
10 ✔
3780
        columnNames: string[],
10 ✔
3781
        constraintName?: string,
10 ✔
3782
    ): Query {
10 ✔
3783
        const primaryKeyName = constraintName
10 ✔
3784
            ? constraintName
10 !
3785
            : this.connection.namingStrategy.primaryKeyName(table, columnNames)
10 ✔
3786

10 ✔
3787
        const columnNamesString = columnNames
10 ✔
3788
            .map((columnName) => `"${columnName}"`)
10 ✔
3789
            .join(", ")
10 ✔
3790
        return new Query(
10 ✔
3791
            `ALTER TABLE ${this.escapePath(
10 ✔
3792
                table,
10 ✔
3793
            )} ADD CONSTRAINT "${primaryKeyName}" PRIMARY KEY (${columnNamesString})`,
10 ✔
3794
        )
10 ✔
3795
    }
10 ✔
3796

26 ✔
3797
    /**
26 ✔
3798
     * Builds drop primary key sql.
26 ✔
3799
     */
26 ✔
3800
    protected dropPrimaryKeySql(table: Table): Query {
26 ✔
3801
        const columnNames = table.primaryColumns.map((column) => column.name)
10 ✔
3802
        const constraintName = table.primaryColumns[0].primaryKeyConstraintName
10 ✔
3803
        const primaryKeyName = constraintName
10 ✔
3804
            ? constraintName
10 !
3805
            : this.connection.namingStrategy.primaryKeyName(table, columnNames)
10 ✔
3806

10 ✔
3807
        return new Query(
10 ✔
3808
            `ALTER TABLE ${this.escapePath(
10 ✔
3809
                table,
10 ✔
3810
            )} DROP CONSTRAINT "${primaryKeyName}"`,
10 ✔
3811
        )
10 ✔
3812
    }
10 ✔
3813

26 ✔
3814
    /**
26 ✔
3815
     * Builds create unique constraint sql.
26 ✔
3816
     */
26 ✔
3817
    protected createUniqueConstraintSql(
26 ✔
3818
        table: Table,
38 ✔
3819
        uniqueConstraint: TableUnique,
38 ✔
3820
    ): Query {
38 ✔
3821
        const columnNames = uniqueConstraint.columnNames
38 ✔
3822
            .map((column) => `"` + column + `"`)
38 ✔
3823
            .join(", ")
38 ✔
3824
        return new Query(
38 ✔
3825
            `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${
38 ✔
3826
                uniqueConstraint.name
38 ✔
3827
            }" UNIQUE (${columnNames})`,
38 ✔
3828
        )
38 ✔
3829
    }
38 ✔
3830

26 ✔
3831
    /**
26 ✔
3832
     * Builds drop unique constraint sql.
26 ✔
3833
     */
26 ✔
3834
    protected dropUniqueConstraintSql(
26 ✔
3835
        table: Table,
38 ✔
3836
        uniqueOrName: TableUnique | string,
38 ✔
3837
    ): Query {
38 ✔
3838
        const uniqueName = InstanceChecker.isTableUnique(uniqueOrName)
38 ✔
3839
            ? uniqueOrName.name
38 ✔
3840
            : uniqueOrName
38 !
3841
        return new Query(
38 ✔
3842
            `ALTER TABLE ${this.escapePath(
38 ✔
3843
                table,
38 ✔
3844
            )} DROP CONSTRAINT "${uniqueName}"`,
38 ✔
3845
        )
38 ✔
3846
    }
38 ✔
3847

26 ✔
3848
    /**
26 ✔
3849
     * Builds create check constraint sql.
26 ✔
3850
     */
26 ✔
3851
    protected createCheckConstraintSql(
26 ✔
3852
        table: Table,
24 ✔
3853
        checkConstraint: TableCheck,
24 ✔
3854
    ): Query {
24 ✔
3855
        return new Query(
24 ✔
3856
            `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${
24 ✔
3857
                checkConstraint.name
24 ✔
3858
            }" CHECK (${checkConstraint.expression})`,
24 ✔
3859
        )
24 ✔
3860
    }
24 ✔
3861

26 ✔
3862
    /**
26 ✔
3863
     * Builds drop check constraint sql.
26 ✔
3864
     */
26 ✔
3865
    protected dropCheckConstraintSql(
26 ✔
3866
        table: Table,
24 ✔
3867
        checkOrName: TableCheck | string,
24 ✔
3868
    ): Query {
24 ✔
3869
        const checkName = InstanceChecker.isTableCheck(checkOrName)
24 ✔
3870
            ? checkOrName.name
24 ✔
3871
            : checkOrName
24 !
3872
        return new Query(
24 ✔
3873
            `ALTER TABLE ${this.escapePath(
24 ✔
3874
                table,
24 ✔
3875
            )} DROP CONSTRAINT "${checkName}"`,
24 ✔
3876
        )
24 ✔
3877
    }
24 ✔
3878

26 ✔
3879
    /**
26 ✔
3880
     * Builds create foreign key sql.
26 ✔
3881
     */
26 ✔
3882
    protected createForeignKeySql(
26 ✔
3883
        table: Table,
6,788 ✔
3884
        foreignKey: TableForeignKey,
6,788 ✔
3885
    ): Query {
6,788 ✔
3886
        const columnNames = foreignKey.columnNames
6,788 ✔
3887
            .map((column) => `"` + column + `"`)
6,788 ✔
3888
            .join(", ")
6,788 ✔
3889
        const referencedColumnNames = foreignKey.referencedColumnNames
6,788 ✔
3890
            .map((column) => `"` + column + `"`)
6,788 ✔
3891
            .join(",")
6,788 ✔
3892
        let sql =
6,788 ✔
3893
            `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${
6,788 ✔
3894
                foreignKey.name
6,788 ✔
3895
            }" FOREIGN KEY (${columnNames}) ` +
6,788 ✔
3896
            `REFERENCES ${this.escapePath(
6,788 ✔
3897
                this.getTablePath(foreignKey),
6,788 ✔
3898
            )}(${referencedColumnNames})`
6,788 ✔
3899
        if (foreignKey.onDelete) sql += ` ON DELETE ${foreignKey.onDelete}`
6,788 ✔
3900
        if (foreignKey.onUpdate) sql += ` ON UPDATE ${foreignKey.onUpdate}`
6,788 ✔
3901

6,788 ✔
3902
        return new Query(sql)
6,788 ✔
3903
    }
6,788 ✔
3904

26 ✔
3905
    /**
26 ✔
3906
     * Builds drop foreign key sql.
26 ✔
3907
     */
26 ✔
3908
    protected dropForeignKeySql(
26 ✔
3909
        table: Table,
6,798 ✔
3910
        foreignKeyOrName: TableForeignKey | string,
6,798 ✔
3911
    ): Query {
6,798 ✔
3912
        const foreignKeyName = InstanceChecker.isTableForeignKey(
6,798 ✔
3913
            foreignKeyOrName,
6,798 ✔
3914
        )
6,798 ✔
3915
            ? foreignKeyOrName.name
6,798 ✔
3916
            : foreignKeyOrName
6,798 !
3917
        return new Query(
6,798 ✔
3918
            `ALTER TABLE ${this.escapePath(
6,798 ✔
3919
                table,
6,798 ✔
3920
            )} DROP CONSTRAINT "${foreignKeyName}"`,
6,798 ✔
3921
        )
6,798 ✔
3922
    }
6,798 ✔
3923

26 ✔
3924
    /**
26 ✔
3925
     * Escapes given table or View path.
26 ✔
3926
     */
26 ✔
3927
    protected escapePath(target: Table | View | string): string {
26 ✔
3928
        const { database, schema, tableName } =
50,480 ✔
3929
            this.driver.parseTableName(target)
50,480 ✔
3930

50,480 ✔
3931
        if (database && database !== this.driver.database) {
50,480 ✔
3932
            if (schema && schema !== this.driver.searchSchema) {
96 ✔
3933
                return `"${database}"."${schema}"."${tableName}"`
84 ✔
3934
            }
84 ✔
3935

12 ✔
3936
            return `"${database}".."${tableName}"`
12 ✔
3937
        }
12 ✔
3938

50,384 ✔
3939
        if (schema && schema !== this.driver.searchSchema) {
50,480 ✔
3940
            return `"${schema}"."${tableName}"`
140 ✔
3941
        }
140 ✔
3942

50,244 ✔
3943
        return `"${tableName}"`
50,244 ✔
3944
    }
50,244 ✔
3945

26 ✔
3946
    /**
26 ✔
3947
     * Concat database name and schema name to the foreign key name.
26 ✔
3948
     * Needs because FK name is relevant to the schema and database.
26 ✔
3949
     */
26 ✔
3950
    protected buildForeignKeyName(
26 ✔
3951
        fkName: string,
8 ✔
3952
        schemaName: string | undefined,
8 ✔
3953
        dbName: string | undefined,
8 ✔
3954
    ): string {
8 ✔
3955
        let joinedFkName = fkName
8 ✔
3956
        if (schemaName && schemaName !== this.driver.searchSchema)
8 ✔
3957
            joinedFkName = schemaName + "." + joinedFkName
8 ✔
3958
        if (dbName && dbName !== this.driver.database)
8 ✔
3959
            joinedFkName = dbName + "." + joinedFkName
8 ✔
3960

8 ✔
3961
        return joinedFkName
8 ✔
3962
    }
8 ✔
3963

26 ✔
3964
    /**
26 ✔
3965
     * Removes parenthesis around default value.
26 ✔
3966
     * Sql server returns default value with parenthesis around, e.g.
26 ✔
3967
     *  ('My text') - for string
26 ✔
3968
     *  ((1)) - for number
26 ✔
3969
     *  (newsequentialId()) - for function
26 ✔
3970
     */
26 ✔
3971
    protected removeParenthesisFromDefault(defaultValue: string): any {
26 ✔
3972
        if (defaultValue.substr(0, 1) !== "(") return defaultValue
428 ✔
3973
        const normalizedDefault = defaultValue.substr(
216 ✔
3974
            1,
216 ✔
3975
            defaultValue.lastIndexOf(")") - 1,
216 ✔
3976
        )
216 ✔
3977
        return this.removeParenthesisFromDefault(normalizedDefault)
216 ✔
3978
    }
216 ✔
3979

26 ✔
3980
    /**
26 ✔
3981
     * Builds a query for create column.
26 ✔
3982
     */
26 ✔
3983
    protected buildCreateColumnSql(
26 ✔
3984
        table: Table,
32,922 ✔
3985
        column: TableColumn,
32,922 ✔
3986
        skipIdentity: boolean,
32,922 ✔
3987
        createDefault: boolean,
32,922 ✔
3988
        skipEnum?: boolean,
32,922 ✔
3989
    ) {
32,922 ✔
3990
        let c = `"${column.name}" ${this.connection.driver.createFullType(
32,922 ✔
3991
            column,
32,922 ✔
3992
        )}`
32,922 ✔
3993

32,922 ✔
3994
        if (!skipEnum && column.enum) {
32,922 ✔
3995
            const expression = this.getEnumExpression(column)
48 ✔
3996
            const checkName =
48 ✔
3997
                this.connection.namingStrategy.checkConstraintName(
48 ✔
3998
                    table,
48 ✔
3999
                    expression,
48 ✔
4000
                    true,
48 ✔
4001
                )
48 ✔
4002
            c += ` CONSTRAINT ${checkName} CHECK(${expression})`
48 ✔
4003
        }
48 ✔
4004

32,922 ✔
4005
        if (column.collation) c += " COLLATE " + column.collation
32,922 ✔
4006

32,922 ✔
4007
        if (column.asExpression) {
32,922 ✔
4008
            c += ` AS (${column.asExpression})`
78 ✔
4009
            if (column.generatedType === "STORED") {
78 ✔
4010
                c += ` PERSISTED`
42 ✔
4011

42 ✔
4012
                // NOT NULL can be specified for computed columns only if PERSISTED is also specified
42 ✔
4013
                if (column.isNullable !== true) c += " NOT NULL"
42 ✔
4014
            }
42 ✔
4015
        } else {
32,922 ✔
4016
            if (column.isNullable !== true) c += " NOT NULL"
32,844 ✔
4017
        }
32,844 ✔
4018

32,922 ✔
4019
        if (
32,922 ✔
4020
            column.isGenerated === true &&
32,922 ✔
4021
            column.generationStrategy === "increment" &&
32,922 ✔
4022
            !skipIdentity
6,004 ✔
4023
        )
32,922 ✔
4024
            // don't use skipPrimary here since updates can update already exist primary without auto inc.
32,922 ✔
4025
            c += " IDENTITY(1,1)"
32,922 ✔
4026

32,922 ✔
4027
        if (
32,922 ✔
4028
            column.default !== undefined &&
32,922 ✔
4029
            column.default !== null &&
32,922 ✔
4030
            createDefault
1,968 ✔
4031
        ) {
32,922 ✔
4032
            // we create named constraint to be able to delete this constraint when column been dropped
1,956 ✔
4033
            const defaultName =
1,956 ✔
4034
                this.connection.namingStrategy.defaultConstraintName(
1,956 ✔
4035
                    table,
1,956 ✔
4036
                    column.name,
1,956 ✔
4037
                )
1,956 ✔
4038
            c += ` CONSTRAINT "${defaultName}" DEFAULT ${column.default}`
1,956 ✔
4039
        }
1,956 ✔
4040

32,922 ✔
4041
        if (
32,922 ✔
4042
            column.isGenerated &&
32,922 ✔
4043
            column.generationStrategy === "uuid" &&
32,922 ✔
4044
            !column.default
256 ✔
4045
        ) {
32,922 ✔
4046
            // we create named constraint to be able to delete this constraint when column been dropped
256 ✔
4047
            const defaultName =
256 ✔
4048
                this.connection.namingStrategy.defaultConstraintName(
256 ✔
4049
                    table,
256 ✔
4050
                    column.name,
256 ✔
4051
                )
256 ✔
4052
            c += ` CONSTRAINT "${defaultName}" DEFAULT NEWSEQUENTIALID()`
256 ✔
4053
        }
256 ✔
4054
        return c
32,922 ✔
4055
    }
32,922 ✔
4056

26 ✔
4057
    private getEnumExpression(column: TableColumn) {
26 ✔
4058
        if (!column.enum) {
52 !
UNCOV
4059
            throw new Error(`Enum is not defined in column ${column.name}`)
×
UNCOV
4060
        }
×
4061
        return (
52 ✔
4062
            column.name +
52 ✔
4063
            " IN (" +
52 ✔
4064
            column.enum.map((val) => "'" + val + "'").join(",") +
52 ✔
4065
            ")"
52 ✔
4066
        )
52 ✔
4067
    }
52 ✔
4068

26 ✔
4069
    protected isEnumCheckConstraint(name: string): boolean {
26 ✔
4070
        return name.indexOf("CHK_") !== -1 && name.indexOf("_ENUM") !== -1
206 ✔
4071
    }
206 ✔
4072

26 ✔
4073
    /**
26 ✔
4074
     * Converts MssqlParameter into real mssql parameter type.
26 ✔
4075
     */
26 ✔
4076
    protected mssqlParameterToNativeParameter(parameter: MssqlParameter): any {
26 ✔
4077
        switch (this.driver.normalizeType({ type: parameter.type as any })) {
53,058 ✔
4078
            case "bit":
53,058 ✔
4079
                return this.driver.mssql.Bit
4,054 ✔
4080
            case "bigint":
53,058 ✔
4081
                return this.driver.mssql.BigInt
64 ✔
4082
            case "decimal":
53,058 ✔
4083
                return this.driver.mssql.Decimal(...parameter.params)
8 ✔
4084
            case "float":
53,058 ✔
4085
                return this.driver.mssql.Float
60 ✔
4086
            case "int":
53,058 ✔
4087
                return this.driver.mssql.Int
24,014 ✔
4088
            case "money":
53,058 ✔
4089
                return this.driver.mssql.Money
2 ✔
4090
            case "numeric":
53,058 ✔
4091
                return this.driver.mssql.Numeric(...parameter.params)
4 ✔
4092
            case "smallint":
53,058 ✔
4093
                return this.driver.mssql.SmallInt
2 ✔
4094
            case "smallmoney":
53,058 ✔
4095
                return this.driver.mssql.SmallMoney
2 ✔
4096
            case "real":
53,058 ✔
4097
                return this.driver.mssql.Real
2 ✔
4098
            case "tinyint":
53,058 ✔
4099
                return this.driver.mssql.TinyInt
2 ✔
4100
            case "char":
53,058 ✔
4101
                if (
10 ✔
4102
                    this.driver.options.options
10 ✔
4103
                        ?.disableAsciiToUnicodeParamConversion
10 ✔
4104
                ) {
10 ✔
4105
                    return this.driver.mssql.Char(...parameter.params)
2 ✔
4106
                }
2 ✔
4107
                return this.driver.mssql.NChar(...parameter.params)
8 ✔
4108
            case "nchar":
53,058 ✔
4109
                return this.driver.mssql.NChar(...parameter.params)
4 ✔
4110
            case "text":
53,058 ✔
4111
                if (
10 ✔
4112
                    this.driver.options.options
10 ✔
4113
                        ?.disableAsciiToUnicodeParamConversion
10 !
4114
                ) {
10 !
UNCOV
4115
                    return this.driver.mssql.Text
×
UNCOV
4116
                }
×
4117
                return this.driver.mssql.Ntext
10 ✔
4118
            case "ntext":
53,058 ✔
4119
                return this.driver.mssql.Ntext
14 ✔
4120
            case "varchar":
53,058 ✔
4121
                if (
170 ✔
4122
                    this.driver.options.options
170 ✔
4123
                        ?.disableAsciiToUnicodeParamConversion
170 ✔
4124
                ) {
170 ✔
4125
                    return this.driver.mssql.VarChar(...parameter.params)
2 ✔
4126
                }
2 ✔
4127
                return this.driver.mssql.NVarChar(...parameter.params)
168 ✔
4128
            case "nvarchar":
53,058 ✔
4129
                return this.driver.mssql.NVarChar(...parameter.params)
23,962 ✔
4130
            case "xml":
53,058 !
UNCOV
4131
                return this.driver.mssql.Xml
×
4132
            case "time":
53,058 ✔
4133
                return this.driver.mssql.Time(...parameter.params)
12 ✔
4134
            case "date":
53,058 ✔
4135
                return this.driver.mssql.Date
10 ✔
4136
            case "datetime":
53,058 ✔
4137
                return this.driver.mssql.DateTime
44 ✔
4138
            case "datetime2":
53,058 ✔
4139
                return this.driver.mssql.DateTime2(...parameter.params)
24 ✔
4140
            case "datetimeoffset":
53,058 ✔
4141
                return this.driver.mssql.DateTimeOffset(...parameter.params)
8 ✔
4142
            case "smalldatetime":
53,058 ✔
4143
                return this.driver.mssql.SmallDateTime
2 ✔
4144
            case "uniqueidentifier":
53,058 ✔
4145
                return this.driver.mssql.UniqueIdentifier
502 ✔
4146
            case "variant":
53,058 !
UNCOV
4147
                return this.driver.mssql.Variant
×
4148
            case "binary":
53,058 ✔
4149
                return this.driver.mssql.Binary
26 ✔
4150
            case "varbinary":
53,058 ✔
4151
                return this.driver.mssql.VarBinary(...parameter.params)
4 ✔
4152
            case "image":
53,058 ✔
4153
                return this.driver.mssql.Image
2 ✔
4154
            case "udt":
53,058 !
UNCOV
4155
                return this.driver.mssql.UDT
×
4156
            case "rowversion":
53,058 !
UNCOV
4157
                return this.driver.mssql.RowVersion
×
4158
            case "vector":
53,058 ✔
4159
                return this.driver.mssql.Ntext
20 ✔
4160
        }
53,058 ✔
4161
    }
53,058 ✔
4162

26 ✔
4163
    /**
26 ✔
4164
     * Converts string literal of isolation level to enum.
26 ✔
4165
     * The underlying mssql driver requires an enum for the isolation level.
26 ✔
4166
     */
26 ✔
4167
    convertIsolationLevel(isolation: IsolationLevel) {
26 ✔
4168
        const ISOLATION_LEVEL = this.driver.mssql.ISOLATION_LEVEL
12 ✔
4169
        switch (isolation) {
12 ✔
4170
            case "READ UNCOMMITTED":
12 ✔
4171
                return ISOLATION_LEVEL.READ_UNCOMMITTED
4 ✔
4172
            case "REPEATABLE READ":
12 ✔
4173
                return ISOLATION_LEVEL.REPEATABLE_READ
2 ✔
4174
            case "SERIALIZABLE":
12 ✔
4175
                return ISOLATION_LEVEL.SERIALIZABLE
4 ✔
4176

12 ✔
4177
            case "READ COMMITTED":
12 ✔
4178
            default:
12 ✔
4179
                return ISOLATION_LEVEL.READ_COMMITTED
2 ✔
4180
        }
12 ✔
4181
    }
12 ✔
4182

26 ✔
4183
    /**
26 ✔
4184
     * Change table comment.
26 ✔
4185
     */
26 ✔
4186
    changeTableComment(
26 ✔
UNCOV
4187
        tableOrName: Table | string,
×
UNCOV
4188
        comment?: string,
×
UNCOV
4189
    ): Promise<void> {
×
UNCOV
4190
        throw new TypeORMError(
×
UNCOV
4191
            `sqlserver driver does not support change table comment.`,
×
UNCOV
4192
        )
×
UNCOV
4193
    }
×
4194
}
26 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc