refactor: backup soft-deleted conversations instead of deleting them

- Create backup table conversations_4f02b6704509_bak for soft-deleted records
- Only create backup table if soft-deleted records exist
- Support recovery during downgrade migration
- Drop backup table after successful restoration
This commit is contained in:
-LAN- 2025-09-03 10:18:59 +08:00
parent b8885fa029
commit d3490ebb0f
No known key found for this signature in database
GPG Key ID: 6BA0D108DED011FF
1 changed files with 36 additions and 1 deletions

View File

@ -19,7 +19,21 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
# Delete any conversations where is_deleted is true before dropping the column
# Create backup table for soft-deleted conversations
backup_table_name = 'conversations_4f02b6704509_bak'
# Check if there are any soft-deleted conversations
result = op.get_bind().execute(sa.text("SELECT COUNT(*) FROM conversations WHERE is_deleted = true"))
count = result.scalar()
if count > 0:
# Create backup table with all columns from conversations
op.execute(sa.text(f"""
CREATE TABLE {backup_table_name} AS
SELECT * FROM conversations WHERE is_deleted = true
"""))
# Delete soft-deleted conversations from main table
op.execute("DELETE FROM conversations WHERE is_deleted = true")
with op.batch_alter_table('conversations', schema=None) as batch_op:
@ -32,5 +46,26 @@ def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('conversations', schema=None) as batch_op:
batch_op.add_column(sa.Column('is_deleted', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False))
# Restore soft-deleted conversations from backup table if it exists
backup_table_name = 'conversations_4f02b6704509_bak'
# Check if backup table exists
result = op.get_bind().execute(sa.text(f"""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = '{backup_table_name}'
)
"""))
if result.scalar():
# Restore the soft-deleted conversations
op.execute(sa.text(f"""
INSERT INTO conversations
SELECT * FROM {backup_table_name}
"""))
# Drop the backup table after restoration
op.execute(sa.text(f"DROP TABLE {backup_table_name}"))
# ### end Alembic commands ###