MySQL检查自动增量脚本 - 没有'SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES'

时间:2013-11-27 17:46:44

标签: mysql linux bash shell auto-increment

我已经在这个剧本上工作了几天(我最近开始用bash写作)
该脚本检查列何时接近其auto_incement限制。我可以从信息模式中获取auto_increment值。但是,因为我们有数百个表和大约4TB的数据需要一段时间。所以我决定从'SHOW CREATE TABLE'获取auto_increment值,希望它会更快(仍然必须在staging中运行)。我确信有多种方法可以解决这个问题,就像我说我不是一个bash脚本专家,但我想你的意见,如果有什么我可以做得更好。希望这也有助于其他人   谢谢! -Gio

#!/bin/bash
#
# This is bash script checks when auto_increment column is reaching its limit
# To run Script $ ./auto_increment_check.sh [username] [password] [host]

MYSQL_USER="$1"
MYSQL_PASSWD="$2"
MYSQL_HOST="$3"

MYSQL=$(which mysql)
if [ $? != 0 ]
then
  echo -e "\nMYSQL CLIENT NOT PRESENT!\n"
  exit 1
fi

MYSQLCONNECT="$MYSQL -u$MYSQL_USER -p$MYSQL_PASSWD -h $MYSQL_HOST"

QUERY="
SELECT table_schema,
       table_name,
       data_type,
       ( CASE data_type
           WHEN 'tinyint' THEN 255
           WHEN 'smallint' THEN 65535
           WHEN 'mediumint' THEN 16777215
           WHEN 'int' THEN 4294967295
           WHEN 'bigint' THEN 18446744073709551615
         end >> IF(Locate('unsigned', column_type) > 0, 0, 1) ) AS MAX_VALUE
FROM   information_schema.columns
       INNER JOIN information_schema.tables USING (table_schema, table_name)
WHERE  table_schema NOT IN ( 'MYSQL', 'INFORMATION_SCHEMA', 'PERFORMANCE_SCHEMA'
                           )
       AND extra = 'auto_increment'"


$MYSQLCONNECT --batch -N -e "$QUERY" | while read DATABASE TABLE DATA_TYPE MAX_VALUE; 
do
  NEXT_AUTO_INCREMENT=`mysql -uroot -pgio --batch -N -e "SHOW CREATE TABLE $DATABASE.$TABLE" |  awk     -F'AUTO_INCREMENT=' 'NF==1{print "0";next}{sub(/ .*/,"",$2);print $2}'`
  AUTO_INCREMENT_RATIO=$(awk 'BEGIN {printf "%2.2f\n", '$NEXT_AUTO_INCREMENT' / '$MAX_VALUE'}')
  [[ $(awk 'BEGIN{print ('$AUTO_INCREMENT_RATIO'>=0.9)}') -eq 1 ]] && echo "Auto Increment limit almost reached! $DATABASE.$TABLE - NEXT_AUTO_INCREMENT= $NEXT_AUTO_INCREMENT, MAX= $MAX_VALUE, RATIO= $AUTO_INCREMENT_RATIO"
done

1 个答案:

答案 0 :(得分:0)

如果information_schema对您来说很慢,我建议您设置innodb_stats_on_metadata=0

对于监控自动增量容量,您应该使用common_schema执行此操作。

安装common_schema后,您可以运行如下查询:

select * 
from common_schema.auto_increment_columns 
order by auto_increment_ratio desc 
limit 10;

有关详细信息,请阅读我去年就此主题撰写的blog post