Files
medical-mall/pages/mall/analytics/test/03_orders_analytics_policies.sql
2026-01-30 16:17:13 +08:00

71 lines
2.1 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- =============================================
-- Analytics Dashboard 专用:订单表 RLS 策略补充
-- 目标:
-- - 允许角色为 admin / analytics 的用户在 Supabase 中
-- 通过 RPC 查询全量订单与订单明细(仅用于统计分析)。
-- - 不影响普通消费者的订单隔离策略。
-- 依赖:
-- - public.ak_users 表存在且包含字段id(uuid), role(text)
-- - 01_create_tables.sql 已经启用 orders / order_items 的 RLS
-- =============================================
DO $$
BEGIN
-- 如果 ak_users 表不存在,直接跳过(避免报错)
IF NOT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'ak_users'
) THEN
RAISE NOTICE 'ak_users table not found, skip analytics RLS policies for orders.';
RETURN;
END IF;
-- orders允许 admin / analytics 角色读取全量订单用于分析
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = 'public'
AND tablename = 'orders'
AND policyname = 'analytics_can_select_all_orders'
) THEN
EXECUTE $pol$
CREATE POLICY analytics_can_select_all_orders
ON public.orders
FOR SELECT
USING (
auth.role() = 'authenticated'
AND EXISTS (
SELECT 1 FROM public.ak_users u
WHERE u.id = auth.uid()
AND u.role IN ('admin','analytics')
)
)
$pol$;
END IF;
-- order_items允许 admin / analytics 查看任意订单的明细
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = 'public'
AND tablename = 'order_items'
AND policyname = 'analytics_can_select_all_order_items'
) THEN
EXECUTE $pol$
CREATE POLICY analytics_can_select_all_order_items
ON public.order_items
FOR SELECT
USING (
auth.role() = 'authenticated'
AND EXISTS (
SELECT 1 FROM public.ak_users u
WHERE u.id = auth.uid()
AND u.role IN ('admin','analytics')
)
)
$pol$;
END IF;
END;
$$;
SELECT 'orders analytics RLS policies applied' AS message;