|
| 1 | +"""Lowercase account names and add display_name |
| 2 | +
|
| 3 | +Revision ID: af024967630d |
| 4 | +Revises: c1f9a3e27d48 |
| 5 | +Create Date: 2026-04-15 12:00:00.000000 |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +import sqlalchemy as sa |
| 10 | +from alembic import op |
| 11 | + |
| 12 | +revision = "af024967630d" |
| 13 | +down_revision = "c1f9a3e27d48" |
| 14 | +branch_labels = None |
| 15 | +depends_on = None |
| 16 | + |
| 17 | + |
| 18 | +def upgrade(): |
| 19 | + op.add_column( |
| 20 | + "account", |
| 21 | + sa.Column("display_name", sa.String(length=64), nullable=True), |
| 22 | + ) |
| 23 | + conn = op.get_bind() |
| 24 | + collisions = conn.execute( |
| 25 | + sa.text( |
| 26 | + "SELECT lower(name) AS lname, array_agg(name) AS names " |
| 27 | + "FROM account GROUP BY lower(name) HAVING count(*) > 1" |
| 28 | + ) |
| 29 | + ).fetchall() |
| 30 | + if collisions: |
| 31 | + raise RuntimeError( |
| 32 | + "Cannot lowercase account.name: case-insensitive collisions " |
| 33 | + f"exist: {collisions}. Resolve these rows before re-running." |
| 34 | + ) |
| 35 | + # For org accounts, pull the nicely-cased display_name from the org row |
| 36 | + # (account.name was already lowercased on org creation). For user accounts, |
| 37 | + # the existing account.name preserves whatever casing the user signed up |
| 38 | + # with. |
| 39 | + conn.execute( |
| 40 | + sa.text( |
| 41 | + "UPDATE account SET display_name = COALESCE(" |
| 42 | + "(SELECT display_name FROM org WHERE org.id = account.org_id), " |
| 43 | + "name) " |
| 44 | + "WHERE display_name IS NULL" |
| 45 | + ) |
| 46 | + ) |
| 47 | + conn.execute(sa.text("UPDATE account SET name = lower(name)")) |
| 48 | + op.create_check_constraint( |
| 49 | + "ck_account_name_lowercase", "account", "name = lower(name)" |
| 50 | + ) |
| 51 | + op.drop_column("org", "display_name") |
| 52 | + |
| 53 | + |
| 54 | +def downgrade(): |
| 55 | + op.add_column( |
| 56 | + "org", |
| 57 | + sa.Column("display_name", sa.String(length=255), nullable=True), |
| 58 | + ) |
| 59 | + op.execute( |
| 60 | + "UPDATE org SET display_name = account.display_name " |
| 61 | + "FROM account WHERE account.org_id = org.id" |
| 62 | + ) |
| 63 | + op.alter_column("org", "display_name", nullable=False) |
| 64 | + op.drop_constraint("ck_account_name_lowercase", "account", type_="check") |
| 65 | + op.drop_column("account", "display_name") |
0 commit comments