Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- ############################################################
- # Program: migrate.sh #
- ############################################################
- ## BEGIN SCRIPT
- usage()
- {
- cat << EOF
- usage: $(basename $0) [OPTIONS] <COMMAND>
- OPTIONS can have:
- -h Show this message
- -v Verbose
- COMMAND can be one of:
- up
- all
- You can either write the db credentials in a file named 'config'
- located in the same dir as this script, or pass them like:
- user=someuser host=somehost pass=somepass db=somedbname $(basename $0) up.
- Also, any variables written in the config file will overwrite those
- in the command line.
- EOF
- }
- debug()
- {
- [ -z $VERBOSE ] && echo $1
- }
- EXIT_INVALID_ARGS=1
- EXIT_SQL_ERROR=2
- VERBOSE=0
- # Check options passed in.
- while getopts "hv" OPTION
- do
- case $OPTION in
- h)
- usage
- exit EXIT_INVALID_ARGS
- ;;
- v)
- VERBOSE=1
- ;;
- ?)
- usage
- exit EXIT_INVALID_ARGS
- ;;
- esac
- done
- shift $(($OPTIND-1))
- # Checks for custom config file path
- [ -z "$cfg" ] && cfg="./config"
- if [ -e "$cfg" ]
- then
- source "$cfg"
- fi
- # Show usage when we can't find or understand the mandatory parameters.
- if [ $# -ne 1 ] \
- || ! (echo $1 | grep -x 'up\|all' &>/dev/null) \
- || [ -z "$user" ] || [ -z "$host" ]
- then
- usage
- exit EXIT_INVALID_ARGS
- else
- cmd=$1
- fi
- # If no basedir was informed, use current dir
- [ -z "$basedir" ] && basedir=$(pwd)
- for sql_file in "$basedir"/db/*.sql
- do
- debug "Checking filename format for '$sql_file'"
- # If the filename is not in the format YYYYMMDD-HH:MM:SS_description.sql we skip it
- if (echo $sql_file | grep -x '[0-9]\{8\}-\([0-9]\{2\}:\)\{2\}[0-9]\{2\}_[a-zA-Z0-9_]\+\.sql')
- then
- # If this file exists, we have some previously executed migration
- if [ -e "$basedir"/db/.last_migration ]
- then
- last_migration=$(cat "$basedir"/db/.last_migration)
- current_filename=$(basename "$sql_file")
- # Check if the current $sql_file is newer than the last one
- if [[ $(date -d "$(echo ${last_migration:0:17} | sed 's/-/ /')" +%s) \
- > $(date -d "$(echo ${current_filename:0:17} | sed 's/-/ /')" +%s) ]]
- then
- debug "File '$sql_file' is older than last sucessfully executed file" \
- "'$(cat $basedir/db/.last_migration). Skipping..."
- continue
- fi
- fi
- debug "Executing SQL file $sql_file"
- # TODO: implement SQL Server branch
- mysql_out=$(mysql -u"$user" -p"$pass" -h"$host" "$db" < $sql_file)
- debug "MySQL exit code: $?"
- if [ $? -ne 0 ]
- then
- debug $mysql_out
- exit $EXIT_SQL_ERROR
- fi
- else
- debug "Filename '$sql_file' cannot be recognized. Skipping..."
- continue
- fi
- echo "$sql_file" > $basedir/db/.last_migration
- if [[ $cmd = "up" ]]
- then
- break
- fi
- done
- exit 0
Add Comment
Please, Sign In to add comment