JhHardwareWRS_BackPoint/scripts/migrate_person_roles.py
2026-06-24 15:19:14 +08:00

46 lines
1.5 KiB
Python

from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from sqlalchemy import text # noqa: E402
from app.database import SessionLocal # noqa: E402
def main() -> None:
with SessionLocal() as db:
db.execute(
text(
"""
CREATE TABLE IF NOT EXISTS person_roles (
phone VARCHAR(20) COLLATE utf8mb4_unicode_ci NOT NULL,
role ENUM('worker','admin','manager') COLLATE utf8mb4_unicode_ci NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (phone, role),
CONSTRAINT fk_person_roles_person
FOREIGN KEY (phone) REFERENCES personnel(phone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""
)
)
columns = db.execute(text("SHOW COLUMNS FROM personnel LIKE 'role'")).all()
if columns:
db.execute(
text(
"""
INSERT IGNORE INTO person_roles (phone, role, created_at)
SELECT phone, role, COALESCE(created_at, CURRENT_TIMESTAMP)
FROM personnel
"""
)
)
db.execute(text("ALTER TABLE personnel DROP COLUMN role"))
db.commit()
print("personnel migrated to one phone/name with multiple roles")
if __name__ == "__main__":
main()