119 lines
3.3 KiB
Python
119 lines
3.3 KiB
Python
"""
|
|
backend/init_db.py
|
|
文件用途:初始化 PostgreSQL 数据库 hxops_db 并创建所有表
|
|
引用文件:psycopg2, urllib.parse, app
|
|
逻辑关系:
|
|
1. 从配置中解析 SQLALCHEMY_DATABASE_URI
|
|
2. 连接 postgres 系统库,检查 hxops_db 是否存在,不存在则创建
|
|
3. 使用 Flask 应用上下文调用 db.create_all() 创建所有表结构
|
|
使用方式:
|
|
在项目根目录下执行:
|
|
cd backend
|
|
python init_db.py
|
|
"""
|
|
import os
|
|
import urllib.parse
|
|
|
|
import psycopg2
|
|
|
|
from app import create_app, db
|
|
|
|
def _parse_db_url(url: str):
|
|
"""
|
|
解析 SQLAlchemy 风格的数据库 URL
|
|
输入示例: postgresql://user:password@localhost:5432/hxops_db
|
|
输出:字典包含 user/password/host/port/dbname
|
|
"""
|
|
# 使用 urllib.parse 解析 URL
|
|
parsed = urllib.parse.urlparse(url)
|
|
# 从 netloc 中解析用户名和密码
|
|
if parsed.username:
|
|
user = urllib.parse.unquote(parsed.username)
|
|
else:
|
|
user = 'postgres'
|
|
if parsed.password:
|
|
password = urllib.parse.unquote(parsed.password)
|
|
else:
|
|
password = ''
|
|
host = parsed.hostname or 'localhost'
|
|
port = parsed.port or 5432
|
|
# 去掉路径前导斜杠得到数据库名
|
|
dbname = parsed.path.lstrip('/') or 'postgres'
|
|
return {
|
|
'user': user,
|
|
'password': password,
|
|
'host': host,
|
|
'port': port,
|
|
'dbname': dbname,
|
|
}
|
|
|
|
|
|
def ensure_database():
|
|
"""
|
|
确保数据库存在
|
|
核心逻辑:
|
|
1. 获取当前环境配置的 SQLALCHEMY_DATABASE_URI
|
|
2. 使用 psycopg2 连接到 postgres 系统数据库
|
|
3. 查询 pg_database,如果不存在则执行 CREATE DATABASE
|
|
"""
|
|
# 获取当前环境
|
|
env = os.getenv('FLASK_ENV', 'development')
|
|
app = create_app(env)
|
|
|
|
# 从应用配置中获取数据库 URL
|
|
url = app.config['SQLALCHEMY_DATABASE_URI']
|
|
print(f"Checking database for environment '{env}': {url}")
|
|
|
|
info = _parse_db_url(url)
|
|
target_db = info['dbname']
|
|
|
|
# 连接系统数据库 postgres
|
|
conn = psycopg2.connect(
|
|
dbname='postgres',
|
|
user=info['user'],
|
|
password=info['password'],
|
|
host=info['host'],
|
|
port=info['port'],
|
|
)
|
|
conn.autocommit = True
|
|
try:
|
|
cur = conn.cursor()
|
|
# 查询目标数据库是否已存在
|
|
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,))
|
|
exists = cur.fetchone() is not None
|
|
if not exists:
|
|
# 创建数据库
|
|
cur.execute(f'CREATE DATABASE "{target_db}"')
|
|
print(f'Created database {target_db}')
|
|
else:
|
|
print(f'Database {target_db} already exists')
|
|
cur.close()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def create_tables():
|
|
"""
|
|
在 hxops_db 中创建所有表结构
|
|
核心逻辑:
|
|
1. 创建 Flask 应用实例
|
|
2. 在应用上下文中调用 db.create_all()
|
|
"""
|
|
env = os.getenv('FLASK_ENV', 'development')
|
|
app = create_app(env)
|
|
with app.app_context():
|
|
db.create_all()
|
|
print(f'All tables created in {app.config["SQLALCHEMY_DATABASE_URI"]}')
|
|
|
|
if __name__ == '__main__':
|
|
ensure_database()
|
|
create_tables()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 第一步:确保数据库存在
|
|
ensure_database()
|
|
# 第二步:创建所有表
|
|
create_tables()
|
|
|