sub2api/backend/migrations/081_create_risk_tables.sql
win 52ad76e6a4
Some checks failed
CI / test (push) Failing after 1m31s
CI / golangci-lint (push) Failing after 32s
Security Scan / backend-security (push) Failing after 32s
Security Scan / frontend-security (push) Failing after 31s
fix: remove +migrate Down section from 081 migration
The migrations runner executes the entire file content in a single
transaction, so the Down section DROP statements were being executed
immediately after the Up section, causing tables to be created then
dropped within the same transaction.
2026-03-28 03:25:54 +08:00

39 lines
1.9 KiB
SQL

CREATE TABLE IF NOT EXISTS account_behavior_hourly (
id BIGSERIAL PRIMARY KEY,
account_id BIGINT NOT NULL,
hour_bucket TIMESTAMPTZ NOT NULL,
api_call_count BIGINT NOT NULL DEFAULT 0,
stream_count BIGINT NOT NULL DEFAULT 0,
total_input_tokens BIGINT NOT NULL DEFAULT 0,
total_output_tokens BIGINT NOT NULL DEFAULT 0,
total_duration_ms BIGINT NOT NULL DEFAULT 0,
p50_duration_ms INT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_account_behavior_hourly UNIQUE (account_id, hour_bucket)
);
CREATE INDEX IF NOT EXISTS idx_account_behavior_hourly_account_id ON account_behavior_hourly (account_id);
CREATE INDEX IF NOT EXISTS idx_account_behavior_hourly_hour_bucket ON account_behavior_hourly (hour_bucket DESC);
CREATE TABLE IF NOT EXISTS account_risk_scores (
id BIGSERIAL PRIMARY KEY,
account_id BIGINT NOT NULL,
risk_score DOUBLE PRECISION NOT NULL DEFAULT 0,
risk_level VARCHAR(16) NOT NULL DEFAULT 'LOW',
risk_reasons JSONB NOT NULL DEFAULT '{}',
feature_vector JSONB NOT NULL DEFAULT '{}',
scored_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
model_version INT NOT NULL DEFAULT 1,
idle_override BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_account_risk_scores_account_id UNIQUE (account_id)
);
CREATE INDEX IF NOT EXISTS idx_account_risk_scores_risk_level ON account_risk_scores (risk_level);
CREATE INDEX IF NOT EXISTS idx_account_risk_scores_risk_score ON account_risk_scores (risk_score DESC);
CREATE INDEX IF NOT EXISTS idx_account_risk_scores_scored_at ON account_risk_scores (scored_at DESC);