024_add_project_creator_fk.py
1 from alembic import op 2 import sqlalchemy as sa 3 4 revision = '024' 5 down_revision = '023' 6 branch_labels = None 7 depends_on = None 8 9 def upgrade(): 10 try: 11 # Null out orphaned creator values that reference deleted users 12 conn = op.get_bind() 13 conn.execute(sa.text( 14 "UPDATE projects SET creator = NULL WHERE creator IS NOT NULL AND creator NOT IN (SELECT id FROM users)" 15 )) 16 # Add foreign key constraint 17 with op.batch_alter_table("projects") as batch_op: 18 batch_op.create_foreign_key("fk_projects_creator_users", "users", ["creator"], ["id"]) 19 except Exception as e: 20 print(f"Error adding creator FK: {e}") 21 22 def downgrade(): 23 try: 24 with op.batch_alter_table("projects") as batch_op: 25 batch_op.drop_constraint("fk_projects_creator_users", type_="foreignkey") 26 except Exception as e: 27 print(f"Error dropping creator FK: {e}")