logs.unturf.com/initialize_db.py

66 lines
1.7 KiB
Python

#!/usr/bin/env python
"""
Initialize or upgrade the main database for PyraLogs.
Usage:
python initialize_db.py
Description:
Creates or updates all tables referenced by `Base.metadata`.
The database file will be created (if it does not exist) in the
DATA_DIR as specified in the app file. No custom paths are allowed.
"""
import os
import sys
import logging
import transaction
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
# Import Base and DATA_DIR from your app.py (Adjust if needed)
from app import Base, DATA_DIR # Make sure app.py defines Base and DATA_DIR
def usage():
script = os.path.basename(sys.argv[0])
print(f"Usage: {script}")
print("Example:")
print(f" python {script}")
sys.exit(1)
def main():
logging.basicConfig(level=logging.INFO)
# We do not allow any command-line arguments.
if len(sys.argv) > 1:
usage()
# Ensure DATA_DIR exists
if not os.path.exists(DATA_DIR):
os.makedirs(DATA_DIR)
logging.info(f"Created data directory at {DATA_DIR}")
# Always use the default path from app.py for the database
db_url = f"sqlite:///{os.path.join(DATA_DIR, 'main.db')}"
logging.info(f"Using DB URL: {db_url}")
# Set up the engine
engine = create_engine(
db_url,
connect_args={"check_same_thread": False},
poolclass=StaticPool
)
SessionFactory = sessionmaker(bind=engine)
# Create or upgrade tables
with transaction.manager:
logging.info("Creating or upgrading tables using Base.metadata.create_all()")
Base.metadata.create_all(engine)
logging.info("Database initialization complete.")
if __name__ == "__main__":
main()