Files
forms/scripts/init_db.py
2026-04-09 19:28:41 +03:00

64 lines
2.0 KiB
Python

#!/usr/bin/env python
"""
Скрипт для инициализации базы данных
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from sqlalchemy import create_engine, text
from app.config import settings
from app.models.base import Base
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def init_database():
"""Синхронная инициализация БД"""
try:
logger.info(f"Connecting to: {settings.DATABASE_URL}")
# Создаем синхронный движок
engine = create_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_pre_ping=True,
)
# Создаем таблицы
logger.info("Creating database tables...")
Base.metadata.create_all(bind=engine)
logger.info("✅ Database tables created successfully!")
# Проверяем подключение - используем text()
with engine.connect() as conn:
result = conn.execute(text("SELECT version()"))
version = result.scalar()
logger.info(f"✅ PostgreSQL version: {version[:50]}...")
# Показываем созданные таблицы
result = conn.execute(text("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name
"""))
tables = [row[0] for row in result]
if tables:
logger.info(f"✅ Created tables: {', '.join(tables)}")
else:
logger.warning("No tables found")
engine.dispose()
logger.info("Database initialization completed successfully!")
except Exception as e:
logger.error(f"❌ Failed to initialize database: {e}")
raise
if __name__ == "__main__":
init_database()