94 lines
2.8 KiB
Python
94 lines
2.8 KiB
Python
"""Add department and creator ownership to operator-managed resources."""
|
|
|
|
from alembic import op
|
|
import sqlalchemy as sa
|
|
|
|
|
|
revision = "0026_admin_ownership"
|
|
down_revision = "0025_admin_rbac"
|
|
branch_labels = None
|
|
depends_on = None
|
|
|
|
DEFAULT_DEPT_ID = "00000000-0000-0000-0000-000000000001"
|
|
OWNED_TABLES = (
|
|
"MediaAsset",
|
|
"HeroSlide",
|
|
"DestinationHero",
|
|
"VehicleOption",
|
|
"VehicleServiceConfig",
|
|
"HomeExperience",
|
|
"HomeTeamBuilding",
|
|
"HomeWildArchive",
|
|
"HomeWanfaRecommendation",
|
|
"WanfaCategory",
|
|
"WanfaRoute",
|
|
"DetailRecord",
|
|
"ConciergeAdvisor",
|
|
"DemandHero",
|
|
"DemandFeatureCard",
|
|
"DemandForm",
|
|
"Lead",
|
|
)
|
|
|
|
|
|
def upgrade() -> None:
|
|
for table_name in OWNED_TABLES:
|
|
op.add_column(
|
|
table_name,
|
|
sa.Column(
|
|
"deptId",
|
|
sa.String(),
|
|
nullable=True,
|
|
server_default=sa.text(f"'{DEFAULT_DEPT_ID}'"),
|
|
),
|
|
)
|
|
op.add_column(table_name, sa.Column("createdById", sa.String(), nullable=True))
|
|
op.create_index(f"ix_{table_name}_deptId", table_name, ["deptId"])
|
|
op.create_index(f"ix_{table_name}_createdById", table_name, ["createdById"])
|
|
op.create_foreign_key(
|
|
f"fk_{table_name}_deptId",
|
|
table_name,
|
|
"AdminDepartment",
|
|
["deptId"],
|
|
["id"],
|
|
ondelete="RESTRICT",
|
|
)
|
|
op.create_foreign_key(
|
|
f"fk_{table_name}_createdById",
|
|
table_name,
|
|
"AdminUser",
|
|
["createdById"],
|
|
["id"],
|
|
ondelete="SET NULL",
|
|
)
|
|
quoted_table = f'"{table_name}"'
|
|
op.execute(
|
|
sa.text(f'UPDATE {quoted_table} SET "deptId" = :dept_id WHERE "deptId" IS NULL').bindparams(
|
|
dept_id=DEFAULT_DEPT_ID
|
|
)
|
|
)
|
|
op.alter_column(
|
|
table_name,
|
|
"deptId",
|
|
existing_type=sa.String(),
|
|
nullable=False,
|
|
server_default=sa.text(f"'{DEFAULT_DEPT_ID}'"),
|
|
)
|
|
op.execute(
|
|
sa.text(
|
|
f'UPDATE {quoted_table} SET "createdById" = '
|
|
'(SELECT "id" FROM "AdminUser" ORDER BY "createdAt" ASC LIMIT 1) '
|
|
'WHERE "createdById" IS NULL'
|
|
)
|
|
)
|
|
|
|
|
|
def downgrade() -> None:
|
|
for table_name in reversed(OWNED_TABLES):
|
|
op.drop_constraint(f"fk_{table_name}_createdById", table_name, type_="foreignkey")
|
|
op.drop_constraint(f"fk_{table_name}_deptId", table_name, type_="foreignkey")
|
|
op.drop_index(f"ix_{table_name}_createdById", table_name=table_name)
|
|
op.drop_index(f"ix_{table_name}_deptId", table_name=table_name)
|
|
op.drop_column(table_name, "createdById")
|
|
op.drop_column(table_name, "deptId")
|