From 0beb1147b9cc1de3c112ba60a2d5328c69015099 Mon Sep 17 00:00:00 2001 From: Gregoo Date: Mon, 27 Jan 2025 22:23:54 +0100 Subject: [PATCH] Allow more advanced migration action through a companion python file --- bricktracker/migrations/__init__.py | 0 bricktracker/sql.py | 28 +++++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 bricktracker/migrations/__init__.py diff --git a/bricktracker/migrations/__init__.py b/bricktracker/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bricktracker/sql.py b/bricktracker/sql.py index 07811d9..9e47d9a 100644 --- a/bricktracker/sql.py +++ b/bricktracker/sql.py @@ -1,3 +1,4 @@ +from importlib import import_module import logging import os import sqlite3 @@ -301,7 +302,32 @@ class BrickSQL(object): version=pending.version) ) - self.executescript(pending.get_query()) + # Load context from the migrations if it exists + # It looks for a file in migrations/ named after the SQL file + # and containing one function named migration_xxxx, also named + # after the SQL file, returning a context dict. + # + # For instance: + # - sql/migrations/0007.sql + # - migrations/0007.py + # - def migration_0007(BrickSQL) -> dict[str, Any] + try: + module = import_module( + '.migrations.{name}'.format( + name=pending.name + ), + package='bricktracker' + ) + + function = getattr(module, 'migration_{name}'.format( + name=pending.name + )) + + context: dict[str, Any] = function(self) + except Exception: + context: dict[str, Any] = {} + + self.executescript(pending.get_query(), **context) self.execute('schema/set_version', version=pending.version) # Tells whether the database needs upgrade