Script para optimizar las tablas fragmentadas en MySQL

Bueno otro buen script a la huchaca… esta escrito en bash aparte de ser utilisisimo porque chequea las tablas fragmentadas y tambien chequea todas las bbdds en busca de tablas MyISAM o INNODB y las optimiza.

#!/bin/bash

VERSION="0.7.2"
log="$PWD/mysql_error_log.txt"

echo "MySQL fragmentation finder (and fixer) v$VERSION, written by Phil Dufault ( http://www.dufault.info/ )"

showHelp() {
echo -e "\tThis script only repairs MyISAM and InnoDB tables"
echo -e "\t--help or -h\t\tthis menu"
echo -e "\t--user username\tspecify mysql username to use\n\t\t\tusing this flag means the script will ask for a password during runtime, unless you supply..."
echo -e "\t--password \"yourpassword\""
echo -e "\t--host hostname\tspecify mysql hostname to use, be it local (default) or remote"
}

#s parse arguments
while [[ $1 == -* ]]; do
case "$1" in
--help|-h) showHelp; exit 0;;
--user) mysqlUser="$2"; shift 2;;
--password) mysqlPass="$2"; shift 2;;
--host) mysqlHost="$2"; shift 2;;
--) shift; break;;
esac
done

# prevent overwriting the commandline args with the ones in .my.cnf, and check that .my.cnf exists
if [[ ! $mysqlUser && -f "$HOME/.my.cnf" ]]; then
if grep "user=" "$HOME/.my.cnf" >/dev/null 2>&1; then
if grep "pass=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlUser=$(grep user= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); mysqlPass=$(grep pass= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); if grep "host=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlHost=$(grep host= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); fi else echo "Found no pass line in your .my.cnf,, fix this or specify with --password" fi else echo "Found no user line in your .my.cnf, fix this or specify with --user" exit 1; fi fi # set localhost if no host is set anywhere else if [[ ! $mysqlHost ]]; then mysqlHost="127.0.0.1" fi # error out if [[ ! $mysqlUser ]]; then echo "Authentication information not found as arguments, nor in $HOME/.my.cnf" echo showHelp exit 1 fi if [[ ! $mysqlPass ]]; then echo -n "Enter your MySQL password: " read -s mysqlPass fi # Test connecting to the database: mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show status" >/dev/null 2>&1
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information.";
exit 1;
fi

# Retrieve the listing of databases:
databases=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show databases;" 2>"$log") );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi

echo -e "Found ${#databases[@]} databases";
for i in ${databases[@]}; do
# get a list of all of the tables, grep for MyISAM or InnoDB, and then sort out the fragmented tables with awk
fragmented=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "SHOW TABLE STATUS FROM $i;" 2>"$log" | awk '{print $1,$2,$10}' | egrep "MyISAM|InnoDB" | awk '$3 > 0' | awk '{print $1}') );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
tput sc
echo -n "Checking $i ... ";
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 1 ]]; then
echo "found ${#fragmented[@]} fragmented tables."
else
echo "found ${#fragmented[@]} fragmented table."
fi
fi
for table in ${fragmented[@]}; do
let fraggedTables=$fraggedTables+1;
echo -ne "\tOptimizing $table ... ";
mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" -D "$i" --skip-column-names --batch -e "optimize table $table" 2>"$log" >/dev/null
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
echo done
done
else
tput rc
tput el
fi
unset fragmented
done

# footer message
if [[ ! $fraggedTables -gt 0 ]]; then
echo "No tables were fragmented, so no optimizing was done.";
else
if [[ $fraggedTables -gt 1 ]]; then
echo "$fraggedTables tables were fragmented, and were optimized.";
else
echo "$fraggedTables table was fragmented, and was optimized.";
fi
fi

if [[ ! -s $log ]]; then
rm -f "$log"
fi

unset fraggedTables

Link | http://www.dufault.info/blog/a-script-to-optimize-fragmented-tables-in-mysql/

Cómo chequear, reparar u optimizar tablas o bases de datos MySQL con mysqlcheck

El cliente mysqlcheck comprueba y repara tablas MyISAM. También puede optimizar y analizar tablas.

mysqlcheck es similar a myisamchk, pero funciona de forma distinta. La principal diferencia operacional es que mysqlcheck debe usarse cuando el servidor mysqld está en ejecución, mientras que myisamchk debe usarse cuando no lo está. El beneficio de usar mysqlcheck es que no tiene que parar el servidor para comprobar o reparar las tablas.

mysqlcheck usa los comandos SQL CHECK TABLE, REPAIR TABLE, ANALYZE TABLE, y OPTIMIZE TABLE de forma conveniente para los usuarios. Determina los comandos a usar en función de la operación que quiera realizar, luego envía los comandos al servidor para ejecutarlos.

Hay tres modos generales de invocar mysqlcheck:

shell> mysqlcheck [opciones] nombre_de_base_de_datos [tablas]
shell> mysqlcheck [opciones] –databases DB1 [DB2 DB3…]
shell> mysqlcheck [opciones] –all-databases

Si no nombra ninguna tabla o usa las opciones –databases o –all-databases, se comprueban todas las bases de datos.

mysqlcheck soporta las siguientes opciones:

Continuar leyendo «Cómo chequear, reparar u optimizar tablas o bases de datos MySQL con mysqlcheck»

Comandos para bases de datos MySQL

Estos son algunos comandos útiles usados por MySQL para manejar bases de datos. Es un listado básico donde no hay mucha explicación. Simplemente es una guía para comenzar a trabajar con las bases de datos Mysql.

Obtener información sobre las bases de datos Mysql :

  • show databases; – Listar todas las bases de datos.
  • connect [database]; – Conectarse a esa base de datos.
  • show tables; – Listar todas las tablas de una base de datos.
  • show table status; – Muestra informacion sobre las tablas de la base de datos.
  • describe [table]; – Muestra la estructura de una tabla de la base de datos.

Manejo de bases de datos Mysql :

  • drop table [table]; – Elimina la tabla, incluyendo registros y estructura.
  • drop table if exists [table]; – Elimina la tabla de la base de datos, pero antes verifica que exista.
  • truncate table [table]; – Elimina los registros, pero mantiene la esrtuctura de la tabla.
  • rename table [table] to [nuevo nombre de tabla]; – Renombra una tabla de la base de datos.

Algunos comandos útiles para consultas a las bases de datos Mysql:

  • select * from [table] limit [numero]; – Muestra los registros desde el 1 hasta [numero].
    Ej. select * from tabla limit 10; – Muestra los 10 primeros registros.
    select * from [table] limit [numero inicio],[numero]; – Muestra los registros desde el numero de inicio hasta numero inicio + numero.
    Ej. select * from tabla limit 11,10; – Muestra desde registro 11 hasta el 20.

Bases de datos Mysql en consola :

  • $ mysqladmin -u -p create – crear base de datos.
  • $ mysqladmin -u -p drop – borrar la base de datos.
  • $ mysqladmin -u root -p proc – listar procesos en ejecucion en el servidor de bases de datos Mysql.
  • $ mysqladmin -u root -p -i 5 status – verificar status cada 5 segundos.
  • $ mysqldump –opt -u -h -p > /path/to/file – Exportar base de datos a un archivo.
  • $ mysqldump –opt -u -h –all-databases -p > /path/to/file – Exportar TODAS las bases de datos a un archivo.
  • $ mysql -h -u -p < /path/to/file – Importar un archivo a la base de datos a mysql
  • $ mysqlcheck -o -u root -p –all-databases – Optimizar las bases de datos mysql.

Verificación y reparación de errores en las bases de datos Mysql :

  • check table [table]; – Verificar la tabla.
  • repair table [table]; – Reparar la tabla rota.

Algún otro comando útil de MySQL?? Se aceptan sugerencias¡¡¡