/
PostgresQueryRunner.ts
2093 lines (1788 loc) · 106 KB
/
PostgresQueryRunner.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {PromiseUtils} from "../../";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {QueryFailedError} from "../../error/QueryFailedError";
import {QueryRunnerAlreadyReleasedError} from "../../error/QueryRunnerAlreadyReleasedError";
import {TransactionAlreadyStartedError} from "../../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../../error/TransactionNotStartedError";
import {ColumnType} from "../../index";
import {ReadStream} from "../../platform/PlatformTools";
import {BaseQueryRunner} from "../../query-runner/BaseQueryRunner";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {TableIndexOptions} from "../../schema-builder/options/TableIndexOptions";
import {Table} from "../../schema-builder/table/Table";
import {TableCheck} from "../../schema-builder/table/TableCheck";
import {TableColumn} from "../../schema-builder/table/TableColumn";
import {TableExclusion} from "../../schema-builder/table/TableExclusion";
import {TableForeignKey} from "../../schema-builder/table/TableForeignKey";
import {TableIndex} from "../../schema-builder/table/TableIndex";
import {TableUnique} from "../../schema-builder/table/TableUnique";
import {View} from "../../schema-builder/view/View";
import {Broadcaster} from "../../subscriber/Broadcaster";
import {OrmUtils} from "../../util/OrmUtils";
import {Query} from "../Query";
import {IsolationLevel} from "../types/IsolationLevel";
import {PostgresDriver} from "./PostgresDriver";
/**
* Runs queries on a single postgres database connection.
*/
export class PostgresQueryRunner extends BaseQueryRunner implements QueryRunner {
// -------------------------------------------------------------------------
// Public Implemented Properties
// -------------------------------------------------------------------------
/**
* Database driver used by connection.
*/
driver: PostgresDriver;
// -------------------------------------------------------------------------
// Protected Properties
// -------------------------------------------------------------------------
/**
* Promise used to obtain a database connection for a first time.
*/
protected databaseConnectionPromise: Promise<any>;
/**
* Special callback provided by a driver used to release a created connection.
*/
protected releaseCallback: Function;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(driver: PostgresDriver, mode: "master"|"slave" = "master") {
super();
this.driver = driver;
this.connection = driver.connection;
this.mode = mode;
this.broadcaster = new Broadcaster(this);
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates/uses database connection from the connection pool to perform further operations.
* Returns obtained database connection.
*/
connect(): Promise<any> {
if (this.databaseConnection)
return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise)
return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(([ connection, release]: any[]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = connection;
this.releaseCallback = release;
return this.databaseConnection;
});
} else { // master
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(([connection, release]: any[]) => {
this.driver.connectedQueryRunners.push(this);
this.databaseConnection = connection;
this.releaseCallback = release;
return this.databaseConnection;
});
}
return this.databaseConnectionPromise;
}
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
release(): Promise<void> {
this.isReleased = true;
if (this.releaseCallback)
this.releaseCallback();
const index = this.driver.connectedQueryRunners.indexOf(this);
if (index !== -1) this.driver.connectedQueryRunners.splice(index);
return Promise.resolve();
}
/**
* Starts transaction.
*/
async startTransaction(isolationLevel?: IsolationLevel): Promise<void> {
if (this.isTransactionActive)
throw new TransactionAlreadyStartedError();
this.isTransactionActive = true;
await this.query("START TRANSACTION");
if (isolationLevel) {
await this.query("SET TRANSACTION ISOLATION LEVEL " + isolationLevel);
}
}
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
async commitTransaction(): Promise<void> {
if (!this.isTransactionActive)
throw new TransactionNotStartedError();
await this.query("COMMIT");
this.isTransactionActive = false;
}
/**
* Rollbacks transaction.
* Error will be thrown if transaction was not started.
*/
async rollbackTransaction(): Promise<void> {
if (!this.isTransactionActive)
throw new TransactionNotStartedError();
await this.query("ROLLBACK");
this.isTransactionActive = false;
}
/**
* Executes a given SQL query.
*/
query(query: string, parameters?: any[]): Promise<any> {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError();
return new Promise<any[]>(async (ok, fail) => {
try {
const databaseConnection = await this.connect();
this.driver.connection.logger.logQuery(query, parameters, this);
const queryStartTime = +new Date();
databaseConnection.query(query, parameters, (err: any, result: any) => {
// log slow queries if maxQueryExecution time is set
const maxQueryExecutionTime = this.driver.connection.options.maxQueryExecutionTime;
const queryEndTime = +new Date();
const queryExecutionTime = queryEndTime - queryStartTime;
if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)
this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
if (err) {
this.driver.connection.logger.logQueryError(err, query, parameters, this);
fail(new QueryFailedError(query, parameters, err));
} else {
switch (result.command) {
case "DELETE":
case "UPDATE":
// for UPDATE and DELETE query additionally return number of affected rows
ok([result.rows, result.rowCount]);
break;
default:
ok(result.rows);
}
}
});
} catch (err) {
fail(err);
}
});
}
/**
* Returns raw data stream.
*/
stream(query: string, parameters?: any[], onEnd?: Function, onError?: Function): Promise<ReadStream> {
const QueryStream = this.driver.loadStreamDependency();
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError();
return new Promise(async (ok, fail) => {
try {
const databaseConnection = await this.connect();
this.driver.connection.logger.logQuery(query, parameters, this);
const stream = databaseConnection.query(new QueryStream(query, parameters));
if (onEnd) stream.on("end", onEnd);
if (onError) stream.on("error", onError);
ok(stream);
} catch (err) {
fail(err);
}
});
}
/**
* Returns all available database names including system databases.
*/
async getDatabases(): Promise<string[]> {
return Promise.resolve([]);
}
/**
* Returns all available schema names including system schemas.
* If database parameter specified, returns schemas of that database.
*/
async getSchemas(database?: string): Promise<string[]> {
return Promise.resolve([]);
}
/**
* Checks if database with the given name exist.
*/
async hasDatabase(database: string): Promise<boolean> {
return Promise.resolve(false);
}
/**
* Checks if schema with the given name exist.
*/
async hasSchema(schema: string): Promise<boolean> {
const result = await this.query(`SELECT * FROM "information_schema"."schemata" WHERE "schema_name" = '${schema}'`);
return result.length ? true : false;
}
/**
* Checks if table with the given name exist in the database.
*/
async hasTable(tableOrName: Table|string): Promise<boolean> {
const parsedTableName = this.parseTableName(tableOrName);
const sql = `SELECT * FROM "information_schema"."tables" WHERE "table_schema" = ${parsedTableName.schema} AND "table_name" = ${parsedTableName.tableName}`;
const result = await this.query(sql);
return result.length ? true : false;
}
/**
* Checks if column with the given name exist in the given table.
*/
async hasColumn(tableOrName: Table|string, columnName: string): Promise<boolean> {
const parsedTableName = this.parseTableName(tableOrName);
const sql = `SELECT * FROM "information_schema"."columns" WHERE "table_schema" = ${parsedTableName.schema} AND "table_name" = ${parsedTableName.tableName} AND "column_name" = '${columnName}'`;
const result = await this.query(sql);
return result.length ? true : false;
}
/**
* Creates a new database.
* Postgres does not supports database creation inside a transaction block.
*/
async createDatabase(database: string, ifNotExist?: boolean): Promise<void> {
await Promise.resolve();
}
/**
* Drops database.
* Postgres does not supports database drop inside a transaction block.
*/
async dropDatabase(database: string, ifExist?: boolean): Promise<void> {
return Promise.resolve();
}
/**
* Creates a new table schema.
*/
async createSchema(schema: string, ifNotExist?: boolean): Promise<void> {
const up = ifNotExist ? `CREATE SCHEMA IF NOT EXISTS "${schema}"` : `CREATE SCHEMA "${schema}"`;
const down = `DROP SCHEMA "${schema}" CASCADE`;
await this.executeQueries(new Query(up), new Query(down));
}
/**
* Drops table schema.
*/
async dropSchema(schemaPath: string, ifExist?: boolean, isCascade?: boolean): Promise<void> {
const schema = schemaPath.indexOf(".") === -1 ? schemaPath : schemaPath.split(".")[0];
const up = ifExist ? `DROP SCHEMA IF EXISTS "${schema}" ${isCascade ? "CASCADE" : ""}` : `DROP SCHEMA "${schema}" ${isCascade ? "CASCADE" : ""}`;
const down = `CREATE SCHEMA "${schema}"`;
await this.executeQueries(new Query(up), new Query(down));
}
/**
* Creates a new table.
*/
async createTable(table: Table, ifNotExist: boolean = false, createForeignKeys: boolean = true, createIndices: boolean = true): Promise<void> {
if (ifNotExist) {
const isTableExist = await this.hasTable(table);
if (isTableExist) return Promise.resolve();
}
const upQueries: Query[] = [];
const downQueries: Query[] = [];
// if table have column with ENUM type, we must create this type in postgres.
await Promise.all(table.columns
.filter(column => column.type === "enum" || column.type === "simple-enum")
.map(async column => {
const hasEnum = await this.hasEnumType(table, column);
// TODO: Should also check if values of existing type matches expected ones
if (!hasEnum) {
upQueries.push(this.createEnumTypeSql(table, column));
downQueries.push(this.dropEnumTypeSql(table, column));
}
return Promise.resolve();
}));
upQueries.push(this.createTableSql(table, createForeignKeys));
downQueries.push(this.dropTableSql(table));
// if createForeignKeys is true, we must drop created foreign keys in down query.
// createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
if (createForeignKeys)
table.foreignKeys.forEach(foreignKey => downQueries.push(this.dropForeignKeySql(table, foreignKey)));
if (createIndices) {
table.indices.forEach(index => {
// new index may be passed without name. In this case we generate index name manually.
if (!index.name)
index.name = this.connection.namingStrategy.indexName(table.name, index.columnNames, index.where);
upQueries.push(this.createIndexSql(table, index));
downQueries.push(this.dropIndexSql(table, index));
});
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Drops the table.
*/
async dropTable(target: Table|string, ifExist?: boolean, dropForeignKeys: boolean = true, dropIndices: boolean = true): Promise<void> {// It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
// to perform drop queries for foreign keys and indices.
if (ifExist) {
const isTableExist = await this.hasTable(target);
if (!isTableExist) return Promise.resolve();
}
// if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
const createForeignKeys: boolean = dropForeignKeys;
const tableName = target instanceof Table ? target.name : target;
const table = await this.getCachedTable(tableName);
const upQueries: Query[] = [];
const downQueries: Query[] = [];
if (dropIndices) {
table.indices.forEach(index => {
upQueries.push(this.dropIndexSql(table, index));
downQueries.push(this.createIndexSql(table, index));
});
}
if (dropForeignKeys)
table.foreignKeys.forEach(foreignKey => upQueries.push(this.dropForeignKeySql(table, foreignKey)));
upQueries.push(this.dropTableSql(table));
downQueries.push(this.createTableSql(table, createForeignKeys));
await this.executeQueries(upQueries, downQueries);
}
/**
* Creates a new view.
*/
async createView(view: View): Promise<void> {
const upQueries: Query[] = [];
const downQueries: Query[] = [];
upQueries.push(this.createViewSql(view));
upQueries.push(await this.insertViewDefinitionSql(view));
downQueries.push(this.dropViewSql(view));
downQueries.push(await this.deleteViewDefinitionSql(view));
await this.executeQueries(upQueries, downQueries);
}
/**
* Drops the view.
*/
async dropView(target: View|string): Promise<void> {
const viewName = target instanceof View ? target.name : target;
const view = await this.getCachedView(viewName);
const upQueries: Query[] = [];
const downQueries: Query[] = [];
upQueries.push(await this.deleteViewDefinitionSql(view));
upQueries.push(this.dropViewSql(view));
downQueries.push(await this.insertViewDefinitionSql(view));
downQueries.push(this.createViewSql(view));
await this.executeQueries(upQueries, downQueries);
}
/**
* Renames the given table.
*/
async renameTable(oldTableOrName: Table|string, newTableName: string): Promise<void> {
const upQueries: Query[] = [];
const downQueries: Query[] = [];
const oldTable = oldTableOrName instanceof Table ? oldTableOrName : await this.getCachedTable(oldTableOrName);
const newTable = oldTable.clone();
const oldTableName = oldTable.name.indexOf(".") === -1 ? oldTable.name : oldTable.name.split(".")[1];
const schemaName = oldTable.name.indexOf(".") === -1 ? undefined : oldTable.name.split(".")[0];
newTable.name = schemaName ? `${schemaName}.${newTableName}` : newTableName;
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(oldTable)} RENAME TO "${newTableName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME TO "${oldTableName}"`));
// rename column primary key constraint
if (newTable.primaryColumns.length > 0) {
const columnNames = newTable.primaryColumns.map(column => column.name);
const oldPkName = this.connection.namingStrategy.primaryKeyName(oldTable, columnNames);
const newPkName = this.connection.namingStrategy.primaryKeyName(newTable, columnNames);
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${oldPkName}" TO "${newPkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${newPkName}" TO "${oldPkName}"`));
}
// rename unique constraints
newTable.uniques.forEach(unique => {
// build new constraint name
const newUniqueName = this.connection.namingStrategy.uniqueConstraintName(newTable, unique.columnNames);
// build queries
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${unique.name}" TO "${newUniqueName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${newUniqueName}" TO "${unique.name}"`));
// replace constraint name
unique.name = newUniqueName;
});
// rename index constraints
newTable.indices.forEach(index => {
// build new constraint name
const schema = this.extractSchema(newTable);
const newIndexName = this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
// build queries
const up = schema ? `ALTER INDEX "${schema}"."${index.name}" RENAME TO "${newIndexName}"` : `ALTER INDEX "${index.name}" RENAME TO "${newIndexName}"`;
const down = schema ? `ALTER INDEX "${schema}"."${newIndexName}" RENAME TO "${index.name}"` : `ALTER INDEX "${newIndexName}" RENAME TO "${index.name}"`;
upQueries.push(new Query(up));
downQueries.push(new Query(down));
// replace constraint name
index.name = newIndexName;
});
// rename foreign key constraints
newTable.foreignKeys.forEach(foreignKey => {
// build new constraint name
const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, foreignKey.referencedTableName, foreignKey.referencedColumnNames);
// build queries
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${foreignKey.name}" TO "${newForeignKeyName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(newTable)} RENAME CONSTRAINT "${newForeignKeyName}" TO "${foreignKey.name}"`));
// replace constraint name
foreignKey.name = newForeignKeyName;
});
// rename ENUM types
const enumColumns = newTable.columns.filter(column => column.type === "enum" || column.type === "simple-enum");
for (let column of enumColumns) {
const oldEnumType = await this.getEnumTypeName(oldTable, column);
upQueries.push(new Query(`ALTER TYPE "${oldEnumType.enumTypeSchema}"."${oldEnumType.enumTypeName}" RENAME TO ${this.buildEnumName(newTable, column, false)}`));
downQueries.push(new Query(`ALTER TYPE ${this.buildEnumName(newTable, column)} RENAME TO "${oldEnumType.enumTypeName}"`));
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Creates a new column from the column in the table.
*/
async addColumn(tableOrName: Table|string, column: TableColumn): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
const clonedTable = table.clone();
const upQueries: Query[] = [];
const downQueries: Query[] = [];
if (column.type === "enum" || column.type === "simple-enum") {
const hasEnum = await this.hasEnumType(table, column);
if (!hasEnum) {
upQueries.push(this.createEnumTypeSql(table, column));
downQueries.push(this.dropEnumTypeSql(table, column));
}
}
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(table, column)}`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN "${column.name}"`));
// create or update primary key constraint
if (column.isPrimary) {
const primaryColumns = clonedTable.primaryColumns;
// if table already have primary key, me must drop it and recreate again
if (primaryColumns.length > 0) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNames = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
}
primaryColumns.push(column);
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNames = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
}
// create column index
const columnIndex = clonedTable.indices.find(index => index.columnNames.length === 1 && index.columnNames[0] === column.name);
if (columnIndex) {
upQueries.push(this.createIndexSql(table, columnIndex));
downQueries.push(this.dropIndexSql(table, columnIndex));
}
// create unique constraint
if (column.isUnique) {
const uniqueConstraint = new TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(table.name, [column.name]),
columnNames: [column.name]
});
clonedTable.uniques.push(uniqueConstraint);
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${uniqueConstraint.name}" UNIQUE ("${column.name}")`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${uniqueConstraint.name}"`));
}
await this.executeQueries(upQueries, downQueries);
clonedTable.addColumn(column);
this.replaceCachedTable(table, clonedTable);
}
/**
* Creates a new columns from the column in the table.
*/
async addColumns(tableOrName: Table|string, columns: TableColumn[]): Promise<void> {
await PromiseUtils.runInSequence(columns, column => this.addColumn(tableOrName, column));
}
/**
* Renames column in the given table.
*/
async renameColumn(tableOrName: Table|string, oldTableColumnOrName: TableColumn|string, newTableColumnOrName: TableColumn|string): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
const oldColumn = oldTableColumnOrName instanceof TableColumn ? oldTableColumnOrName : table.columns.find(c => c.name === oldTableColumnOrName);
if (!oldColumn)
throw new Error(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
let newColumn;
if (newTableColumnOrName instanceof TableColumn) {
newColumn = newTableColumnOrName;
} else {
newColumn = oldColumn.clone();
newColumn.name = newTableColumnOrName;
}
return this.changeColumn(table, oldColumn, newColumn);
}
/**
* Changes a column in the table.
*/
async changeColumn(tableOrName: Table|string, oldTableColumnOrName: TableColumn|string, newColumn: TableColumn): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
let clonedTable = table.clone();
const upQueries: Query[] = [];
const downQueries: Query[] = [];
const oldColumn = oldTableColumnOrName instanceof TableColumn
? oldTableColumnOrName
: table.columns.find(column => column.name === oldTableColumnOrName);
if (!oldColumn)
throw new Error(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
if (oldColumn.type !== newColumn.type || oldColumn.length !== newColumn.length) {
// To avoid data conversion, we just recreate column
await this.dropColumn(table, oldColumn);
await this.addColumn(table, newColumn);
// update cloned table
clonedTable = table.clone();
} else {
if (oldColumn.name !== newColumn.name) {
// rename column
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME COLUMN "${oldColumn.name}" TO "${newColumn.name}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME COLUMN "${newColumn.name}" TO "${oldColumn.name}"`));
// rename ENUM type
if (oldColumn.type === "enum" || oldColumn.type === "simple-enum") {
const oldEnumType = await this.getEnumTypeName(table, oldColumn);
upQueries.push(new Query(`ALTER TYPE "${oldEnumType.enumTypeSchema}"."${oldEnumType.enumTypeName}" RENAME TO ${this.buildEnumName(table, newColumn, false)}`));
downQueries.push(new Query(`ALTER TYPE ${this.buildEnumName(table, newColumn)} RENAME TO "${oldEnumType.enumTypeName}"`));
}
// rename column primary key constraint
if (oldColumn.isPrimary === true) {
const primaryColumns = clonedTable.primaryColumns;
// build old primary constraint name
const columnNames = primaryColumns.map(column => column.name);
const oldPkName = this.connection.namingStrategy.primaryKeyName(clonedTable, columnNames);
// replace old column name with new column name
columnNames.splice(columnNames.indexOf(oldColumn.name), 1);
columnNames.push(newColumn.name);
// build new primary constraint name
const newPkName = this.connection.namingStrategy.primaryKeyName(clonedTable, columnNames);
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${oldPkName}" TO "${newPkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${newPkName}" TO "${oldPkName}"`));
}
// rename column sequence
if (oldColumn.isGenerated === true && newColumn.generationStrategy === "increment") {
const schema = this.extractSchema(table);
// building sequence name. Sequence without schema needed because it must be supplied in RENAME TO without
// schema name, but schema needed in ALTER SEQUENCE argument.
const seqName = this.buildSequenceName(table, oldColumn.name, undefined, true, true);
const newSeqName = this.buildSequenceName(table, newColumn.name, undefined, true, true);
const up = schema ? `ALTER SEQUENCE "${schema}"."${seqName}" RENAME TO "${newSeqName}"` : `ALTER SEQUENCE "${seqName}" RENAME TO "${newSeqName}"`;
const down = schema ? `ALTER SEQUENCE "${schema}"."${newSeqName}" RENAME TO "${seqName}"` : `ALTER SEQUENCE "${newSeqName}" RENAME TO "${seqName}"`;
upQueries.push(new Query(up));
downQueries.push(new Query(down));
}
// rename unique constraints
clonedTable.findColumnUniques(oldColumn).forEach(unique => {
// build new constraint name
unique.columnNames.splice(unique.columnNames.indexOf(oldColumn.name), 1);
unique.columnNames.push(newColumn.name);
const newUniqueName = this.connection.namingStrategy.uniqueConstraintName(clonedTable, unique.columnNames);
// build queries
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${unique.name}" TO "${newUniqueName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${newUniqueName}" TO "${unique.name}"`));
// replace constraint name
unique.name = newUniqueName;
});
// rename index constraints
clonedTable.findColumnIndices(oldColumn).forEach(index => {
// build new constraint name
index.columnNames.splice(index.columnNames.indexOf(oldColumn.name), 1);
index.columnNames.push(newColumn.name);
const schema = this.extractSchema(table);
const newIndexName = this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where);
// build queries
const up = schema ? `ALTER INDEX "${schema}"."${index.name}" RENAME TO "${newIndexName}"` : `ALTER INDEX "${index.name}" RENAME TO "${newIndexName}"`;
const down = schema ? `ALTER INDEX "${schema}"."${newIndexName}" RENAME TO "${index.name}"` : `ALTER INDEX "${newIndexName}" RENAME TO "${index.name}"`;
upQueries.push(new Query(up));
downQueries.push(new Query(down));
// replace constraint name
index.name = newIndexName;
});
// rename foreign key constraints
clonedTable.findColumnForeignKeys(oldColumn).forEach(foreignKey => {
// build new constraint name
foreignKey.columnNames.splice(foreignKey.columnNames.indexOf(oldColumn.name), 1);
foreignKey.columnNames.push(newColumn.name);
const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, foreignKey.referencedTableName, foreignKey.referencedColumnNames);
// build queries
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${foreignKey.name}" TO "${newForeignKeyName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} RENAME CONSTRAINT "${newForeignKeyName}" TO "${foreignKey.name}"`));
// replace constraint name
foreignKey.name = newForeignKeyName;
});
// rename old column in the Table object
const oldTableColumn = clonedTable.columns.find(column => column.name === oldColumn.name);
clonedTable.columns[clonedTable.columns.indexOf(oldTableColumn!)].name = newColumn.name;
oldColumn.name = newColumn.name;
}
if (newColumn.precision !== oldColumn.precision || newColumn.scale !== oldColumn.scale) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(newColumn)}`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(oldColumn)}`));
}
if (
(newColumn.type === "enum" || newColumn.type === "simple-enum")
&& (oldColumn.type === "enum" || oldColumn.type === "simple-enum")
&& !OrmUtils.isArraysEqual(newColumn.enum!, oldColumn.enum!)
) {
const enumName = this.buildEnumName(table, newColumn);
const arraySuffix = newColumn.isArray ? "[]" : "";
const oldEnumName = this.buildEnumName(table, newColumn, true, false, true);
const oldEnumNameWithoutSchema = this.buildEnumName(table, newColumn, false, false, true);
const enumTypeBeforeColumnChange = await this.getEnumTypeName(table, oldColumn);
// rename old ENUM
upQueries.push(new Query(`ALTER TYPE "${enumTypeBeforeColumnChange.enumTypeSchema}"."${enumTypeBeforeColumnChange.enumTypeName}" RENAME TO ${oldEnumNameWithoutSchema}`));
downQueries.push(new Query(`ALTER TYPE ${oldEnumName} RENAME TO "${enumTypeBeforeColumnChange.enumTypeName}"`));
// create new ENUM
upQueries.push(this.createEnumTypeSql(table, newColumn));
downQueries.push(this.dropEnumTypeSql(table, oldColumn));
// if column have default value, we must drop it to avoid issues with type casting
if (newColumn.default !== null && newColumn.default !== undefined) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT ${newColumn.default}`));
}
// build column types
const upType = `${enumName}${arraySuffix} USING "${newColumn.name}"::"text"::${enumName}${arraySuffix}`;
const downType = `${oldEnumName}${arraySuffix} USING "${newColumn.name}"::"text"::${oldEnumName}${arraySuffix}`;
// update column to use new type
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${upType}`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${downType}`));
// if column have default value and we dropped it before, we must bring it back
if (newColumn.default !== null && newColumn.default !== undefined) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT ${newColumn.default}`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
}
// remove old ENUM
upQueries.push(this.dropEnumTypeSql(table, newColumn, oldEnumName));
downQueries.push(this.createEnumTypeSql(table, oldColumn, oldEnumName));
}
if (oldColumn.isNullable !== newColumn.isNullable) {
if (newColumn.isNullable) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`));
} else {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`));
}
}
if (oldColumn.comment !== newColumn.comment) {
upQueries.push(new Query(`COMMENT ON COLUMN ${this.escapePath(table)}."${oldColumn.name}" IS '${newColumn.comment}'`));
downQueries.push(new Query(`COMMENT ON COLUMN ${this.escapePath(table)}."${newColumn.name}" IS '${oldColumn.comment}'`));
}
if (newColumn.isPrimary !== oldColumn.isPrimary) {
const primaryColumns = clonedTable.primaryColumns;
// if primary column state changed, we must always drop existed constraint.
if (primaryColumns.length > 0) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNames = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
}
if (newColumn.isPrimary === true) {
primaryColumns.push(newColumn);
// update column in table
const column = clonedTable.columns.find(column => column.name === newColumn.name);
column!.isPrimary = true;
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNames = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
} else {
const primaryColumn = primaryColumns.find(c => c.name === newColumn.name);
primaryColumns.splice(primaryColumns.indexOf(primaryColumn!), 1);
// update column in table
const column = clonedTable.columns.find(column => column.name === newColumn.name);
column!.isPrimary = false;
// if we have another primary keys, we must recreate constraint.
if (primaryColumns.length > 0) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNames = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
}
}
}
if (newColumn.isUnique !== oldColumn.isUnique) {
if (newColumn.isUnique === true) {
const uniqueConstraint = new TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(table.name, [newColumn.name]),
columnNames: [newColumn.name]
});
clonedTable.uniques.push(uniqueConstraint);
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${uniqueConstraint.name}" UNIQUE ("${newColumn.name}")`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${uniqueConstraint.name}"`));
} else {
const uniqueConstraint = clonedTable.uniques.find(unique => {
return unique.columnNames.length === 1 && !!unique.columnNames.find(columnName => columnName === newColumn.name);
});
clonedTable.uniques.splice(clonedTable.uniques.indexOf(uniqueConstraint!), 1);
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${uniqueConstraint!.name}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${uniqueConstraint!.name}" UNIQUE ("${newColumn.name}")`));
}
}
if (oldColumn.isGenerated !== newColumn.isGenerated && newColumn.generationStrategy !== "uuid") {
if (newColumn.isGenerated === true) {
upQueries.push(new Query(`CREATE SEQUENCE ${this.buildSequenceName(table, newColumn)} OWNED BY ${this.escapePath(table)}."${newColumn.name}"`));
downQueries.push(new Query(`DROP SEQUENCE ${this.buildSequenceName(table, newColumn)}`));
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT nextval('${this.buildSequenceName(table, newColumn, undefined, true)}')`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
} else {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT nextval('${this.buildSequenceName(table, newColumn, undefined, true)}')`));
upQueries.push(new Query(`DROP SEQUENCE ${this.buildSequenceName(table, newColumn)}`));
downQueries.push(new Query(`CREATE SEQUENCE ${this.buildSequenceName(table, newColumn)} OWNED BY ${this.escapePath(table)}."${newColumn.name}"`));
}
}
if (newColumn.default !== oldColumn.default) {
if (newColumn.default !== null && newColumn.default !== undefined) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT ${newColumn.default}`));
if (oldColumn.default !== null && oldColumn.default !== undefined) {
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT ${oldColumn.default}`));
} else {
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
}
} else if (oldColumn.default !== null && oldColumn.default !== undefined) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" DROP DEFAULT`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" SET DEFAULT ${oldColumn.default}`));
}
}
if ((newColumn.spatialFeatureType || "").toLowerCase() !== (oldColumn.spatialFeatureType || "").toLowerCase() || newColumn.srid !== oldColumn.srid) {
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(newColumn)}`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(oldColumn)}`));
}
}
await this.executeQueries(upQueries, downQueries);
this.replaceCachedTable(table, clonedTable);
}
/**
* Changes a column in the table.
*/
async changeColumns(tableOrName: Table|string, changedColumns: { newColumn: TableColumn, oldColumn: TableColumn }[]): Promise<void> {
await PromiseUtils.runInSequence(changedColumns, changedColumn => this.changeColumn(tableOrName, changedColumn.oldColumn, changedColumn.newColumn));
}
/**
* Drops column in the table.
*/
async dropColumn(tableOrName: Table|string, columnOrName: TableColumn|string): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
const column = columnOrName instanceof TableColumn ? columnOrName : table.findColumnByName(columnOrName);
if (!column)
throw new Error(`Column "${columnOrName}" was not found in table "${table.name}"`);
const clonedTable = table.clone();
const upQueries: Query[] = [];
const downQueries: Query[] = [];
// drop primary key constraint
if (column.isPrimary) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, clonedTable.primaryColumns.map(column => column.name));
const columnNames = clonedTable.primaryColumns.map(primaryColumn => `"${primaryColumn.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(clonedTable)} DROP CONSTRAINT "${pkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(clonedTable)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
// update column in table
const tableColumn = clonedTable.findColumnByName(column.name);
tableColumn!.isPrimary = false;
// if primary key have multiple columns, we must recreate it without dropped column
if (clonedTable.primaryColumns.length > 0) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, clonedTable.primaryColumns.map(column => column.name));
const columnNames = clonedTable.primaryColumns.map(primaryColumn => `"${primaryColumn.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(clonedTable)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(clonedTable)} DROP CONSTRAINT "${pkName}"`));
}
}
// drop column index
const columnIndex = clonedTable.indices.find(index => index.columnNames.length === 1 && index.columnNames[0] === column.name);
if (columnIndex) {
clonedTable.indices.splice(clonedTable.indices.indexOf(columnIndex), 1);
upQueries.push(this.dropIndexSql(table, columnIndex));
downQueries.push(this.createIndexSql(table, columnIndex));
}
// drop column check
const columnCheck = clonedTable.checks.find(check => !!check.columnNames && check.columnNames.length === 1 && check.columnNames[0] === column.name);
if (columnCheck) {
clonedTable.checks.splice(clonedTable.checks.indexOf(columnCheck), 1);
upQueries.push(this.dropCheckConstraintSql(table, columnCheck));
downQueries.push(this.createCheckConstraintSql(table, columnCheck));
}
// drop column unique
const columnUnique = clonedTable.uniques.find(unique => unique.columnNames.length === 1 && unique.columnNames[0] === column.name);
if (columnUnique) {
clonedTable.uniques.splice(clonedTable.uniques.indexOf(columnUnique), 1);
upQueries.push(this.dropUniqueConstraintSql(table, columnUnique));
downQueries.push(this.createUniqueConstraintSql(table, columnUnique));
}
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN "${column.name}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(table, column)}`));
// drop enum type
if (column.type === "enum" || column.type === "simple-enum") {
const hasEnum = await this.hasEnumType(table, column);
if (hasEnum) {
const enumType = await this.getEnumTypeName(table, column);
const escapedEnumName = `"${enumType.enumTypeSchema}"."${enumType.enumTypeName}"`;
upQueries.push(this.dropEnumTypeSql(table, column, escapedEnumName));
downQueries.push(this.createEnumTypeSql(table, column, escapedEnumName));
}
}
await this.executeQueries(upQueries, downQueries);
clonedTable.removeColumn(column);
this.replaceCachedTable(table, clonedTable);
}
/**
* Drops the columns in the table.
*/
async dropColumns(tableOrName: Table|string, columns: TableColumn[]): Promise<void> {
await PromiseUtils.runInSequence(columns, column => this.dropColumn(tableOrName, column));
}
/**
* Creates a new primary key.
*/
async createPrimaryKey(tableOrName: Table|string, columnNames: string[]): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
const clonedTable = table.clone();
const up = this.createPrimaryKeySql(table, columnNames);
// mark columns as primary, because dropPrimaryKeySql build constraint name from table primary column names.
clonedTable.columns.forEach(column => {
if (columnNames.find(columnName => columnName === column.name))
column.isPrimary = true;
});
const down = this.dropPrimaryKeySql(clonedTable);
await this.executeQueries(up, down);
this.replaceCachedTable(table, clonedTable);
}
/**
* Updates composite primary keys.
*/
async updatePrimaryKeys(tableOrName: Table|string, columns: TableColumn[]): Promise<void> {
const table = tableOrName instanceof Table ? tableOrName : await this.getCachedTable(tableOrName);
const clonedTable = table.clone();
const columnNames = columns.map(column => column.name);
const upQueries: Query[] = [];
const downQueries: Query[] = [];
// if table already have primary columns, we must drop them.
const primaryColumns = clonedTable.primaryColumns;
if (primaryColumns.length > 0) {
const pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(column => column.name));
const columnNamesString = primaryColumns.map(column => `"${column.name}"`).join(", ");
upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNamesString})`));