@@ -7,7 +7,29 @@ TRUNCATE TABLE document_generations CASCADE;
77-- Clean out existing users
88TRUNCATE TABLE users CASCADE;
99
10- -- Modify users table to ensure ID matches auth.users
10+ -- Identify and drop foreign key constraints that reference users.id
11+ DO $$
12+ DECLARE
13+ r RECORD;
14+ BEGIN
15+ FOR r IN (
16+ SELECT
17+ tc .constraint_name ,
18+ tc .table_name
19+ FROM
20+ information_schema .table_constraints tc
21+ JOIN information_schema .constraint_column_usage ccu ON tc .constraint_name = ccu .constraint_name
22+ WHERE
23+ tc .constraint_type = ' FOREIGN KEY'
24+ AND ccu .table_name = ' users'
25+ AND ccu .column_name = ' id'
26+ ) LOOP
27+ EXECUTE format(' ALTER TABLE %I DROP CONSTRAINT %I CASCADE' , r .table_name , r .constraint_name );
28+ RAISE NOTICE ' Dropped foreign key constraint: % on table: %' , r .constraint_name , r .table_name ;
29+ END LOOP;
30+ END $$;
31+
32+ -- Now we can safely modify the users table
1133ALTER TABLE users DROP CONSTRAINT IF EXISTS users_pkey;
1234ALTER TABLE users ADD CONSTRAINT users_pkey PRIMARY KEY (id);
1335
@@ -32,4 +54,22 @@ CREATE TRIGGER on_auth_user_created
3254 FOR EACH ROW EXECUTE FUNCTION public .handle_new_user ();
3355
3456-- Add a comment explaining the auth integration
35- COMMENT ON TABLE public.users IS ' Custom users table that integrates with auth.users. The id column should match the id in auth.users.' ;
57+ COMMENT ON TABLE public.users IS ' Custom users table that integrates with auth.users. The id column should match the id in auth.users.' ;
58+
59+ -- Re-create foreign key constraints for api_keys
60+ ALTER TABLE api_keys
61+ ADD CONSTRAINT api_keys_user_id_fkey
62+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ;
63+
64+ -- Re-create foreign key constraints for document_generations (if it has one)
65+ DO $$
66+ BEGIN
67+ IF EXISTS (
68+ SELECT 1 FROM information_schema .columns
69+ WHERE table_name = ' document_generations' AND column_name = ' user_id'
70+ ) THEN
71+ ALTER TABLE document_generations
72+ ADD CONSTRAINT document_generations_user_id_fkey
73+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ;
74+ END IF;
75+ END $$;
0 commit comments