-- Questions about a finished detailed analysis (natal or yearly forecast), -- answered by the model that wrote the analysis. Each question uses a -- `question` unit (admins ask for free); a failed answer is refunded once. CREATE TABLE questions ( id uuid PRIMARY KEY, analysis_id uuid NOT NULL REFERENCES analyses ON DELETE CASCADE, asked_by uuid REFERENCES users ON DELETE SET NULL, question text NOT NULL CHECK (length(question) BETWEEN 3 AND 1000), language text NOT NULL, model text NOT NULL, prompt_version text NOT NULL, status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')), answer text, error text, model_used text, input_tokens integer, output_tokens integer, cost_usd double precision, credits_charged integer NOT NULL DEFAULT 0, attempts integer NOT NULL DEFAULT 0, next_attempt_at timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now(), started_at timestamptz, completed_at timestamptz ); CREATE INDEX questions_analysis_idx ON questions (analysis_id, created_at); CREATE INDEX questions_pending_idx ON questions (next_attempt_at) WHERE status = 'pending'; -- Wakes the analysis worker, like a new analysis. CREATE TRIGGER questions_notify AFTER INSERT ON questions FOR EACH STATEMENT EXECUTE FUNCTION notify_analyses(); ALTER TABLE credit_ledger ADD COLUMN question_id uuid REFERENCES questions ON DELETE SET NULL; CREATE UNIQUE INDEX credit_ledger_question_refund_once ON credit_ledger (question_id) WHERE reason = 'refund'; ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_unit_check; ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_unit_check CHECK (unit IN ('natal', 'synastry', 'forecast', 'person', 'question')); ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_reason_check; ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_reason_check CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase', 'person', 'package', 'question')); -- The question-answer prompt is editable on the admin page. ALTER TABLE prompt_revisions DROP CONSTRAINT prompt_revisions_kind_check; ALTER TABLE prompt_revisions ADD CONSTRAINT prompt_revisions_kind_check CHECK (kind IN ('summary', 'natal', 'synastry', 'forecast', 'question'));