py.lib
20:1a3d395b5cdf
Go to Latest
py.lib/db/migrator.py
.
3 Инструмент миграции схемы БД.
5 DOC: https://ws.a0fs.net/w/ncc.ws/devel/python/modules/db_migrator/
8 from os.path import exists, join as p_join, isdir
12 class MigrateError(Exception): pass
15 class MigrateManager(object):
16 def __init__(self, control_table: str, migrate_env: str):
17 self.control_table = control_table
19 if not exists(migrate_env):
20 raise MigrateError('Migrate enviroment not found')
22 self.schema = p_join(migrate_env, 'schema.sql')
23 if not exists(self.schema):
24 raise MigrateError('Schema file not found: %s' % self.schema)
26 self.patch_dir = p_join(migrate_env, 'patch')
27 if not isdir(self.patch_dir):
28 raise MigrateError('Patch dir not found or not directory: %s' % self.patch_dir)
30 def get_patch_files(self, ver: int):
32 for f in listdir(self.patch_dir):
33 if not f.lower().endswith('.sql'):
36 _f = f.strip().split('.')
41 except (TypeError, ValueError) as e:
42 raise MigrateError('Error on parse version "%(ver)s" of file "%(f)s": %(e)s' % {
49 raise MigrateError('Error on get version from filename: %s' % f)
52 raise MigrateError('Version duplicates on parse file: %s' % f)
54 res[_ver] = p_join(self.patch_dir, f)
56 for i in sorted(res.keys()):
61 def get_commands(file):
63 with open(file) as IN:
65 if l.lstrip().startswith('--'):
76 def init_db(self, db):
78 for c in self.get_commands(self.schema):
86 cursor.execute("SELECT version FROM %s" % self.control_table)
97 for up_ver, patch_file in self.get_patch_files(ver):
99 for cmd in self.get_commands(patch_file):
103 cursor.execute("DELETE FROM %s" % self.control_table)
106 INSERT INTO %s (version)
108 """ % (self.control_table, new_ver))
112 def get_conn_from_my_obj(obj: object):
114 Получиение объекта соединения из обёрток, которые я сам себе пишу для работы с DB-API
119 if hasattr(obj, '_conn'):
121 elif hasattr(obj, '_con'):
124 raise TypeError('No known connection object in given database object found')