20260526181000_FixStepActionActionConfigRelation.cs
3.87 KB
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
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Rcs.Infrastructure.DB.MsSql;
#nullable disable
namespace Rcs.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260526181000_FixStepActionActionConfigRelation")]
public class FixStepActionActionConfigRelation : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
DO $$
DECLARE
uq_name text;
idx_name text;
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = current_schema()
AND table_name = 'step_actions'
) THEN
FOR uq_name IN
SELECT con.conname
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
JOIN pg_attribute att ON att.attrelid = rel.oid AND att.attnum = ANY(con.conkey)
WHERE con.contype = 'u'
AND nsp.nspname = current_schema()
AND rel.relname = 'step_actions'
AND att.attname = 'action_config_id'
LOOP
EXECUTE format('ALTER TABLE step_actions DROP CONSTRAINT IF EXISTS %I', uq_name);
END LOOP;
FOR idx_name IN
SELECT i.indexname
FROM pg_indexes i
WHERE i.schemaname = current_schema()
AND i.tablename = 'step_actions'
AND i.indexdef ILIKE 'CREATE UNIQUE INDEX%'
AND i.indexdef ILIKE '%(action_config_id)%'
LOOP
EXECUTE format('DROP INDEX IF EXISTS %I', idx_name);
END LOOP;
IF NOT EXISTS (
SELECT 1
FROM pg_indexes i
WHERE i.schemaname = current_schema()
AND i.tablename = 'step_actions'
AND i.indexname = 'idx_action_action_config'
) THEN
CREATE INDEX idx_action_action_config ON step_actions (action_config_id);
END IF;
END IF;
END
$$;
""");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = current_schema()
AND table_name = 'step_actions'
) THEN
DROP INDEX IF EXISTS idx_action_action_config;
IF NOT EXISTS (
SELECT 1
FROM step_actions
WHERE action_config_id IS NOT NULL
GROUP BY action_config_id
HAVING COUNT(*) > 1
) THEN
CREATE UNIQUE INDEX idx_action_action_config ON step_actions (action_config_id);
END IF;
END IF;
END
$$;
""");
}
}
}