This repository has been archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
history-migration.ts
85 lines (73 loc) · 2.43 KB
/
history-migration.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
import { EntityTarget, QueryRunner, Table, TableIndex } from "typeorm";
/**
* Helper function for drop unique indices for history entity.
* The default is to drop the all unique indices.
* If you want to regenerate the index with the unique flag removed, please set keepIndex to true.
*
* @param {QueryRunner} queryRunner
* @param {EntityTarget<any>} target
* @param {boolean} [keepIndex=false] If false, drop the index. If true, regenerate the index with the unique flag removed.
* @return {*} {Promise<void>}
*/
export async function dropUniqueIndices(
queryRunner: QueryRunner,
target: EntityTarget<any>,
keepIndex = false,
): Promise<void> {
const metadata = queryRunner.connection.getMetadata(target);
if (!metadata) {
throw Error(`metadata not found`);
}
const dropForeignKeyNames: string[] = [];
for (const foreignKey of metadata.foreignKeys) {
for (const column of foreignKey.columns) {
// @OneToOne creates a unique index.
if (column.relationMetadata?.isOneToOne) {
dropForeignKeyNames.push(foreignKey.name);
continue;
}
}
}
for (const dropForeignKeyName of dropForeignKeyNames) {
await queryRunner.dropForeignKey(metadata.tableName, dropForeignKeyName);
}
const table = await getTable(queryRunner, metadata.tablePath);
const uniqueIndices = table.indices.filter((i) => i.isUnique).map((x) => x.clone());
for (const uniqueIndex of uniqueIndices) {
await queryRunner.dropIndex(table, uniqueIndex);
if (keepIndex) {
await queryRunner.createIndex(
table,
new TableIndex({
columnNames: uniqueIndex.columnNames,
isUnique: false,
isSpatial: uniqueIndex.isSpatial,
isFulltext: uniqueIndex.isFulltext,
name: uniqueIndex.name,
parser: uniqueIndex.parser,
where: uniqueIndex.where,
}),
);
}
}
const uniques = table.uniques.map((x) => x.clone());
for (const unique of uniques) {
await queryRunner.dropUniqueConstraint(table, unique);
if (keepIndex) {
await queryRunner.createIndex(
table,
new TableIndex({
columnNames: unique.columnNames,
isUnique: false,
}),
);
}
}
}
async function getTable(queryRunner: QueryRunner, tablePath: string): Promise<Table> {
const table = await queryRunner.getTable(tablePath);
if (!table) {
throw Error(`'${tablePath}' table not found`);
}
return table;
}