You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-- Alternative approach using a function to handle cancellation
2
+
-- This bypasses RLS issues by using a SECURITY DEFINER function
3
+
4
+
-- Create a function to cancel rebalance requests
5
+
CREATE OR REPLACEFUNCTIONpublic.cancel_rebalance_request(p_request_id UUID)
6
+
RETURNS BOOLEAN
7
+
LANGUAGE plpgsql
8
+
SECURITY DEFINER
9
+
SET search_path = public
10
+
AS $$
11
+
DECLARE
12
+
v_user_id UUID;
13
+
v_current_status TEXT;
14
+
BEGIN
15
+
-- Get the user_id and current status of the request
16
+
SELECT user_id, status INTO v_user_id, v_current_status
17
+
FROMpublic.rebalance_requests
18
+
WHERE id = p_request_id;
19
+
20
+
-- Check if request exists
21
+
IF NOT FOUND THEN
22
+
RAISE EXCEPTION 'Rebalance request not found';
23
+
END IF;
24
+
25
+
-- Check if the user owns this request
26
+
IF v_user_id !=auth.uid() THEN
27
+
RAISE EXCEPTION 'Unauthorized: You can only cancel your own rebalance requests';
28
+
END IF;
29
+
30
+
-- Check if already in terminal state
31
+
IF v_current_status IN ('completed', 'cancelled') THEN
32
+
RAISE EXCEPTION 'Cannot cancel: Rebalance is already %', v_current_status;
33
+
END IF;
34
+
35
+
-- Update the request to cancelled
36
+
UPDATEpublic.rebalance_requests
37
+
SET
38
+
status ='cancelled',
39
+
is_canceled = true,
40
+
updated_at = NOW()
41
+
WHERE id = p_request_id;
42
+
43
+
-- Also cancel any related analyses
44
+
UPDATEpublic.analysis_history
45
+
SET
46
+
is_canceled = true,
47
+
analysis_status =-1
48
+
WHERE
49
+
rebalance_request_id = p_request_id
50
+
AND analysis_status =0; -- Only cancel running analyses
51
+
52
+
RETURN TRUE;
53
+
END;
54
+
$$;
55
+
56
+
-- Grant execute permission to authenticated users
57
+
GRANT EXECUTE ON FUNCTION public.cancel_rebalance_request(UUID) TO authenticated;
58
+
59
+
-- Add comment for documentation
60
+
COMMENT ON FUNCTION public.cancel_rebalance_request IS 'Safely cancels a rebalance request and its associated analyses. Only the owner can cancel their own requests.';
0 commit comments