Files
jyls_django/finance/migrations/0002_add_missing_approvers_order.py
2026-01-13 18:29:01 +08:00

91 lines
3.2 KiB
Python

# Generated manually to add missing approvers_order fields
# This migration adds approvers_order fields if they don't exist in the database
from django.db import migrations, models
def add_approvers_order_if_not_exists(apps, schema_editor):
"""使用 SQL 检查并添加字段(如果不存在)"""
db_alias = schema_editor.connection.alias
# 检查并添加 Income.approvers_order
with schema_editor.connection.cursor() as cursor:
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'finance_income'
AND COLUMN_NAME = 'approvers_order'
""")
if cursor.fetchone()[0] == 0:
cursor.execute("ALTER TABLE finance_income ADD COLUMN approvers_order TEXT NULL")
# 检查并添加 Payment.approvers_order
with schema_editor.connection.cursor() as cursor:
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'finance_payment'
AND COLUMN_NAME = 'approvers_order'
""")
if cursor.fetchone()[0] == 0:
cursor.execute("ALTER TABLE finance_payment ADD COLUMN approvers_order TEXT NULL")
# 检查并添加 Reimbursement.approvers_order
with schema_editor.connection.cursor() as cursor:
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'finance_reimbursement'
AND COLUMN_NAME = 'approvers_order'
""")
if cursor.fetchone()[0] == 0:
cursor.execute("ALTER TABLE finance_reimbursement ADD COLUMN approvers_order TEXT NULL")
# 检查并添加 BonusChange.approvers_order
with schema_editor.connection.cursor() as cursor:
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'finance_bonuschange'
AND COLUMN_NAME = 'approvers_order'
""")
if cursor.fetchone()[0] == 0:
cursor.execute("ALTER TABLE finance_bonuschange ADD COLUMN approvers_order TEXT NULL")
def reverse_add_approvers_order(apps, schema_editor):
"""回滚操作:删除字段"""
db_alias = schema_editor.connection.alias
with schema_editor.connection.cursor() as cursor:
try:
cursor.execute("ALTER TABLE finance_income DROP COLUMN approvers_order")
except:
pass
try:
cursor.execute("ALTER TABLE finance_payment DROP COLUMN approvers_order")
except:
pass
try:
cursor.execute("ALTER TABLE finance_reimbursement DROP COLUMN approvers_order")
except:
pass
try:
cursor.execute("ALTER TABLE finance_bonuschange DROP COLUMN approvers_order")
except:
pass
class Migration(migrations.Migration):
dependencies = [
('finance', '0001_initial'),
]
operations = [
migrations.RunPython(add_approvers_order_if_not_exists, reverse_add_approvers_order),
]