|
3 | 3 |
|
4 | 4 | Adds the show_program_content column to control Program tab visibility. |
5 | 5 |
|
6 | | - This migration handles two scenarios: |
7 | | - 1. Fresh database: adds show_program_content column directly |
8 | | - 2. Existing database with show_twelve_step_content: renames the column |
| 6 | + This migration handles four scenarios: |
| 7 | + 1. Both columns exist: backfill new from old, then drop old column |
| 8 | + 2. Only old column exists: rename old to new column |
| 9 | + 3. Neither column exists: add new column with default |
| 10 | + 4. Only new column exists: no action needed (already migrated) |
9 | 11 | */ |
10 | 12 |
|
11 | 13 | DO $$ |
12 | 14 | BEGIN |
13 | | - -- Check if the old column exists (existing database) |
| 15 | + -- Case 1: Both columns exist (partial migration or manual addition) |
| 16 | + -- Backfill new column from old and drop old column |
14 | 17 | IF EXISTS ( |
15 | 18 | SELECT 1 FROM information_schema.columns |
16 | 19 | WHERE table_schema = 'public' |
17 | 20 | AND table_name = 'profiles' |
18 | 21 | AND column_name = 'show_twelve_step_content' |
| 22 | + ) AND EXISTS ( |
| 23 | + SELECT 1 FROM information_schema.columns |
| 24 | + WHERE table_schema = 'public' |
| 25 | + AND table_name = 'profiles' |
| 26 | + AND column_name = 'show_program_content' |
| 27 | + ) THEN |
| 28 | + -- Backfill any NULL values in new column from old column |
| 29 | + UPDATE public.profiles |
| 30 | + SET show_program_content = show_twelve_step_content |
| 31 | + WHERE show_program_content IS NULL AND show_twelve_step_content IS NOT NULL; |
| 32 | + -- Drop the old column |
| 33 | + ALTER TABLE public.profiles |
| 34 | + DROP COLUMN show_twelve_step_content; |
| 35 | + -- Case 2: Only old column exists (existing database) |
| 36 | + -- Rename old column to new |
| 37 | + ELSIF EXISTS ( |
| 38 | + SELECT 1 FROM information_schema.columns |
| 39 | + WHERE table_schema = 'public' |
| 40 | + AND table_name = 'profiles' |
| 41 | + AND column_name = 'show_twelve_step_content' |
19 | 42 | ) THEN |
20 | | - -- Rename existing column |
21 | 43 | ALTER TABLE public.profiles |
22 | 44 | RENAME COLUMN show_twelve_step_content TO show_program_content; |
23 | | - -- Check if neither column exists (fresh database) |
| 45 | + -- Case 3: Neither column exists (fresh database) |
| 46 | + -- Add new column |
24 | 47 | ELSIF NOT EXISTS ( |
25 | 48 | SELECT 1 FROM information_schema.columns |
26 | 49 | WHERE table_schema = 'public' |
27 | 50 | AND table_name = 'profiles' |
28 | 51 | AND column_name = 'show_program_content' |
29 | 52 | ) THEN |
30 | | - -- Add new column |
31 | 53 | ALTER TABLE public.profiles |
32 | 54 | ADD COLUMN show_program_content BOOLEAN DEFAULT true; |
33 | 55 | END IF; |
| 56 | + -- Case 4: Only new column exists - no action needed (migration already complete) |
34 | 57 | END $$; |
35 | 58 |
|
36 | 59 | COMMENT ON COLUMN public.profiles.show_program_content IS |
|
0 commit comments