-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmigrate.py
66 lines (53 loc) · 1.84 KB
/
migrate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import io
from typing import Optional
from alembic.config import Config
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from alembic import command
from app.core.config import SQLALCHEMY_DATABASE_URL
from app.core.database.models import Base
from app.features.posts import categories
from app.utils import get_logger
engine = create_engine(
f"postgresql://{SQLALCHEMY_DATABASE_URL.split('://')[1]}",
pool_size=6,
max_overflow=0,
pool_timeout=15, # seconds
pool_recycle=1800,
echo=False,
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
log = get_logger(__name__)
def main():
run_migrations()
def init_db():
with engine.connect() as connection:
connection.execute(text("CREATE EXTENSION IF NOT EXISTS postgis"))
Base.metadata.create_all(bind=engine)
with SessionLocal() as session:
categories.add_categories_to_db(session)
def run_migrations():
log.info("Running db migrations")
alembic_cfg = Config("alembic.ini")
current_revision = get_current_revision()
if current_revision is None:
# If alembic_version table doesn't exist, init db and stamp it with the most recent revision
log.info("Creating tables and stamping version")
init_db()
command.stamp(alembic_cfg, "head")
else:
log.info("Migrating")
command.upgrade(alembic_cfg, "head")
log.info("Ran db migrations")
def get_current_revision() -> Optional[str]:
output_buffer = io.StringIO()
alembic_cfg = Config("alembic.ini", stdout=output_buffer)
command.current(alembic_cfg)
output = output_buffer.getvalue()
if output:
return output
else:
# If current revision doesn't exist, output is an empty string, so we return None here
return None
if __name__ == "__main__":
main()