优化一键脚本

This commit is contained in:
yml
2026-06-05 21:46:37 +08:00
parent cb79395226
commit 6be0917ce4
3 changed files with 148 additions and 23 deletions
+29 -11
View File
@@ -52,7 +52,7 @@ show_help() {
用法: ./scripts/dev.sh [选项]
选项:
--reset-db 重置数据库(删除并重建)
--reset-db 重置数据库(删除并重建,自动清理旧迁移记录
--seed-only 仅重新同步基础数据
--no-migrate 不执行数据库迁移
--no-frontend 不启动前端
@@ -76,7 +76,7 @@ show_help() {
示例:
./scripts/dev.sh # 正常启动
./scripts/dev.sh --reset-db # 重置数据库后启动
./scripts/dev.sh --reset-db # 重置数据库后启动(推荐迁移后使用)
./scripts/dev.sh --seed-only # 重新同步基础数据
EOF
exit 0
@@ -248,15 +248,33 @@ CREATE TABLE IF NOT EXISTS schema_migrations (
SQL
}
clean_legacy_migrations() {
local has_legacy
has_legacy="$(mysql_scalar "SELECT COUNT(*) FROM schema_migrations WHERE version IN ('000002_payment_refund_schema', '000003_add_indexes', '000004_add_support_status', '000005_add_announcements', '000006_insert_sample_announcements', '000007_add_announcement_permissions', '000008_fix_announcement_charset');")"
if [[ "${has_legacy}" != "0" ]]; then
log_warn "检测到旧的迁移记录(000002-000008),正在清理..."
mysql_hfb --default-character-set=utf8mb4 -e \
"DELETE FROM schema_migrations WHERE version IN ('000002_payment_refund_schema', '000003_add_indexes', '000004_add_support_status', '000005_add_announcements', '000006_insert_sample_announcements', '000007_add_announcement_permissions', '000008_fix_announcement_charset');" "${MYSQL_DATABASE}"
log_success "已清理旧迁移记录"
fi
}
bootstrap_existing_schema_history() {
local migration_count users_exists
migration_count="$(mysql_scalar "SELECT COUNT(*) FROM schema_migrations;")"
users_exists="$(mysql_scalar "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'users';")"
if [[ "${migration_count}" == "0" && "${users_exists}" != "0" ]]; then
log_warn "检测到已有表结构但没有迁移记录,补记 000001_init 并同步初始化脚本"
mysql_hfb --default-character-set=utf8mb4 -e \
"INSERT IGNORE INTO schema_migrations (version) VALUES ('000001_init');" "${MYSQL_DATABASE}"
log_warn "检测到已有表结构但没有迁移记录,补记当前所有迁移文件为已应用"
local file version
shopt -s nullglob
for file in "${MIGRATIONS_DIR}"/*.sql; do
version="$(basename "${file}" .sql)"
mysql_hfb --default-character-set=utf8mb4 -e \
"INSERT IGNORE INTO schema_migrations (version) VALUES ('${version}');" "${MYSQL_DATABASE}"
done
shopt -u nullglob
fi
}
@@ -270,6 +288,11 @@ run_migrations() {
ensure_migration_table
bootstrap_existing_schema_history
# 只有在数据库未重置的情况下才需要清理旧迁移记录
if [[ "${RESET_DB}" != "1" ]]; then
clean_legacy_migrations
fi
local file version applied
local found=0
shopt -s nullglob
@@ -278,12 +301,7 @@ run_migrations() {
version="$(basename "${file}" .sql)"
applied="$(mysql_scalar "SELECT COUNT(*) FROM schema_migrations WHERE version = '${version}';")"
if [[ "${applied}" != "0" ]]; then
if [[ "${version}" == "000001_init" ]]; then
log "同步初始化脚本:${version}"
mysql_hfb --default-character-set=utf8mb4 "${MYSQL_DATABASE}" < "${file}"
else
log "跳过已应用迁移:${version}"
fi
log "跳过已应用迁移:${version}"
continue
fi