Files
vps_web/migrate_db.py

48 lines
1.9 KiB
Python
Raw Normal View History

2026-02-09 14:18:42 +08:00
# -*- coding: utf-8 -*-
"""为已有数据库添加新列traffic、countries并将部分列改为可空。仅需运行一次。"""
import sys
from app import app, db
from sqlalchemy import text
def run():
with app.app_context():
engine = db.engine
dialect = engine.dialect.name
if dialect == "mysql":
with engine.connect() as conn:
for col, spec in [
("traffic", "VARCHAR(64) NULL"),
("countries", "VARCHAR(255) NULL"),
]:
try:
conn.execute(text("ALTER TABLE vps_plans ADD COLUMN {} {}".format(col, spec)))
conn.commit()
print("Added column:", col)
except Exception as e:
if "Duplicate column" in str(e) or "already exists" in str(e).lower():
print("Column", col, "already exists, skip.")
else:
print("Add", col, ":", e)
for col, spec in [
("region", "VARCHAR(128) NULL"),
("vcpu", "INT NULL"),
("memory_gb", "INT NULL"),
("storage_gb", "INT NULL"),
("bandwidth_mbps", "INT NULL"),
("price_cny", "DOUBLE NULL"),
("price_usd", "DOUBLE NULL"),
]:
try:
conn.execute(text("ALTER TABLE vps_plans MODIFY COLUMN {} {}".format(col, spec)))
conn.commit()
print("Modified column:", col)
except Exception as e:
print("Modify", col, ":", e)
else:
print("Only MySQL migration is implemented. For SQLite, recreate the DB or add columns manually.")
print("Done.")
if __name__ == "__main__":
run()
sys.exit(0)