"""Contact folders — hierarchical folders for organizing contacts. Revision ID: 0022 Revises: 0021_unified_contacts Create Date: 2026-07-20 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects.postgresql import UUID revision = "0022_contact_folders" down_revision = "0021_unified_contacts" def upgrade(): # 1. Create contact_folders table op.create_table( "contact_folders", sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")), sa.Column("tenant_id", UUID(as_uuid=True), nullable=False, index=True), sa.Column("name", sa.String(255), nullable=False), sa.Column("parent_id", UUID(as_uuid=True), sa.ForeignKey("contact_folders.id", ondelete="CASCADE"), nullable=True), sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False), sa.Column("sort_order", sa.Integer, nullable=False, server_default="0"), sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")), sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")), sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), ) op.execute('CREATE INDEX IF NOT EXISTS ix_contact_folders_tenant_parent ON contact_folders (tenant_id, parent_id)') op.execute('CREATE INDEX IF NOT EXISTS ix_contact_folders_user ON contact_folders (user_id)') # 2. Add folder_id column to contacts op.execute("ALTER TABLE contacts ADD COLUMN IF NOT EXISTS folder_id UUID REFERENCES contact_folders(id) ON DELETE SET NULL") op.execute('CREATE INDEX IF NOT EXISTS ix_contacts_folder_id ON contacts (folder_id)') def downgrade(): op.drop_index("ix_contacts_folder_id", table_name="contacts") op.drop_column("contacts", "folder_id") op.drop_index("ix_contact_folders_user", table_name="contact_folders") op.drop_index("ix_contact_folders_tenant_parent", table_name="contact_folders") op.drop_table("contact_folders")