mirror of
https://github.com/aljazceru/nutshell.git
synced 2026-02-04 16:24:21 +01:00
allow for internal and external migrations
This commit is contained in:
@@ -12,8 +12,8 @@ async def migrate_databases(db: Database, migrations_module):
|
||||
|
||||
async def set_migration_version(conn, db_name, version):
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO dbversions (db, version) VALUES (?, ?)
|
||||
f"""
|
||||
INSERT INTO {table_with_schema(db, 'dbversions')} (db, version) VALUES (?, ?)
|
||||
ON CONFLICT (db) DO UPDATE SET version = ?
|
||||
""",
|
||||
(db_name, version, version),
|
||||
@@ -22,7 +22,7 @@ async def migrate_databases(db: Database, migrations_module):
|
||||
async def run_migration(db, migrations_module):
|
||||
db_name = migrations_module.__name__.split(".")[-2]
|
||||
for key, migrate in migrations_module.__dict__.items():
|
||||
match = match = matcher.match(key)
|
||||
match = matcher.match(key)
|
||||
if match:
|
||||
version = int(match.group(1))
|
||||
if version > current_versions.get(db_name, 0):
|
||||
@@ -37,17 +37,19 @@ async def migrate_databases(db: Database, migrations_module):
|
||||
async with db.connect() as conn:
|
||||
if conn.type == SQLITE:
|
||||
exists = await conn.fetchone(
|
||||
"SELECT * FROM sqlite_master WHERE type='table' AND name='dbversions'"
|
||||
f"SELECT * FROM sqlite_master WHERE type='table' AND name='{table_with_schema(db, 'dbversions')}'"
|
||||
)
|
||||
elif conn.type in {POSTGRES, COCKROACH}:
|
||||
exists = await conn.fetchone(
|
||||
"SELECT * FROM information_schema.tables WHERE table_name = 'dbversions'"
|
||||
f"SELECT * FROM information_schema.tables WHERE table_name = '{table_with_schema(db, 'dbversions')}'"
|
||||
)
|
||||
|
||||
if not exists:
|
||||
await migrations_module.m000_create_migrations_table(conn)
|
||||
|
||||
rows = await (await conn.execute("SELECT * FROM dbversions")).fetchall()
|
||||
rows = await (
|
||||
await conn.execute(f"SELECT * FROM {table_with_schema(db, 'dbversions')}")
|
||||
).fetchall()
|
||||
current_versions = {row["db"]: row["version"] for row in rows}
|
||||
matcher = re.compile(r"^m(\d\d\d)_")
|
||||
await run_migration(conn, migrations_module)
|
||||
await run_migration(db, migrations_module)
|
||||
|
||||
Reference in New Issue
Block a user