sky/migrations/00001_init.sql
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

408 lines
16 KiB
PL/PgSQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- +goose Up
-- +goose StatementBegin
-- ============================================================
-- 00001_init.sql — 内容平台 V4 初始 Schema
-- 目标:PostgreSQL 16+
-- 约定:
-- * 所有主键为 UUID(应用层生成 v7,时间有序)
-- * 时间统一 TIMESTAMPTZ,应用层用 UTC
-- * 金额统一 BIGINT 存「分」
-- * 状态字段用 TEXT + CHECK(不用 ENUM,避免 ALTER TYPE 锁表)
-- * 软删除统一 deleted_at
-- ============================================================
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS btree_gin;
-- ---------- 用户 ----------
CREATE TABLE users (
id UUID PRIMARY KEY,
account TEXT NOT NULL,
nickname TEXT NOT NULL,
email TEXT,
phone TEXT,
password_hash TEXT NOT NULL,
avatar_url TEXT,
role TEXT NOT NULL DEFAULT 'user'
CHECK (role IN ('super_admin','operator','reviewer','author','user')),
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active','banned','deleted')),
bio TEXT,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX uq_users_account ON users (lower(account)) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX uq_users_email ON users (lower(email)) WHERE email IS NOT NULL AND deleted_at IS NULL;
CREATE UNIQUE INDEX uq_users_phone ON users (phone) WHERE phone IS NOT NULL AND deleted_at IS NULL;
CREATE INDEX idx_users_role_status ON users (role, status) WHERE deleted_at IS NULL;
-- ---------- 分类(自引用树) ----------
CREATE TABLE categories (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
slug TEXT NOT NULL,
parent_id UUID REFERENCES categories(id) ON DELETE RESTRICT,
sort_order INTEGER NOT NULL DEFAULT 0,
icon_url TEXT,
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active','hidden')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX uq_categories_slug ON categories (slug);
CREATE INDEX idx_categories_parent ON categories (parent_id, sort_order);
-- ---------- 标签 ----------
CREATE TABLE tags (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
article_count INTEGER NOT NULL DEFAULT 0 CHECK (article_count >= 0),
heat_count BIGINT NOT NULL DEFAULT 0 CHECK (heat_count >= 0),
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active','hidden')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX uq_tags_name ON tags (lower(name));
CREATE INDEX idx_tags_hot ON tags (heat_count DESC) WHERE status = 'active';
-- ---------- 文章 ----------
CREATE TABLE articles (
id UUID PRIMARY KEY,
mask_id TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
rich_text_title JSONB,
subtitle TEXT,
abstract TEXT,
cover_img_url TEXT,
cover_crop JSONB,
-- 视觉配置(原 config_json 拆解)
visual_config JSONB NOT NULL DEFAULT '{}'::jsonb,
interaction_config JSONB NOT NULL DEFAULT '{}'::jsonb,
-- 从 config_json 提升为独立列的字段(参与查询/统计的必须拆出来)
bg_style TEXT,
bg_img_url TEXT,
font_id TEXT,
music_id TEXT,
text_pos TEXT CHECK (text_pos IS NULL OR text_pos IN ('left','center','right')),
enable_watermark BOOLEAN NOT NULL DEFAULT false,
enable_comment BOOLEAN NOT NULL DEFAULT true,
privacy TEXT NOT NULL DEFAULT 'public'
CHECK (privacy IN ('public','private','password','paid')),
privacy_password TEXT,
has_reward BOOLEAN NOT NULL DEFAULT false,
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
category_id UUID REFERENCES categories(id) ON DELETE SET NULL,
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft','pending','published','offline')),
review_status TEXT NOT NULL DEFAULT 'pending'
CHECK (review_status IN ('pending','approved','rejected')),
review_note TEXT,
reviewed_by UUID REFERENCES users(id) ON DELETE SET NULL,
reviewed_at TIMESTAMPTZ,
published_at TIMESTAMPTZ,
-- 计数字段:PG 侧为「最终一致」的持久化快照,实时值在 Valkey
view_count BIGINT NOT NULL DEFAULT 0 CHECK (view_count >= 0),
like_count BIGINT NOT NULL DEFAULT 0 CHECK (like_count >= 0),
fav_count BIGINT NOT NULL DEFAULT 0 CHECK (fav_count >= 0),
comment_count BIGINT NOT NULL DEFAULT 0 CHECK (comment_count >= 0),
share_count BIGINT NOT NULL DEFAULT 0 CHECK (share_count >= 0),
schema_version INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
CONSTRAINT chk_articles_published_at
CHECK (status <> 'published' OR published_at IS NOT NULL)
);
CREATE UNIQUE INDEX uq_articles_mask ON articles (mask_id);
-- 列表主路径:只索引已发布,索引体积减半
CREATE INDEX idx_articles_pub ON articles (published_at DESC, id DESC)
WHERE status = 'published' AND deleted_at IS NULL;
CREATE INDEX idx_articles_cat_pub ON articles (category_id, published_at DESC)
WHERE status = 'published' AND deleted_at IS NULL;
CREATE INDEX idx_articles_owner ON articles (owner_id, updated_at DESC)
WHERE deleted_at IS NULL;
CREATE INDEX idx_articles_review ON articles (created_at DESC)
WHERE review_status = 'pending' AND deleted_at IS NULL;
CREATE INDEX idx_articles_title_trgm ON articles USING gin (title gin_trgm_ops)
WHERE deleted_at IS NULL;
CREATE INDEX idx_articles_visual_gin ON articles USING gin (visual_config);
CREATE INDEX idx_articles_interaction_gin ON articles USING gin (interaction_config);
-- ---------- 区块 ----------
CREATE TABLE sections (
id UUID PRIMARY KEY,
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
order_index INTEGER NOT NULL CHECK (order_index >= 0),
kind TEXT NOT NULL CHECK (kind IN (
'text','subtitle','image','video','audio','vote','location','goods'
)),
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT chk_sections_payload_object CHECK (jsonb_typeof(payload) = 'object')
);
CREATE INDEX idx_sections_art ON sections (article_id, order_index);
-- 编辑器同篇文章内 order_index 不重复
CREATE UNIQUE INDEX uq_sections_art_order ON sections (article_id, order_index);
-- ---------- 文章-标签 ----------
CREATE TABLE article_tags (
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
tag_id UUID NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (article_id, tag_id)
);
CREATE INDEX idx_article_tags_tag ON article_tags (tag_id, article_id);
-- ---------- 点赞 / 收藏 / 关注 ----------
CREATE TABLE article_likes (
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (article_id, user_id)
);
CREATE INDEX idx_article_likes_user ON article_likes (user_id, created_at DESC);
CREATE TABLE article_favorites (
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
folder_name TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (article_id, user_id)
);
CREATE INDEX idx_fav_user ON article_favorites (user_id, created_at DESC);
CREATE TABLE user_follows (
follower_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
following_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (follower_id, following_id),
CONSTRAINT chk_follows_self CHECK (follower_id <> following_id)
);
CREATE INDEX idx_follows_following ON user_follows (following_id, created_at DESC);
-- ---------- 评论 ----------
CREATE TABLE comments (
id UUID PRIMARY KEY,
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
parent_id UUID REFERENCES comments(id) ON DELETE CASCADE,
reply_to_comment_id UUID REFERENCES comments(id) ON DELETE SET NULL,
reply_to_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
content TEXT NOT NULL CHECK (char_length(content) BETWEEN 1 AND 5000),
depth SMALLINT NOT NULL DEFAULT 0 CHECK (depth BETWEEN 0 AND 3),
like_count BIGINT NOT NULL DEFAULT 0 CHECK (like_count >= 0),
status TEXT NOT NULL DEFAULT 'visible'
CHECK (status IN ('visible','hidden','deleted')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ
);
CREATE INDEX idx_comments_art ON comments (article_id, created_at DESC)
WHERE status = 'visible' AND deleted_at IS NULL;
CREATE INDEX idx_comments_parent ON comments (parent_id, created_at)
WHERE status = 'visible' AND deleted_at IS NULL;
CREATE INDEX idx_comments_user ON comments (user_id, created_at DESC);
CREATE TABLE comment_likes (
comment_id UUID NOT NULL REFERENCES comments(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (comment_id, user_id)
);
-- ---------- 通知 ----------
CREATE TABLE notifications (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
actor_id UUID REFERENCES users(id) ON DELETE SET NULL,
type TEXT NOT NULL CHECK (type IN (
'like','comment','reply','follow','mention','review','system'
)),
entity_type TEXT NOT NULL DEFAULT '',
entity_id UUID,
title TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
is_read BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 红点查询是全站最高频的查询之一,必须走部分索引
CREATE INDEX idx_notif_unread ON notifications (user_id, created_at DESC)
WHERE is_read = false;
CREATE INDEX idx_notif_all ON notifications (user_id, created_at DESC);
-- ---------- 举报 ----------
CREATE TABLE reports (
id UUID PRIMARY KEY,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_type TEXT NOT NULL CHECK (target_type IN ('article','comment','user')),
target_id UUID NOT NULL,
reason TEXT NOT NULL,
description TEXT,
evidence_json JSONB,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','handled','rejected')),
handler_id UUID REFERENCES users(id) ON DELETE SET NULL,
handle_note TEXT,
handled_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_reports_pending ON reports (created_at DESC) WHERE status = 'pending';
CREATE INDEX idx_reports_target ON reports (target_type, target_id);
-- ---------- 钱包与收益 ----------
CREATE TABLE author_wallets (
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
balance_cents BIGINT NOT NULL DEFAULT 0 CHECK (balance_cents >= 0),
total_earned_cents BIGINT NOT NULL DEFAULT 0 CHECK (total_earned_cents >= 0),
frozen_cents BIGINT NOT NULL DEFAULT 0 CHECK (frozen_cents >= 0),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE author_earnings_records (
id UUID PRIMARY KEY,
author_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
article_id UUID REFERENCES articles(id) ON DELETE SET NULL,
type TEXT NOT NULL CHECK (type IN ('reward','bonus','withdraw','refund')),
amount_cents BIGINT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','settled','failed')),
remark TEXT,
idempotency_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 幂等键:第三方支付回调重复投递时不会重复入账
CREATE UNIQUE INDEX uq_earnings_idem ON author_earnings_records (idempotency_key);
CREATE INDEX idx_earnings_author ON author_earnings_records (author_id, created_at DESC);
-- ---------- 每日统计(按月分区) ----------
CREATE TABLE article_stats_daily (
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
stat_date DATE NOT NULL,
pv_count BIGINT NOT NULL DEFAULT 0,
uv_count BIGINT NOT NULL DEFAULT 0,
like_inc BIGINT NOT NULL DEFAULT 0,
fav_inc BIGINT NOT NULL DEFAULT 0,
share_inc BIGINT NOT NULL DEFAULT 0,
comment_inc BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (article_id, stat_date)
) PARTITION BY RANGE (stat_date);
-- 初始分区:覆盖 2026-01 起 24 个月,后续由定时任务 precreate 下一个月
DO $$
DECLARE
start_date DATE := '2026-01-01';
i INT;
part_name TEXT;
from_d DATE;
to_d DATE;
BEGIN
FOR i IN 0..23 LOOP
from_d := start_date + (i || ' months')::interval;
to_d := start_date + ((i+1) || ' months')::interval;
part_name := 'article_stats_daily_' || to_char(from_d, 'YYYYMM');
EXECUTE format(
'CREATE TABLE IF NOT EXISTS %I PARTITION OF article_stats_daily FOR VALUES FROM (%L) TO (%L)',
part_name, from_d, to_d
);
END LOOP;
END $$;
CREATE INDEX idx_stats_date ON article_stats_daily (stat_date);
-- ---------- 系统设置 ----------
CREATE TABLE system_settings (
key TEXT PRIMARY KEY,
value_json JSONB NOT NULL DEFAULT '{}'::jsonb,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- ---------- 搜索 outbox(索引同步用,不依赖 PG NOTIFY,避免连接断开丢消息) ----------
CREATE TABLE search_outbox (
id BIGSERIAL PRIMARY KEY,
entity_type TEXT NOT NULL CHECK (entity_type IN ('article','user','tag')),
entity_id UUID NOT NULL,
op TEXT NOT NULL CHECK (op IN ('upsert','delete')),
processed BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_outbox_unprocessed ON search_outbox (id) WHERE processed = false;
-- ---------- updated_at 自动维护 ----------
CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DO $$
DECLARE t TEXT;
BEGIN
FOREACH t IN ARRAY ARRAY['users','categories','tags','articles','sections','comments','author_wallets','system_settings']
LOOP
EXECUTE format(
'CREATE TRIGGER trg_%s_touch BEFORE UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION touch_updated_at()',
t, t
);
END LOOP;
END $$;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS search_outbox;
DROP TABLE IF EXISTS system_settings;
DROP TABLE IF EXISTS article_stats_daily;
DROP TABLE IF EXISTS author_earnings_records;
DROP TABLE IF EXISTS author_wallets;
DROP TABLE IF EXISTS reports;
DROP TABLE IF EXISTS notifications;
DROP TABLE IF EXISTS comment_likes;
DROP TABLE IF EXISTS comments;
DROP TABLE IF EXISTS user_follows;
DROP TABLE IF EXISTS article_favorites;
DROP TABLE IF EXISTS article_likes;
DROP TABLE IF EXISTS article_tags;
DROP TABLE IF EXISTS sections;
DROP TABLE IF EXISTS articles;
DROP TABLE IF EXISTS tags;
DROP TABLE IF EXISTS categories;
DROP TABLE IF EXISTS users;
DROP FUNCTION IF EXISTS touch_updated_at();
-- +goose StatementEnd