54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
|
|
#!/usr/bin/env python
|
||
|
|
# -*- coding: utf-8 -*-
|
||
|
|
"""
|
||
|
|
数据库初始化脚本
|
||
|
|
用于手动创建或重置数据库表
|
||
|
|
"""
|
||
|
|
|
||
|
|
from app import app
|
||
|
|
from extensions import db
|
||
|
|
import models
|
||
|
|
|
||
|
|
def init_database():
|
||
|
|
"""初始化数据库表"""
|
||
|
|
with app.app_context():
|
||
|
|
print("🔧 开始初始化数据库...")
|
||
|
|
|
||
|
|
# 创建所有表
|
||
|
|
db.create_all()
|
||
|
|
|
||
|
|
# 检查表是否创建成功
|
||
|
|
from sqlalchemy import inspect
|
||
|
|
inspector = inspect(db.engine)
|
||
|
|
tables = inspector.get_table_names()
|
||
|
|
|
||
|
|
print(f"\n✅ 数据库表已创建,共 {len(tables)} 张表:")
|
||
|
|
for table in tables:
|
||
|
|
print(f" - {table}")
|
||
|
|
|
||
|
|
print("\n📊 表结构详情:")
|
||
|
|
for table_name in tables:
|
||
|
|
columns = inspector.get_columns(table_name)
|
||
|
|
print(f"\n{table_name}:")
|
||
|
|
for col in columns:
|
||
|
|
print(f" {col['name']} ({col['type']})")
|
||
|
|
|
||
|
|
def drop_all_tables():
|
||
|
|
"""删除所有表(慎用)"""
|
||
|
|
with app.app_context():
|
||
|
|
print("⚠️ 警告:即将删除所有数据库表!")
|
||
|
|
confirm = input("确认删除?输入 yes 继续: ")
|
||
|
|
if confirm.lower() == 'yes':
|
||
|
|
db.drop_all()
|
||
|
|
print("✅ 所有表已删除")
|
||
|
|
else:
|
||
|
|
print("❌ 操作已取消")
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
import sys
|
||
|
|
|
||
|
|
if len(sys.argv) > 1 and sys.argv[1] == '--drop':
|
||
|
|
drop_all_tables()
|
||
|
|
else:
|
||
|
|
init_database()
|