mirror of
https://github.com/langbot-app/LangBot.git
synced 2025-11-25 19:37:36 +08:00
65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import datetime
|
|
import typing
|
|
|
|
import sqlalchemy.ext.asyncio as sqlalchemy_asyncio
|
|
import sqlalchemy
|
|
|
|
from . import database
|
|
from ..entity.persistence import base, user, model, pipeline, bot, plugin
|
|
from ..core import app
|
|
from .databases import sqlite
|
|
|
|
|
|
class PersistenceManager:
|
|
"""持久化模块管理器"""
|
|
|
|
ap: app.Application
|
|
|
|
db: database.BaseDatabaseManager
|
|
"""数据库管理器"""
|
|
|
|
meta: sqlalchemy.MetaData
|
|
|
|
def __init__(self, ap: app.Application):
|
|
self.ap = ap
|
|
self.meta = base.Base.metadata
|
|
|
|
async def initialize(self):
|
|
|
|
for manager in database.preregistered_managers:
|
|
self.db = manager(self.ap)
|
|
await self.db.initialize()
|
|
|
|
await self.create_tables()
|
|
|
|
async def create_tables(self):
|
|
# TODO: 对扩展友好
|
|
|
|
# 日志
|
|
async with self.get_db_engine().connect() as conn:
|
|
await conn.run_sync(self.meta.create_all)
|
|
|
|
await conn.commit()
|
|
|
|
async def execute_async(
|
|
self,
|
|
*args,
|
|
**kwargs
|
|
) -> sqlalchemy.engine.cursor.CursorResult:
|
|
async with self.get_db_engine().connect() as conn:
|
|
result = await conn.execute(*args, **kwargs)
|
|
await conn.commit()
|
|
return result
|
|
|
|
def get_db_engine(self) -> sqlalchemy_asyncio.AsyncEngine:
|
|
return self.db.get_engine()
|
|
|
|
def serialize_model(self, model: typing.Type[sqlalchemy.Base], data: sqlalchemy.Base) -> dict:
|
|
return {
|
|
column.name: getattr(data, column.name) if not isinstance(getattr(data, column.name), (datetime.datetime)) else getattr(data, column.name).isoformat()
|
|
for column in model.__table__.columns
|
|
}
|