Branchwell

AI Resource Pro / website / scripts / create-settings-function.sql

1-- Create function to create settings table
2CREATE OR REPLACE FUNCTION create_settings_table()
3RETURNS void AS $$
4BEGIN
5 -- Create settings table if it doesn't exist
6 CREATE TABLE IF NOT EXISTS public.settings (
7 key TEXT PRIMARY KEY,
8 value TEXT NOT NULL,
9 created_at TIMESTAMPTZ DEFAULT now(),
10 updated_at TIMESTAMPTZ DEFAULT now()
11 );
12
13 -- Enable RLS
14 ALTER TABLE public.settings ENABLE ROW LEVEL SECURITY;
15
16 -- Create policy for admins
17 BEGIN
18 CREATE POLICY "Admins can manage settings" ON public.settings
19 FOR ALL USING (
20 EXISTS (
21 SELECT 1 FROM public.users WHERE id = auth.uid() AND is_admin = true
22 )
23 );
24 EXCEPTION
25 WHEN duplicate_object THEN
26 -- Policy already exists, ignore error
27 NULL;
28 END;
29
30 -- Create updated_at trigger
31 BEGIN
32 CREATE TRIGGER set_updated_at
33 BEFORE UPDATE ON public.settings
34 FOR EACH ROW
35 EXECUTE FUNCTION update_updated_at();
36 EXCEPTION
37 WHEN duplicate_object THEN
38 -- Trigger already exists, ignore error
39 NULL;
40 END;
41END;
42$$ LANGUAGE plpgsql;