This commit is contained in:
root 2025-07-13 11:20:28 +08:00
parent 238d988be1
commit c6bd87f852
1 changed files with 57 additions and 6 deletions

View File

@ -79,15 +79,13 @@ PostgreSQL 驱动 psycopg2 未安装。请安装:
try: try:
with self._get_connection() as conn: with self._get_connection() as conn:
with conn.cursor() as cursor: with conn.cursor() as cursor:
# 创建用户表(如果不存在) # 创建用户表(如果不存在)- 不包含新字段
create_table_sql = """ create_table_sql = """
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id VARCHAR(36) PRIMARY KEY, id VARCHAR(36) PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL, username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL, email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(64) NOT NULL, password_hash VARCHAR(64) NOT NULL,
display_name VARCHAR(100) NOT NULL,
avatar_url TEXT DEFAULT '',
is_active BOOLEAN DEFAULT TRUE, is_active BOOLEAN DEFAULT TRUE,
last_login TIMESTAMP, last_login TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
@ -96,6 +94,9 @@ PostgreSQL 驱动 psycopg2 未安装。请安装:
""" """
cursor.execute(create_table_sql) cursor.execute(create_table_sql)
# 检查并添加缺失的字段
self._migrate_user_table(cursor)
# 创建索引 # 创建索引
indexes = [ indexes = [
"CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);", "CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);",
@ -114,6 +115,56 @@ PostgreSQL 驱动 psycopg2 未安装。请安装:
logger.error(f"Failed to initialize user table: {e}") logger.error(f"Failed to initialize user table: {e}")
raise e raise e
def _migrate_user_table(self, cursor):
"""
迁移用户表结构添加缺失的字段
"""
try:
# 检查 display_name 字段是否存在
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'display_name'
""")
if not cursor.fetchone():
logger.info("Adding display_name column to users table")
cursor.execute("""
ALTER TABLE users
ADD COLUMN display_name VARCHAR(100) DEFAULT ''
""")
# 为现有用户设置 display_name 为 username
cursor.execute("""
UPDATE users
SET display_name = username
WHERE display_name = '' OR display_name IS NULL
""")
# 设置字段为 NOT NULL
cursor.execute("""
ALTER TABLE users
ALTER COLUMN display_name SET NOT NULL
""")
# 检查 avatar_url 字段是否存在
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'avatar_url'
""")
if not cursor.fetchone():
logger.info("Adding avatar_url column to users table")
cursor.execute("""
ALTER TABLE users
ADD COLUMN avatar_url TEXT DEFAULT ''
""")
except Exception as e:
logger.error(f"Failed to migrate user table: {e}")
raise e
def _hash_password(self, password: str) -> str: def _hash_password(self, password: str) -> str:
"""密码哈希""" """密码哈希"""
return hashlib.sha256(password.encode()).hexdigest() return hashlib.sha256(password.encode()).hexdigest()