Files
juwan-backend/desc/sql/users/user_verifications.sql
T
2026-02-27 05:42:13 +08:00

35 lines
1.5 KiB
PL/PgSQL
Raw 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.
CREATE TABLE user_verifications (
id BIGINT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
role VARCHAR(20) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
materials JSONB NOT NULL,
reject_reason TEXT,
reviewed_by BIGINT,
reviewed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT chk_verification_status CHECK (status IN ('pending', 'approved', 'rejected')),
UNIQUE(user_id, role) -- 每个角色只有一条最新的认证记录
);
-- NoteAuto update verification_status of users table
CREATE OR REPLACE FUNCTION sync_user_verification_status()
RETURNS TRIGGER AS $$
DECLARE
status_json JSONB;
BEGIN
SELECT jsonb_object_agg(role, status)
INTO status_json
FROM user_verifications
WHERE user_id = NEW.user_id;
UPDATE users SET verification_status = status_json WHERE id = NEW.user_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_sync_verifications
AFTER INSERT OR UPDATE ON user_verifications
FOR EACH ROW EXECUTE FUNCTION sync_user_verification_status();