Skip to content

Commit

Permalink
migration script + run
Browse files Browse the repository at this point in the history
  • Loading branch information
HMnesterov committed Aug 26, 2023
1 parent aaf394e commit efb0077
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import uvicorn

if __name__ == '__main__':
uvicorn.run(app="core.deps:app", host="127.0.0.1", port=8000)
22 changes: 22 additions & 0 deletions core/deps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from .migrate import migrate
from tortoise import Tortoise
from core.app import app
from .settings import settings


@app.on_event("startup")
async def on_startup():
await Tortoise.init(
db_url=settings.DB_CONNECTION,
modules={

"migrate": ["core.migrate"],
"models": []
}
)
await migrate()


@app.on_event("shutdown")
async def on_shutdown():
await Tortoise.close_connections()
38 changes: 38 additions & 0 deletions core/migrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
from typing import List
from core.logger import logger
from core.settings import settings
from tortoise import fields, models
from tortoise.transactions import in_transaction


class Migrate(models.Model):
id = fields.BigIntField(pk=True)
file = fields.CharField(max_length=1024)


async def migrate():
#create migration table
async with in_transaction("default") as conn:
await conn.execute_script(
"create table if not exists \"migrate\"(\"id\" BIGSERIAL PRIMARY KEY, \"file\" varchar(1024));"
)
#collect new migrations
scripts_files: List[str] = os.listdir(settings.DB_MIGRATE_PATH)
if not scripts_files:
return
script_db: Migrate = await Migrate.filter().order_by('-id').first()
if script_db is None:
unregistered_migration_scripts = scripts_files
else:
unregistered_migration_scripts = scripts_files[scripts_files.index(script_db.file) + 1:]
#make migrations
logger.info(msg=f"Found {len(unregistered_migration_scripts)} changes: {unregistered_migration_scripts}")
for migration_script in unregistered_migration_scripts:
async with in_transaction("default") as t_conn:
sql_script = open(file=f"{settings.DB_MIGRATE_PATH}{os.sep}{migration_script}", mode="r")
await t_conn.execute_script(sql_script)
await Migrate.create(file=migration_script)



0 comments on commit efb0077

Please sign in to comment.