8b55b9cf55
Co-authored-by: Cursor <cursoragent@cursor.com>
36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
"""给已经上线的库补上认证字段。create_all 不会修改旧表。"""
|
|
|
|
from sqlalchemy import inspect, text
|
|
|
|
from app.database import engine
|
|
|
|
|
|
def upgrade_schema() -> None:
|
|
inspector = inspect(engine)
|
|
if "users" not in inspector.get_table_names():
|
|
return
|
|
columns = {column["name"] for column in inspector.get_columns("users")}
|
|
statements: list[str] = []
|
|
if "username" not in columns:
|
|
statements.append("ALTER TABLE users ADD COLUMN username VARCHAR(32)")
|
|
if "password_hash" not in columns:
|
|
statements.append("ALTER TABLE users ADD COLUMN password_hash VARCHAR(255)")
|
|
if "role" not in columns:
|
|
statements.append("ALTER TABLE users ADD COLUMN role VARCHAR(16) DEFAULT 'user' NOT NULL")
|
|
if not statements and _has_username_index(inspector):
|
|
return
|
|
with engine.begin() as conn:
|
|
for statement in statements:
|
|
conn.execute(text(statement))
|
|
if not _has_username_index(inspector):
|
|
conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username ON users (username)"))
|
|
|
|
|
|
def _has_username_index(inspector) -> bool:
|
|
if "users" not in inspector.get_table_names():
|
|
return False
|
|
for index in inspector.get_indexes("users"):
|
|
if index.get("column_names") == ["username"] and index.get("unique"):
|
|
return True
|
|
return False
|