fix(migrations): make all migrations idempotent; distinguish applied vs error

- 006: ADD COLUMN 补 IF NOT EXISTS
- 002: 5 个索引(status_published/slug_unique/post_tags_post/post_tags_tag/cover)补 IF NOT EXISTS
- migrate.sh: 区分「已应用」与「真出错」,真错误时打印输出并中止,不再静默吞掉(M6)

已验证:第二次运行全部 OK(幂等),不再出现重复对象错误。
This commit is contained in:
xfy 2026-06-18 13:34:02 +08:00
parent 71d4126e94
commit 179897ba6f
3 changed files with 18 additions and 8 deletions

View File

@ -66,10 +66,20 @@ echo "$MIGRATION_FILES" | sort | while IFS= read -r file; do
filename=$(basename "$file")
echo -n "[$filename] ... "
if psql "$DATABASE_URL" -f "$file" > /dev/null 2>&1; then
# 区分「已应用」与「真出错」迁移本身已幂等IF NOT EXISTS正常应返回 0。
# 非零退出码视为真错误打印输出并中止避免静默吞错M6
err_output=$(psql "$DATABASE_URL" -f "$file" 2>&1 >/dev/null)
rc=$?
if [[ $rc -eq 0 ]]; then
echo "OK"
elif echo "$err_output" | grep -qiE "already exists|duplicate|multiple primary keys"; then
echo "SKIPPED (already applied)"
else
echo "SKIPPED (already applied or error)"
echo "FAIL"
echo "$err_output" | head -5 | sed 's/^/ /'
echo "Migration aborted due to error in $filename"
exit 1
fi
done

View File

@ -20,8 +20,8 @@ CREATE TABLE IF NOT EXISTS posts (
CONSTRAINT posts_status_check CHECK (status IN ('draft', 'published'))
);
CREATE INDEX idx_posts_status_published ON posts(status, published_at DESC) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX idx_posts_slug_unique ON posts(slug) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_posts_status_published ON posts(status, published_at DESC) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_posts_slug_unique ON posts(slug) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS tags (
id SERIAL PRIMARY KEY,
@ -34,8 +34,8 @@ CREATE TABLE IF NOT EXISTS post_tags (
PRIMARY KEY (post_id, tag_id)
);
CREATE INDEX idx_post_tags_post ON post_tags(post_id);
CREATE INDEX idx_post_tags_tag ON post_tags(tag_id);
CREATE INDEX IF NOT EXISTS idx_post_tags_post ON post_tags(post_id);
CREATE INDEX IF NOT EXISTS idx_post_tags_tag ON post_tags(tag_id);
-- 为封面图添加索引
CREATE INDEX idx_posts_cover ON posts(cover_image) WHERE cover_image IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_posts_cover ON posts(cover_image) WHERE cover_image IS NOT NULL;

View File

@ -1 +1 @@
ALTER TABLE posts ADD COLUMN toc_html TEXT;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS toc_html TEXT;