44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from pillar_tool.util import config
|
|
|
|
from os import lockf, F_LOCK
|
|
from os.path import dirname, realpath
|
|
|
|
from alembic.config import Config
|
|
from alembic.command import upgrade, check, util
|
|
from pillar_tool.util import config
|
|
|
|
def run_db_migrations():
|
|
cfg = config()
|
|
user = cfg.db.user
|
|
password = cfg.db.password
|
|
host = cfg.db.host
|
|
port = cfg.db.port
|
|
database = cfg.db.database
|
|
alembic_cfg = Config()
|
|
alembic_cfg.set_main_option('script_location', f'{dirname(realpath(__file__))}/migrations')
|
|
alembic_cfg.set_main_option('sqlalchemy.url', f'postgresql://{user}:{password}@{host}:{port}/{database}')
|
|
alembic_cfg.set_main_option('prepend_sys_path', '.')
|
|
|
|
with open(realpath(__file__), 'a') as f:
|
|
lockf(f.fileno(), F_LOCK, 0)
|
|
upgrade(config=alembic_cfg, revision='head')
|
|
|
|
|
|
|
|
cfg = config()
|
|
SessionLocal = sessionmaker(
|
|
autocommit=False,
|
|
autoflush=False,
|
|
bind=create_engine(
|
|
url=f"postgresql+psycopg2://{cfg.db.user}:{cfg.db.password}@{cfg.db.host}:{cfg.db.port}/{cfg.db.database}"
|
|
)
|
|
)
|
|
|
|
def get_connection():
|
|
return SessionLocal()
|
|
|
|
|