|
1
|
export function generatePostgresAlterColummnIfExistStatement( |
|
2
|
tableName: string, |
|
3
|
columns: string[], |
|
4
|
alterExpression: string |
|
5
|
) { |
|
6
|
let script = ` |
|
7
|
DO $$ |
|
8
|
DECLARE |
|
9
|
current_column text; |
|
10
|
BEGIN` |
|
11
|
|
|
12
|
columns.forEach((column) => { |
|
13
|
script += ` |
|
14
|
current_column := '${column}'; |
|
15
|
IF EXISTS ( |
|
16
|
SELECT 1 |
|
17
|
FROM information_schema.columns |
|
18
|
WHERE table_name = '${tableName}' |
|
19
|
AND column_name = current_column |
|
20
|
) THEN |
|
21
|
EXECUTE format('ALTER TABLE %I ALTER COLUMN %I ${alterExpression}', '${tableName}', current_column); |
|
22
|
ELSE |
|
23
|
RAISE NOTICE 'Column % does not exist or alteration condition not met.', current_column; |
|
24
|
END IF;` |
|
25
|
}) |
|
26
|
|
|
27
|
script += ` |
|
28
|
END$$; |
|
29
|
` |
|
30
|
|
|
31
|
return script |
|
32
|
} |