Skip to content

Instantly share code, notes, and snippets.

@thevtm
Created July 1, 2022 13:26
Show Gist options
  • Save thevtm/454003bba8a00ce50efa2958246fdbc0 to your computer and use it in GitHub Desktop.
Save thevtm/454003bba8a00ce50efa2958246fdbc0 to your computer and use it in GitHub Desktop.
Database Development Utilities
#!/bin/python
# This is a simple script to help save and restore the database during development.
# Usage:
# - dev-db save users
# - dev-db restore users
import sys
import os
# Config
DB_HOST = "0.0.0.0"
DB_PORT = "3306"
DB_USER = "root"
DB_PASSWORD = "password"
DB_DATABASE = "app_development"
DB_DUMPS_DIRECTORY = "db-dumps"
PROFILES = {
'users': [
'users',
'users_notification_preferences',
],
'products': [
'offers',
'offer_translations'
]
}
# Execution
# 1. Validate arguments
SAVE_COMMAND = 'save'
RESTORE_COMMAND = 'restore'
if (len(sys.argv) != 3):
raise Exception('Invalid arguments!')
command_arg = sys.argv[1]
command_profile = sys.argv[2]
if (command_arg not in [SAVE_COMMAND, RESTORE_COMMAND]):
raise Exception(f'"{command_arg}" is not a valid command!')
if (command_profile not in PROFILES.keys()):
raise Exception(f'"{command_profile}" is not a valid profile!')
# 2. Execute command
script_file_directory_path = os.path.dirname(os.path.realpath(__file__))
if (command_arg == SAVE_COMMAND):
print(f'Saving {command_profile}...')
output_file_path = f'{script_file_directory_path}/{DB_DUMPS_DIRECTORY}/{command_profile}.sql'
print(f'{command_profile.capitalize()} will be saved to "{output_file_path}"')
tables = ' '.join(PROFILES[command_profile])
command = f'mysqldump --host={DB_HOST} --user={DB_USER} --password={DB_PASSWORD} {DB_DATABASE} {tables} > {output_file_path}'
os.system(command)
print(f'{command_profile.capitalize()} saved successfully!')
elif (command_arg == RESTORE_COMMAND):
print(f'Restoring {command_profile}...')
input_file_path = f'{script_file_directory_path}/{DB_DUMPS_DIRECTORY}/{command_profile}.sql'
print(f'Using file "{input_file_path}"')
command = f'mysql --host={DB_HOST} --user={DB_USER} --password={DB_PASSWORD} {DB_DATABASE} < {input_file_path}'
os.system(command)
print(f'{command_profile.capitalize()} restored successfully!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment