91 lines
2.6 KiB
Python
91 lines
2.6 KiB
Python
from sqlalchemy import create_engine, Column, Integer, String, Float, ForeignKey, DateTime, Boolean, JSON, inspect
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker, relationship
|
|
from datetime import datetime
|
|
import os
|
|
import sqlite3
|
|
import json
|
|
|
|
# 创建数据库引擎
|
|
SQLALCHEMY_DATABASE_URL = "sqlite:///./cpy_admin.db"
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
# 创建会话工厂
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 创建基类
|
|
Base = declarative_base()
|
|
|
|
# 获取数据库会话
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
def backup_data():
|
|
"""备份数据库中的数据"""
|
|
if not os.path.exists("cpy_admin.db"):
|
|
return {}
|
|
|
|
conn = sqlite3.connect("cpy_admin.db")
|
|
cursor = conn.cursor()
|
|
|
|
# 获取所有表的数据
|
|
tables_data = {}
|
|
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
|
tables = cursor.fetchall()
|
|
|
|
for table in tables:
|
|
table_name = table[0]
|
|
cursor.execute(f"SELECT * FROM {table_name}")
|
|
columns = [description[0] for description in cursor.description]
|
|
rows = cursor.fetchall()
|
|
tables_data[table_name] = [dict(zip(columns, row)) for row in rows]
|
|
|
|
conn.close()
|
|
return tables_data
|
|
|
|
def restore_data(tables_data):
|
|
"""恢复数据到数据库"""
|
|
conn = sqlite3.connect("cpy_admin.db")
|
|
cursor = conn.cursor()
|
|
|
|
for table_name, rows in tables_data.items():
|
|
if not rows:
|
|
continue
|
|
|
|
columns = rows[0].keys()
|
|
placeholders = ','.join(['?' for _ in columns])
|
|
insert_sql = f"INSERT INTO {table_name} ({','.join(columns)}) VALUES ({placeholders})"
|
|
|
|
for row in rows:
|
|
values = [row[col] for col in columns]
|
|
cursor.execute(insert_sql, values)
|
|
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
# 创建数据库表
|
|
def create_tables():
|
|
# 检查数据库文件是否存在
|
|
db_exists = os.path.exists("cpy_admin.db")
|
|
|
|
# 如果数据库存在,备份数据
|
|
if db_exists:
|
|
tables_data = backup_data()
|
|
# 删除数据库文件
|
|
os.remove("cpy_admin.db")
|
|
|
|
# 创建所有表
|
|
Base.metadata.create_all(bind=engine)
|
|
print("数据库表已创建")
|
|
|
|
# 如果之前有数据,恢复数据
|
|
if db_exists:
|
|
restore_data(tables_data)
|
|
print("数据已恢复")
|