From 9d9a4fe3f2a2f2cb53781707553b818589f0e617 Mon Sep 17 00:00:00 2001 From: "raoha.rh" Date: Tue, 24 Dec 2024 11:22:19 +0800 Subject: [PATCH] feat: add bot token usage analyzer --- .../20241224030938_remote_schema.sql | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 migrations/supabase/migrations/20241224030938_remote_schema.sql diff --git a/migrations/supabase/migrations/20241224030938_remote_schema.sql b/migrations/supabase/migrations/20241224030938_remote_schema.sql new file mode 100644 index 00000000..8de95576 --- /dev/null +++ b/migrations/supabase/migrations/20241224030938_remote_schema.sql @@ -0,0 +1,24 @@ +set check_function_bodies = off; + +CREATE OR REPLACE FUNCTION public.analyze_user_token_usage(start_date date, end_date date) + RETURNS TABLE(bot_id text, usage_date date, input_tokens bigint, output_tokens bigint, total_tokens bigint) + LANGUAGE plpgsql +AS $function$ +BEGIN + RETURN QUERY + SELECT + u.bot_id AS bot_id, + u.date AS usage_date, -- 使用别名来避免歧义 + SUM(u.input_token)::BIGINT AS input_tokens, -- 将结果转换为 BIGINT + SUM(u.output_token)::BIGINT AS output_tokens, -- 将结果转换为 BIGINT + SUM(u.total_token)::BIGINT AS total_tokens -- 将结果转换为 BIGINT + FROM user_token_usage u + WHERE + u.date >= start_date AND + u.date <= end_date + GROUP BY u.date, u.bot_id; +END; +$function$ +; + +