|
| 1 | +"""add actor_kind and actor_token_id to audit_log |
| 2 | +
|
| 3 | +Revision ID: i8j9k0l1m2n3 |
| 4 | +Revises: h7i8j9k0l1m2 |
| 5 | +Create Date: 2026-05-07 14:30:00.000000 |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Sequence, Union |
| 10 | + |
| 11 | +import sqlalchemy as sa |
| 12 | +from sqlalchemy.dialects import postgresql |
| 13 | + |
| 14 | +from alembic import op |
| 15 | + |
| 16 | +# revision identifiers, used by Alembic. |
| 17 | +revision: str = "i8j9k0l1m2n3" |
| 18 | +down_revision: Union[str, None] = "h7i8j9k0l1m2" |
| 19 | +branch_labels: Union[str, Sequence[str], None] = None |
| 20 | +depends_on: Union[str, Sequence[str], None] = None |
| 21 | + |
| 22 | + |
| 23 | +def upgrade() -> None: |
| 24 | + op.add_column("audit_log", sa.Column("actor_kind", sa.String(length=20), nullable=False, server_default="user")) |
| 25 | + op.add_column("audit_log", sa.Column("actor_token_id", postgresql.UUID(as_uuid=True), nullable=True)) |
| 26 | + op.alter_column("audit_log", "user_id", existing_type=postgresql.UUID(as_uuid=True), nullable=True) |
| 27 | + |
| 28 | + op.execute("UPDATE audit_log SET actor_kind = 'user' WHERE actor_kind IS NULL") |
| 29 | + |
| 30 | + op.create_foreign_key( |
| 31 | + "fk_audit_log_actor_token_id_runner_tokens", |
| 32 | + "audit_log", |
| 33 | + "runner_tokens", |
| 34 | + ["actor_token_id"], |
| 35 | + ["id"], |
| 36 | + ondelete="SET NULL", |
| 37 | + ) |
| 38 | + op.create_check_constraint( |
| 39 | + "ck_audit_log_actor_identity", |
| 40 | + "audit_log", |
| 41 | + "(actor_kind = 'user' AND user_id IS NOT NULL AND actor_token_id IS NULL) " |
| 42 | + "OR (actor_kind = 'runner_token' AND actor_token_id IS NOT NULL AND user_id IS NULL)", |
| 43 | + ) |
| 44 | + op.create_index("idx_audit_log_actor_token_id", "audit_log", ["actor_token_id"]) |
| 45 | + op.create_index("idx_audit_log_actor_kind_created_at", "audit_log", ["actor_kind", "created_at"]) |
| 46 | + |
| 47 | + |
| 48 | +def downgrade() -> None: |
| 49 | + op.drop_index("idx_audit_log_actor_kind_created_at", table_name="audit_log") |
| 50 | + op.drop_index("idx_audit_log_actor_token_id", table_name="audit_log") |
| 51 | + op.drop_constraint("ck_audit_log_actor_identity", "audit_log", type_="check") |
| 52 | + op.drop_constraint("fk_audit_log_actor_token_id_runner_tokens", "audit_log", type_="foreignkey") |
| 53 | + |
| 54 | + # Restore non-null user_id invariant for pre-actor rows. |
| 55 | + op.execute("DELETE FROM audit_log WHERE user_id IS NULL") |
| 56 | + op.alter_column("audit_log", "user_id", existing_type=postgresql.UUID(as_uuid=True), nullable=False) |
| 57 | + op.drop_column("audit_log", "actor_token_id") |
| 58 | + op.drop_column("audit_log", "actor_kind") |
0 commit comments