-- 助手逐次请求的用量与收尾原因(P2a,2026-09-22): -- 改前 LLM 调用路径完全不解析 usage,成本不可见,也没有"这次是不是半途收尾"的留痕。 -- 本表每次 /chat 写一行:轮数、工具数、token、耗时、stop_reason(final/token_budget/wallclock_budget/no_progress/max_rounds/aborted)。 -- conversation_id 关联会话(ON DELETE CASCADE),会话按 180 天保留清理时一并清理;无会话时写 NULL。 -- 设计:docs/design/20260922-assistant-agent-framework.md(P2a) DO $$ DECLARE sch text; BEGIN FOR sch IN SELECT nspname FROM pg_namespace WHERE nspname = 'public' OR nspname = 'legacy_public' OR nspname = 'tenant_template' OR nspname LIKE 'tenant_%' ORDER BY 1 LOOP IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = sch AND table_name = 'assistant_conversations') THEN CONTINUE; END IF; EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.assistant_turns ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID REFERENCES %I.assistant_conversations(id) ON DELETE CASCADE, user_id VARCHAR(64) NOT NULL, branch_code VARCHAR(50) NOT NULL, surface VARCHAR(32) NOT NULL, provider VARCHAR(64), model VARCHAR(120), rounds INT NOT NULL DEFAULT 0, tool_calls INT NOT NULL DEFAULT 0, prompt_tokens INT NOT NULL DEFAULT 0, completion_tokens INT NOT NULL DEFAULT 0, elapsed_ms INT NOT NULL DEFAULT 0, stop_reason VARCHAR(32) NOT NULL DEFAULT ''final'', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )', sch, sch ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_assistant_turns_owner ON %I.assistant_turns (user_id, created_at DESC)', sch ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_assistant_turns_branch ON %I.assistant_turns (branch_code, created_at DESC)', sch ); IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN BEGIN EXECUTE format('GRANT SELECT, INSERT ON TABLE %I.assistant_turns TO canteen_app_rls', sch); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'skip grant on %.assistant_turns: %', sch, SQLERRM; END; END IF; END LOOP; END $$; -- 新业务表必须登记进 tenant_business_tables()(平台冻结规则:迁移期有断言守卫,失败即中断) CREATE OR REPLACE FUNCTION public.tenant_business_tables() RETURNS TEXT[] LANGUAGE sql IMMUTABLE AS $$ SELECT ARRAY[ 'after_sale_returns', 'after_sales', 'ai_prompt_overrides', 'ai_prompt_revisions', 'ai_prompt_templates', 'alias_recognition_logs', 'allocation_tasks', 'assistant_conversations', 'assistant_messages', 'assistant_turns', 'bid_awards', 'bid_invitations', 'bid_prices', 'bid_quotes', 'bid_round_items', 'bid_rounds', 'categories', 'cost_adjustments', 'cost_details', 'customer_alias_stats', 'customer_delivery_assignments', 'customer_portal_users', 'customer_processing_aliases', 'customer_quote_sheet_customers', 'customer_quote_sheet_items', 'customer_quote_sheets', 'customer_quote_versions', 'customer_recipients', 'customer_sku_aliases', 'customer_sku_remarks', 'customer_skus', 'customer_statements', 'customers', 'delivery_location_history', 'delivery_person_locations', 'delivery_person_users', 'delivery_persons', 'delivery_schedules', 'delivery_signatures', 'delivery_tasks', 'exception_tickets', 'fixed_costs', 'free_cost_invoice_links', 'free_cost_invoices', 'import_mapping_memories', 'inspection_loss_confirmations', 'inspection_returns', 'inspection_review_logs', 'inspections', 'inventory', 'inventory_logs', 'inventory_reservations', 'invoices', 'market_compare_exclusions', 'market_external_catalog', 'market_price_history', 'market_price_indices', 'market_prices', 'market_sku_external_bindings', 'notifications', 'operation_logs', 'order_allocation_batches', 'order_item_fulfillments', 'order_item_returns', 'order_items', 'orders', 'parse_session_items', 'parse_sessions', 'picking_assign_rules', 'picking_containers', 'picking_items', 'picking_scan_logs', 'picking_tasks', 'price_invert_events', 'print_jobs', 'processing_demand_items', 'processing_demand_picks', 'processing_logs', 'processing_tasks', 'product_catalog', 'product_substitutions', 'purchase_orders', 'purchaser_users', 'quality_report_prep_links', 'quality_reports', 'seasonal_recommendations', 'self_purchase_stock_inbounds', 'sign_records', 'sku_direct_delivery_customers', 'sku_suppliers', 'skus', 'smart_classification_rules', 'statement_disputes', 'statement_lines', 'statement_payments', 'supplier_categories', 'supplier_prep_amend_requests', 'supplier_preparations', 'supplier_price_agreements', 'supplier_rating_snapshots', 'supplier_statements', 'supplier_users', 'suppliers', 'system_configs', 'unit_conversions', 'user_preferences', 'voice_recognition_logs', 'warehouse_locations', 'warehouses', 'weigh_devices' ] $$; DO $$ DECLARE missing text; BEGIN SELECT string_agg(t, ', ') INTO missing FROM unnest(ARRAY['assistant_conversations', 'assistant_messages', 'assistant_turns']) AS t WHERE NOT (t = ANY (public.tenant_business_tables())); IF missing IS NOT NULL THEN RAISE EXCEPTION 'tenant_business_tables() 缺表: %', missing; END IF; END $$;