Advertisement
Guest User

sqlsizer.sh

a guest
Apr 9th, 2018
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 5.44 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. function usage {
  4.     echo "sqlsizer.sh database ..."
  5.     echo ""
  6.     echo "sqlsizer is a script for finding the size of various databases and "
  7.     echo "tables in a database. By default sqlsizer prints the size of every database. "
  8.     echo "You can find the size of a whole database by specifying just the database name or "
  9.     echo "you can find the size of a single table by specifying database.table instead. "
  10.     echo "If you wish to find the sizes of all tables in a database, specify 'database.' with a trailing period."
  11.     echo "This script always checks for databases running on localhost."
  12.     echo ""
  13.     exit
  14. }
  15.  
  16. # converts input numbers to fewer digits using si-prefixes
  17. function humanReadable {
  18.     local bytes="${1:-0}"
  19.     local padding="${2:-0}"
  20.     local base="${3:-1024}"
  21.     awk -v bytes="${bytes}" -v pad="${padding}" -v base="${base}" '
  22.        function human(x, pad, base) {
  23.            if(base!=1024)base=1000
  24.            basesuf=(base==1024)?"iB":"B"
  25.  
  26.            s="BKMGTEPYZ"
  27.            while (x>=base && length(s)>1)
  28.                {x/=base; s=substr(s,2)}
  29.            s=substr(s,1,1)
  30.  
  31.            xf=(pad=="yes") ? ((s=="B")?"%5d   ":"%8.2f") : ((s=="B")?"%d":"%.2f")
  32.            s=(s!="B") ? (s basesuf) : ((pad=="0") ? s : ((basesuf=="iB")?(s "  "):(s " ")))
  33.  
  34.            return sprintf( (xf "%s"), x, s)
  35.        }
  36.        BEGIN{printf human(bytes, pad, base)}'
  37.     return
  38. }
  39.  
  40. # Checks to see if the sqlLoginFile contains working mysql login information.
  41. # sqlLoginFile must be global.
  42. sqlLoginFile="${HOME}/.my.cnf"
  43. function myLoginCheck {
  44.     if [[ -f ${sqlLoginFile} ]]; then
  45.         if mysql --defaults-file="${sqlLoginFile}" -e ";" ; then
  46.             return 0
  47.         fi
  48.     fi
  49.     return 1
  50. }
  51.  
  52. # Prompt for SQL login information, do not return until we have a working login
  53. function userPrompt {
  54.     local enteredPass=""
  55.     read -s -p "Enter SQL root password: " enteredPass
  56.     sqlLoginFile=$(mktemp -q --tmpdir "sqlsizer.XXXXXX")
  57.     trap 'rm -f "${sqlLoginFile}"' EXIT
  58.     chmod 0600 "${sqlLoginFile}"
  59.     cat > "${sqlLoginFile}" << EOF
  60. [client]
  61. user=root
  62. password='${enteredPass}'
  63. EOF
  64.     until mysql --defaults-file="${sqlLoginFile}" -e ";" ; do
  65.         read -s -p "Can't connect, please retry: " enteredPass
  66.         cat > "${sqlLoginFile}" << EOF
  67. [client]
  68. user=root
  69. password='${enteredPass}'
  70. EOF
  71.     done
  72.     echo ""
  73. }
  74.  
  75. # takes a database name as it's only argument. returns true if a database exists with that name
  76. function databaseExists {
  77.     mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names -e "use $1" &> /dev/null
  78.     return
  79. }
  80.  
  81. # takes databasename.tablename as it's only argument. returns true if that table exists in that database
  82. function tableExists {
  83.     local dbname=$(cut -d '.' -f 1 <<< "$1")
  84.     local tablename=$(cut -d '.' -f 2 <<< "$1")
  85.     local retval=$(mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names -e \
  86.     "SELECT COUNT(*) FROM information_schema.tables
  87.    WHERE table_schema = \"${dbname}\" AND table_name = \"${tablename}\";")
  88.     if [[ ${retval} -gt 0 ]]; then
  89.         return 0
  90.     fi
  91.     return 1
  92. }
  93.  
  94. # takes an existing database as it's only argument. Returns it's size in bytes
  95. function databaseSize {
  96.     mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names -e \
  97.     "SELECT SUM(data_length + index_length) FROM information_schema.tables
  98.    WHERE table_schema = \"$1\";"
  99. }
  100.  
  101. # takes an existing database.table as it's only argument. Returns it's size in bytes
  102. function tableSize {
  103.     local dbname=$(cut -d '.' -f 1 <<< "$1")
  104.     local tablename=$(cut -d '.' -f 2 <<< "$1")
  105.     mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names -e \
  106.     "SELECT SUM(data_length + index_length) FROM information_schema.tables
  107.    WHERE table_schema = \"${dbname}\" AND table_name = \"${tablename}\";"
  108. }
  109.  
  110. # returns a list of all tables in a database in database.table format
  111. function getAllTables {
  112.     local database=$(sed 's/.$//g' <<< ${1})
  113.     mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names "${database}" -e "show tables" | sort | sed "s/^/${1}/g"
  114. }
  115.  
  116. # simply returns a list of all databases
  117. function getAllDBs {
  118.     mysql --defaults-file="${sqlLoginFile}" --silent --skip-column-names -e "show databases" | sort
  119. }
  120.  
  121. # --------------------------------------------------------------------------- #
  122.  
  123. if ! myLoginCheck; then
  124.     userPrompt
  125. fi
  126.  
  127. # If no  arguments, print all databases by default
  128. if [[ $# -eq 0 ]]; then
  129.     for d in $(getAllDBs); do
  130.         humanReadable $(databaseSize $d)
  131.         echo " $d"
  132.     done
  133. fi
  134.  
  135. while [[ $# -gt 0 ]]; do
  136.     # option processing
  137.     if [[ $1 == "-"* ]]; then
  138.         if [[ $1 == "-h" || $1 == "--help" ]]; then
  139.             usage
  140.         fi
  141.     fi
  142.  
  143.     # operand processing
  144.     if [[ $1 == *"." ]]; then
  145.         # input is database. print all the tables in a database
  146.         for t in $(getAllTables "$1"); do
  147.             humanReadable $(tableSize $t)
  148.             echo " $t"
  149.         done
  150.     elif [[ $1 == *"."* ]]; then
  151.         # input is database.table. print just that table
  152.         if tableExists $1; then
  153.             humanReadable $(tableSize $1)
  154.             echo " $1"
  155.         fi
  156.     else
  157.         # input is just a database. print just that database
  158.         if databaseExists $1; then
  159.             humanReadable $(databaseSize $1)
  160.             echo " $1"
  161.         fi
  162.     fi
  163.     shift
  164. done
  165.  
  166. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement