CREATE TABLE wallets
(
    user_id        BIGINT PRIMARY KEY,
    balance        DECIMAL(12, 2) NOT NULL DEFAULT 0.00,
    frozen_balance DECIMAL(12, 2) NOT NULL DEFAULT 0.00,
    version        INT            NOT NULL DEFAULT 1, -- 必须使用乐观锁
    updated_at     TIMESTAMPTZ    NOT NULL DEFAULT NOW(),

    CONSTRAINT chk_balance_non_negative CHECK (balance >= 0),
    CONSTRAINT chk_frozen_non_negative CHECK (frozen_balance >= 0)
);

CREATE INDEX idx_wallets_updated ON wallets (updated_at DESC);

CREATE TRIGGER trigger_wallets_updated_at
    BEFORE UPDATE
    ON wallets
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();