Skip to content

Commit 8cce5ad

Browse files
0113 Migration Fix: Make github_branch migration idempotent: add column only if not exists (#4754)
1 parent d63900c commit 8cce5ad

1 file changed

Lines changed: 29 additions & 27 deletions

File tree

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,6 @@
11
# Generated by Django 2.2.20 on 2025-07-09 15:00
22

3-
from django.db import migrations, models
4-
5-
6-
def fix_duplicate_github_fields(apps, schema_editor):
7-
"""
8-
No data migration needed since we're using a partial unique constraint.
9-
"""
10-
pass
11-
12-
13-
def reverse_fix_duplicate_github_fields(apps, schema_editor):
14-
"""
15-
No reverse migration needed.
16-
"""
17-
pass
3+
from django.db import migrations
184

195

206
class Migration(migrations.Migration):
@@ -24,20 +10,36 @@ class Migration(migrations.Migration):
2410
]
2511

2612
operations = [
27-
migrations.AddField(
28-
model_name="challenge",
29-
name="github_branch",
30-
field=models.CharField(
31-
blank=True, default="", max_length=200, null=True
13+
migrations.RunSQL(
14+
sql=(
15+
"DO $$\n"
16+
"BEGIN\n"
17+
" IF NOT EXISTS (\n"
18+
" SELECT 1 FROM information_schema.columns\n"
19+
" WHERE table_name='challenge'\n"
20+
" AND column_name='github_branch'\n"
21+
" ) THEN\n"
22+
" ALTER TABLE challenge ADD COLUMN github_branch "
23+
"varchar(200) NULL DEFAULT '';\n"
24+
" END IF;\n"
25+
"END$$;"
26+
),
27+
reverse_sql=(
28+
"ALTER TABLE challenge DROP COLUMN IF EXISTS github_branch;"
3229
),
3330
),
34-
migrations.RunPython(
35-
fix_duplicate_github_fields,
36-
reverse_fix_duplicate_github_fields,
37-
),
38-
# Add a partial unique constraint that only applies when both fields are not empty
31+
# Add a partial unique constraint
32+
# Only applies when both fields are not empty
3933
migrations.RunSQL(
40-
"CREATE UNIQUE INDEX challenge_github_repo_branch_partial_idx ON challenge (github_repository, github_branch) WHERE github_repository != '' AND github_branch != '';",
41-
reverse_sql="DROP INDEX IF EXISTS challenge_github_repo_branch_partial_idx;",
34+
(
35+
"CREATE UNIQUE INDEX challenge_github_repo_branch_partial_idx "
36+
"ON challenge (github_repository, github_branch) "
37+
"WHERE github_repository != '' "
38+
"AND github_branch != '';"
39+
),
40+
reverse_sql=(
41+
"DROP INDEX IF EXISTS "
42+
"challenge_github_repo_branch_partial_idx;"
43+
),
4244
),
4345
]

0 commit comments

Comments
 (0)