Skip to content

Commit

Permalink
Ticckt 45, running almebic on startup
Browse files Browse the repository at this point in the history
  • Loading branch information
Nargis Sultani committed Nov 22, 2023
1 parent feb4c50 commit 2caa9f9
Show file tree
Hide file tree
Showing 12 changed files with 118 additions and 114 deletions.
2 changes: 1 addition & 1 deletion alembic.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[alembic]
# path to migration scripts
script_location = ./db_revisions
script_location = ./src/db_revisions

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
Expand Down
102 changes: 0 additions & 102 deletions db_revisions/env.py

This file was deleted.

11 changes: 0 additions & 11 deletions db_revisions/utils.py

This file was deleted.

File renamed without changes.
20 changes: 20 additions & 0 deletions src/db_revisions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import os
import logging
from alembic import command as alembic
from alembic.config import Config
from .utils import INST_DB_URL, basedir

log = logging.getLogger()


def get_alembic_config(db_url: str = INST_DB_URL) -> Config:
alembic_dir = os.path.join(basedir, "db_revisions")
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", alembic_dir)
alembic_cfg.set_main_option("sqlalchemy.url", str(db_url))
return alembic_cfg


def upgrade_database(revision: str = "head", db_url: str = INST_DB_URL) -> None:
alembic_cfg = get_alembic_config(db_url)
alembic.upgrade(alembic_cfg, revision)
49 changes: 49 additions & 0 deletions src/db_revisions/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from alembic import context
from entities.models import Base
from db_revisions.utils import INST_DB_URL, INST_DB_SCHEMA

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", INST_DB_URL)
# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata
target_metadata.schema = INST_DB_SCHEMA

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)


def run_migrations_offline():
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}
)
with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
configuration = config.get_section(config.config_ini_section)
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata, version_table_schema=target_metadata.schema
)
with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
File renamed without changes.
41 changes: 41 additions & 0 deletions src/db_revisions/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import os
import sys
from dotenv import load_dotenv
from alembic import op
from sqlalchemy import engine_from_config
from sqlalchemy.engine import reflection

if getattr(sys, "frozen", False):
# we are running in a bundle
basedir = sys._MEIPast
else:
# we are running in a normal Python environment
basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(basedir)

# this specific to SBL configuration
env_file = os.path.join(basedir, ".env.local")

ENV = os.getenv("ENV", "LOCAL")

if ENV == "LOCAL":
load_dotenv(env_file)
else:
load_dotenv()

INST_DB_USER = os.environ.get("INST_DB_USER")
INST_DB_PWD = os.environ.get("INST_DB_PWD")
INST_DB_HOST = os.environ.get("INST_DB_HOST")
INST_DB_NAME = os.environ.get("INST_DB_NAME")
INST_DB_SCHEMA = os.environ.get("INST_DB_SCHEMA")
INST_DB_PATH = f"{INST_DB_USER}:{INST_DB_PWD}@{INST_DB_HOST}/{INST_DB_NAME}"
INST_DB_URL = f"postgresql://{INST_DB_USER}:{INST_DB_PWD}@{INST_DB_HOST}/{INST_DB_NAME}"
# end specific SBL configuration


def table_exists(table_name):
config = op.get_context().config
engine = engine_from_config(config.get_section(config.config_ini_section), prefix="sqlalchemy.")
inspector = reflection.Inspector.from_engine(engine)
tables = inspector.get_table_names()
return table_name in tables
7 changes: 7 additions & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,18 @@

from config import settings

from db_revisions import upgrade_database

log = logging.getLogger()

app = FastAPI()


@app.on_event("startup")
async def startup() -> None:
upgrade_database()


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exception: HTTPException) -> JSONResponse:
log.error(exception, exc_info=True, stack_info=True)
Expand Down

0 comments on commit 2caa9f9

Please sign in to comment.