You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
RuoYi-Vue/sql_refacor0120/auto_add_mysql_partition.sh

59 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/bin/bash
# ==============================================================================
# MySQL 分区表自动扩展脚本(按月分区)
# 适用表t_stock_daily_trade已按 trade_date 按月分区)
# 执行时机每月最后一天凌晨2点确保下一个月分区已创建
# ==============================================================================
# -------------------------- 配置区(用户需根据实际情况修改) --------------------------
DB_HOST="localhost"
DB_PORT="3306"
DB_USER="root"
DB_PASS="your_password"
DB_NAME="a_stock_db"
TARGET_TABLE="t_stock_daily_trade" # 目标分区表
# ----------------------------------------------------------------------------------
# 日志函数
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> /var/log/auto_add_mysql_partition.log
}
# 1. 计算下一个月的关键日期如当前12月下一个月是次年1月
# 下一个月的1号用于分区边界VALUES LESS THAN (TO_DAYS('下下月1号'))
next_month_first_day=$(date -d "$(date +%Y-%m-01) +1 month" +%Y-%m-01)
# 下下月的1号分区边界小于下下月1号即包含整个下一个月
next_next_month_first_day=$(date -d "$next_month_first_day +1 month" +%Y-%m-01)
# 分区名格式p202501
partition_name="p$(date -d "$next_month_first_day" +%Y%m)"
log "INFO: 开始检查MySQL分区下一个月$next_month_first_day,分区名:$partition_name,边界:$next_next_month_first_day"
# 2. 检查分区是否已存在
check_sql="SELECT COUNT(*) FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_SCHEMA = '$DB_NAME'
AND TABLE_NAME = '$TARGET_TABLE'
AND PARTITION_NAME = '$partition_name';"
# 执行查询并获取结果(过滤掉表头和空行)
partition_count=$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -D$DB_NAME -N -s -e "$check_sql")
if [ "$partition_count" -eq 1 ]; then
log "INFO: 分区已存在!无需创建,分区名:$partition_name"
exit 0
fi
# 3. 创建新分区
add_partition_sql="ALTER TABLE $TARGET_TABLE
ADD PARTITION (
PARTITION $partition_name
VALUES LESS THAN (TO_DAYS('$next_next_month_first_day'))
COMMENT '$(date -d "$next_month_first_day" +%Y年%m月)数据'
);"
if mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -D$DB_NAME -e "$add_partition_sql"; then
log "SUCCESS: 分区创建完成!分区名:$partition_name,边界:$next_next_month_first_day"
else
log "ERROR: 分区创建失败SQL$add_partition_sql"
exit 1
fi