|
| 1 | +"""fix-borked-bigserial-cols-if-needed |
| 2 | +
|
| 3 | +Revision ID: 9c67b9d5e01e |
| 4 | +Revises: 3143eb18a369 |
| 5 | +Create Date: 2026-03-11 13:07:30.838743 |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +import sqlalchemy as sa |
| 10 | +from alembic import op |
| 11 | + |
| 12 | + |
| 13 | +# revision identifiers, used by Alembic. |
| 14 | +revision = "9c67b9d5e01e" |
| 15 | +down_revision = "3143eb18a369" |
| 16 | +branch_labels = None |
| 17 | +depends_on = None |
| 18 | + |
| 19 | + |
| 20 | +def upgrade(): |
| 21 | + conn = op.get_bind() |
| 22 | + |
| 23 | + # data_extractions pkey: int8 => bigserial (?) |
| 24 | + column_default = conn.execute( |
| 25 | + sa.text( |
| 26 | + "SELECT column_default FROM information_schema.columns " |
| 27 | + "WHERE table_name = 'data_extractions' AND column_name = 'id'" |
| 28 | + ) |
| 29 | + ).scalar() |
| 30 | + # column_default is null or missing "nextval" if it's plain int8 w/o a sequence default |
| 31 | + if column_default is None or "nextval" not in column_default: |
| 32 | + conn.execute( |
| 33 | + sa.text( |
| 34 | + "CREATE SEQUENCE IF NOT EXISTS data_extractions_id_seq " |
| 35 | + "AS bigint OWNED BY data_extractions.id" |
| 36 | + ) |
| 37 | + ) |
| 38 | + conn.execute( |
| 39 | + sa.text( |
| 40 | + "SELECT setval('data_extractions_id_seq', " |
| 41 | + "(SELECT COALESCE(MAX(id), 1) FROM data_extractions))" |
| 42 | + ) |
| 43 | + ) |
| 44 | + conn.execute( |
| 45 | + sa.text( |
| 46 | + "ALTER TABLE data_extractions " |
| 47 | + "ALTER COLUMN id SET DEFAULT nextval('data_extractions_id_seq')" |
| 48 | + ) |
| 49 | + ) |
| 50 | + |
| 51 | + # dedupes pkey: int8 => bigserial (?) |
| 52 | + column_default = conn.execute( |
| 53 | + sa.text( |
| 54 | + "SELECT column_default FROM information_schema.columns " |
| 55 | + "WHERE table_name = 'dedupes' AND column_name = 'id'" |
| 56 | + ) |
| 57 | + ).scalar() |
| 58 | + # column_default is null or missing "nextval" if it's plain int8 w/o a sequence default |
| 59 | + if column_default is None or "nextval" not in column_default: |
| 60 | + conn.execute( |
| 61 | + sa.text( |
| 62 | + "CREATE SEQUENCE IF NOT EXISTS dedupes_id_seq " |
| 63 | + "AS bigint OWNED BY dedupes.id" |
| 64 | + ) |
| 65 | + ) |
| 66 | + conn.execute( |
| 67 | + sa.text( |
| 68 | + "SELECT setval('dedupes_id_seq', " |
| 69 | + "(SELECT COALESCE(MAX(id), 1) FROM dedupes))" |
| 70 | + ) |
| 71 | + ) |
| 72 | + conn.execute( |
| 73 | + sa.text( |
| 74 | + "ALTER TABLE dedupes " |
| 75 | + "ALTER COLUMN id SET DEFAULT nextval('dedupes_id_seq')" |
| 76 | + ) |
| 77 | + ) |
| 78 | + |
| 79 | + |
| 80 | +def downgrade(): |
| 81 | + # restoring a plain int8 is probably not desirable; |
| 82 | + # leave downgrade as a no-op or implement as needed |
| 83 | + pass |
0 commit comments