Guest User

Untitled

a guest
Sep 27th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #!/usr/local/bin/bash
  2. #
  3. # Description: Dump all triggers of a database, each in a seperate file. See below which parameters to use. At execution it will ask for the MySQL password
  4. #
  5. #
  6.  
  7. usageMessage=$(cat << EOF
  8. usage: mysqldump_trigger.sh [-h hostname] [-p port] [-u user] [-d database] [-o outfolder] [\?]
  9. Dump all triggers of MySQL database schema to files. Each trigger will be put in a seperate file. At execution there will be asked for the password of the SQL user.
  10.  
  11. -h : Hostname of de MySQL server
  12.  
  13. -p : Port number of the MySQL server
  14.  
  15. -u : MySQL user
  16.  
  17. -d : Database name of which the triggers will be dumped
  18.  
  19. -o : Output folder of the trigger.sql files. Each file will have the name of the trigger.
  20.  
  21. EOF
  22. )
  23.  
  24.  
  25. # INITIALIZING variables
  26. MYSQL=`which mysql`
  27. newline=$(echo -e '\r')
  28.  
  29. if (( $OPTIND == 1 )); then
  30. echo "${usageMessage}"
  31. exit 1
  32. fi
  33.  
  34. # Parsing commandline arguments
  35. while getopts ":u:h:p:d:o:H" opt; do
  36. case ${opt} in
  37. h ) # host
  38. host=$OPTARG
  39. ;;
  40. p ) # port
  41. port=$OPTARG
  42. ;;
  43. u ) # user
  44. user=$OPTARG
  45. ;;
  46. d ) # database
  47. database=$OPTARG
  48. ;;
  49. o )
  50. outputFolder=$OPTARG
  51. mkdir -p "${outputFolder}"
  52. ;;
  53. \? ) #Help
  54.  
  55. echo "Invalid option ${OPTARG}"
  56. exit 1
  57. ;;
  58. : ) # parameter is missing a argument
  59. echo "Invalid option: ${OPTARG} requires an argument" 1>&2
  60. exit 1
  61. ;;
  62. esac
  63. done
  64. shift $((OPTIND -1))
  65.  
  66. # ask for password. Will not be shown in the terminal
  67. read -sp "Enter password: " password
  68.  
  69. MYSQL_PARAMS="-u ${user} --password=${password} -h ${host} -P ${port} -D ${database}"
  70.  
  71. # retrieve all the triggers of a database schema and loop for the the CREATE statement of each of them
  72. "${MYSQL}" ${MYSQL_PARAMS} -NBe "SELECT TRIGGER_NAME FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA = '${database}'" -D INFORMATION_SCHEMA | while read -a row;
  73. do
  74. trigger="${row[0]}"
  75. while read -r line; do
  76. triggerName=$(echo $line | awk '{print $1}')
  77. value=$(echo $line | awk '{print $1=""; print $0}' | sed ':a;N;$!ba;s/\n/ /g'| sed 's/^[ \t]*//g' | sed "s/STRICT.*trigger/DELIMITER ;;\\${newline}CREATE TRIGGER/g" | sed "s/end utf8 utf8_general_ci utf8_general_ci/\\${newline}END;;\\${newline}DELIMITER ;/g")
  78. echo "Exporting $triggerName"
  79. echo "$value" >> "${outputFolder}/${triggerName}.sql"
  80. done< <("${MYSQL}" ${MYSQL_PARAMS} -NBe "SHOW CREATE TRIGGER ${trigger}")
  81. done;
Add Comment
Please, Sign In to add comment