cosmo/backend/scripts/run_sql.py

41 lines
1.3 KiB
Python

import asyncio
import sys
from sqlalchemy import text
from app.database import get_db, init_db
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def run_sql_file(sql_file_path):
await init_db()
try:
with open(sql_file_path, 'r') as f:
sql_content = f.read()
# Split by semicolon to handle multiple statements if needed
# But sqlalchemy text() might handle it. Let's try executing as one block if possible,
# or split manually if it's simple.
statements = [s.strip() for s in sql_content.split(';') if s.strip()]
async for session in get_db():
for stmt in statements:
logger.info(f"Executing: {stmt[:50]}...")
await session.execute(text(stmt))
await session.commit()
logger.info("SQL execution completed successfully.")
except FileNotFoundError:
logger.error(f"File not found: {sql_file_path}")
except Exception as e:
logger.error(f"Error executing SQL: {e}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python -m scripts.run_sql <path_to_sql_file>")
sys.exit(1)
sql_file = sys.argv[1]
asyncio.run(run_sql_file(sql_file))