async refactor & docker deploy environment
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
49
db.py
49
db.py
@@ -1,13 +1,42 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from models import Base
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///bot.db')
|
||||
engine = create_engine(DATABASE_URL, echo=True)
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
import os
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import declarative_base
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
def init_db():
|
||||
Base.metadata.create_all(engine)
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///bot.db")
|
||||
|
||||
if DATABASE_URL.startswith("sqlite+aiosqlite:///"):
|
||||
db_path = DATABASE_URL.replace("sqlite+aiosqlite:///", "")
|
||||
abs_db_path = os.path.abspath(db_path)
|
||||
db_dir = os.path.dirname(abs_db_path)
|
||||
if db_dir and not os.path.exists(db_dir):
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
|
||||
engine = create_async_engine(DATABASE_URL, future=True, echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
||||
Base = declarative_base()
|
||||
|
||||
async def init_db():
|
||||
print(f'База данных: {DATABASE_URL}')
|
||||
need_create = False
|
||||
if DATABASE_URL.startswith("sqlite+aiosqlite:///"):
|
||||
db_path = DATABASE_URL.replace("sqlite+aiosqlite:///", "")
|
||||
abs_db_path = os.path.abspath(db_path)
|
||||
print(f"Абсолютный путь к базе данных: {abs_db_path}")
|
||||
if not os.path.exists(abs_db_path):
|
||||
print("Файл базы данных отсутствует, будет создан.")
|
||||
need_create = True
|
||||
else:
|
||||
print(f"База данных: {DATABASE_URL}")
|
||||
# Для других СУБД всегда пытаемся создать таблицы
|
||||
need_create = True
|
||||
|
||||
if need_create:
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
tables = Base.metadata.tables.keys()
|
||||
print(f"Созданы таблицы: {', '.join(tables)}")
|
||||
else:
|
||||
print("База данных уже существует, создание таблиц пропущено.")
|
||||
Reference in New Issue
Block a user