|
1
|
export async function transactionWrapper<TManager = unknown>( |
|
2
|
manager: any, |
|
3
|
task: (transactionManager: any) => Promise<any>, |
|
4
|
{ |
|
5
|
transaction, |
|
6
|
isolationLevel, |
|
7
|
enableNestedTransactions = false, |
|
8
|
}: { |
|
9
|
isolationLevel?: string |
|
10
|
transaction?: TManager |
|
11
|
enableNestedTransactions?: boolean |
|
12
|
} = {} |
|
13
|
): Promise<any> { |
|
14
|
// Reuse the same transaction if it is already provided and nested transactions are disabled |
|
15
|
if (!enableNestedTransactions && transaction) { |
|
16
|
return await task(transaction) |
|
17
|
} |
|
18
|
|
|
19
|
const options = {} |
|
20
|
|
|
21
|
if (transaction) { |
|
22
|
Object.assign(options, { ctx: transaction }) |
|
23
|
} |
|
24
|
|
|
25
|
if (isolationLevel) { |
|
26
|
Object.assign(options, { isolationLevel }) |
|
27
|
} |
|
28
|
|
|
29
|
const transactionMethod = manager.transaction ?? manager.transactional |
|
30
|
return await transactionMethod.bind(manager)(task, options) |
|
31
|
} |
|
32
|
|
|
33
|
export function normalizeMigrationSQL(sql: string) { |
|
34
|
sql = sql.replace( |
|
35
|
/create table (?!if not exists)/g, |
|
36
|
"create table if not exists " |
|
37
|
) |
|
38
|
sql = sql.replace(/alter table (?!if exists)/g, "alter table if exists ") |
|
39
|
sql = sql.replace( |
|
40
|
/create index (?!if not exists)/g, |
|
41
|
"create index if not exists " |
|
42
|
) |
|
43
|
sql = sql.replace(/alter index (?!if exists)/g, "alter index if exists ") |
|
44
|
sql = sql.replace(/drop index (?!if exists)/g, "drop index if exists ") |
|
45
|
sql = sql.replace( |
|
46
|
/create unique index (?!if not exists)/g, |
|
47
|
"create unique index if not exists " |
|
48
|
) |
|
49
|
sql = sql.replace( |
|
50
|
/drop unique index (?!if exists)/g, |
|
51
|
"drop unique index if exists " |
|
52
|
) |
|
53
|
sql = sql.replace( |
|
54
|
/add column (?!if not exists)/g, |
|
55
|
"add column if not exists " |
|
56
|
) |
|
57
|
sql = sql.replace(/drop column (?!if exists)/g, "drop column if exists ") |
|
58
|
sql = sql.replace( |
|
59
|
/drop constraint (?!if exists)/g, |
|
60
|
"drop constraint if exists " |
|
61
|
) |
|
62
|
|
|
63
|
return sql |
|
64
|
} |