1+ -- This migration provides a comprehensive fix for document_generations permissions
2+ -- by addressing both the table structure and RLS policies
3+
4+ -- First, ensure the table has RLS enabled
5+ ALTER TABLE document_generations ENABLE ROW LEVEL SECURITY;
6+
7+ -- Drop all existing policies to start fresh
8+ DROP POLICY IF EXISTS document_generations_select_policy ON document_generations;
9+ DROP POLICY IF EXISTS document_generations_insert_policy ON document_generations;
10+ DROP POLICY IF EXISTS document_generations_all_policy ON document_generations;
11+ DROP POLICY IF EXISTS document_generations_service_role_policy ON document_generations;
12+
13+ -- Ensure user_id is properly set up (NOT NULL and with proper reference)
14+ ALTER TABLE document_generations
15+ ALTER COLUMN user_id SET NOT NULL ,
16+ ADD CONSTRAINT fk_document_generations_user
17+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ;
18+
19+ -- Create a policy for users to select their own document generations
20+ CREATE POLICY document_generations_select_policy ON document_generations
21+ FOR SELECT
22+ USING (
23+ auth .uid ()::text = (SELECT email FROM users WHERE id = user_id)
24+ );
25+
26+ -- Create a policy for users to insert their own document generations
27+ CREATE POLICY document_generations_insert_policy ON document_generations
28+ FOR INSERT
29+ WITH CHECK (
30+ auth .uid ()::text = (SELECT email FROM users WHERE id = user_id)
31+ );
32+
33+ -- Create a policy for the service role to manage all document generations
34+ CREATE POLICY document_generations_service_role_policy ON document_generations
35+ FOR ALL
36+ TO service_role
37+ USING (true);
38+
39+ -- Add an index for better performance
40+ CREATE INDEX IF NOT EXISTS idx_document_generations_user_id ON document_generations(user_id);
41+
42+ -- Log the changes
43+ DO $$
44+ BEGIN
45+ RAISE NOTICE ' Comprehensive fix for document_generations table applied' ;
46+ RAISE NOTICE ' Updated RLS policies to use direct auth.uid() comparison' ;
47+ RAISE NOTICE ' Added foreign key constraint to ensure referential integrity' ;
48+ RAISE NOTICE ' Added service_role policy for all operations' ;
49+ END $$;
0 commit comments