logs.unturf.com/initialize_db.py
Russell Ballestrini bed3607168 modified: app.py
modified:   initialize_db.py
2025-01-11 19:26:49 -05:00

65 lines
1.8 KiB
Python

#!/usr/bin/env python
"""
Initialize or upgrade the main database for this web application.
Usage:
python initialize_db.py
Environment Variables:
DB_URI (optional):
The SQLAlchemy database URL (e.g., "sqlite:///main.db").
Defaults to "sqlite:///main.db" if not set.
Description:
Creates or updates all tables referenced by `Base.metadata`.
If the database file/tables do not exist, they will be created.
"""
import os
import sys
import logging
import transaction
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
# Adjust these imports to your actual project structure:
# Ensure 'Base' is imported from your 'app.py' where your models are defined.
from app import Base # Assuming 'app.py' contains your models and 'Base'
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)
if len(sys.argv) > 1:
# We only expect optional arguments. If needed, parse them here.
usage()
# Read environment variable for DB URL
db_url = os.environ.get("DB_URI", "sqlite:///main.db")
logging.info(f"Using DB URL: {db_url}")
# Set up engine
engine = create_engine(
db_url,
connect_args={"check_same_thread": False} if "sqlite" in db_url else {},
poolclass=StaticPool if "sqlite" in db_url else None,
)
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()