1
0
mirror of https://github.com/spl0k/supysonic.git synced 2024-09-19 10:51:04 +00:00

First throw at automatic database migrations

Only supporting SQL scripts for now
This commit is contained in:
spl0k 2018-08-29 17:46:59 +02:00
parent 2568b9bc91
commit e84459d627
19 changed files with 23 additions and 8 deletions

View File

@ -1,6 +1,6 @@
include cgi-bin/* include cgi-bin/*
include config.sample include config.sample
include README.md include README.md
include supysonic/schema/* recursive-include supysonic/schema *
recursive-include supysonic/templates * recursive-include supysonic/templates *
recursive-include supysonic/static * recursive-include supysonic/static *

View File

@ -507,25 +507,40 @@ def parse_uri(database_uri):
return dict(provider = 'mysql', user = uri.username, passwd = uri.password, host = uri.hostname, db = uri.path[1:], **args) return dict(provider = 'mysql', user = uri.username, passwd = uri.password, host = uri.hostname, db = uri.path[1:], **args)
return dict() return dict()
def execute_sql_resource_script(respath):
sql = pkg_resources.resource_string(__package__, respath).decode('utf-8')
for statement in sql.split(';'):
statement = statement.strip()
if statement and not statement.startswith('--'):
metadb.execute(statement)
def init_database(database_uri): def init_database(database_uri):
settings = parse_uri(database_uri) settings = parse_uri(database_uri)
metadb.bind(**settings) metadb.bind(**settings)
metadb.generate_mapping(check_tables = False) metadb.generate_mapping(check_tables = False)
# Check if we should create the tables
try: try:
metadb.check_tables() metadb.check_tables()
except DatabaseError: except DatabaseError:
sql = pkg_resources.resource_string(__package__, 'schema/' + settings['provider'] + '.sql').decode('utf-8')
with db_session: with db_session:
for statement in sql.split(';'): execute_sql_resource_script('schema/' + settings['provider'] + '.sql')
statement = statement.strip()
if statement:
metadb.execute(statement)
Meta(key = 'schema_version', value = SCHEMA_VERSION) Meta(key = 'schema_version', value = SCHEMA_VERSION)
finally:
metadb.disconnect()
# Check for schema changes
with db_session:
version = Meta['schema_version']
if version.value < SCHEMA_VERSION:
migrations = sorted(pkg_resources.resource_listdir(__package__, 'schema/migration/' + settings['provider']))
for migration in migrations:
date, ext = os.path.splitext(migration)
if date <= version.value or ext != '.sql':
continue
execute_sql_resource_script('schema/migration/{}/{}'.format(settings['provider'], migration))
version.value = SCHEMA_VERSION
metadb.disconnect()
db.bind(**settings) db.bind(**settings)
db.generate_mapping(check_tables = False) db.generate_mapping(check_tables = False)