From 075f931b5e72256c95744eed03a12c8b425d61cf Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Tue, 18 Jul 2023 15:17:18 -0500 Subject: [PATCH] Add separate functions for dump, restore of mysql DB --- rattail_fabric2/mysql.py | 50 +++++++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/rattail_fabric2/mysql.py b/rattail_fabric2/mysql.py index 889fa7a..a96dbbb 100644 --- a/rattail_fabric2/mysql.py +++ b/rattail_fabric2/mysql.py @@ -2,7 +2,7 @@ ################################################################################ # # Rattail -- Retail Software Framework -# Copyright © 2010-2021 Lance Edgar +# Copyright © 2010-2023 Lance Edgar # # This file is part of Rattail. # @@ -149,20 +149,31 @@ def script(c, path, database=''): c.sudo("bash -c 'mysql {} < {}'".format(database, path)) +def dump_db(c, name, skip_triggers=False): + """ + Dump a database to file, on the server represented by ``c`` param. + + This function returns the name of the DB dump file. The name will + not have a path component as it's assumed to be in the home folder + of the connection user. + """ + skip_triggers = '--skip-triggers' if skip_triggers else '' + # note, we force sudo "as root" to ensure -H flag is used + # (which allows us to leverage /root/.my.cnf config file) + c.sudo(f'mysqldump {skip_triggers} --result-file={name}.sql {name}', + user='root') + c.sudo(f'gzip --force {name}.sql') + return f'{name}.sql.gz' + + def download_db(c, name, destination=None, **kwargs): """ Download a database from the "current" server. """ - if destination is None: - destination = './{}.sql.gz'.format(name) - triggers = '--skip-triggers' if kwargs.get('skip_triggers') else '' - mysqldump = 'mysqldump {0} --result-file={1}.sql {1}'.format(triggers, name) - # note, we force sudo "as root" to ensure -H flag is used - # (which allows us to leverage /root/.my.cnf config file) - c.sudo(mysqldump, user='root') - c.sudo('gzip --force {}.sql'.format(name)) - c.get('{}.sql.gz'.format(name), destination) - c.sudo('rm {}.sql.gz'.format(name)) + filename = dump_db(c, name, + skip_triggers=kwargs.get('skip_triggers', False)) + c.get(filename, destination or f'./{filename}') + c.sudo(f'rm {filename}') def clone_db(c, name, download, user=None, force=False): @@ -193,3 +204,20 @@ def clone_db(c, name, download, user=None, force=False): c.run('gunzip --force {}.sql.gz'.format(name)) c.sudo("bash -c 'mysql {0} < {0}.sql'".format(name)) c.run('rm {}.sql'.format(name)) + + +def restore_db(c, name, path): + """ + Restore a database from a dump file. + + :param name: Name of the database to restore. + + :param path: Path to the DB dump file, which should end in ``.sql.gz`` + """ + if not path.endswith('.sql.gz'): + raise ValueError("Path to dump file must end in `.sql.gz`") + + c.sudo(f'gunzip --force {path}') + sql_path = path[:-3] + c.sudo(f"bash -c 'mysql {name} < {sql_path}'") + c.sudo(f'rm {sql_path}')