Branchwell

AI Resource Pro / website / scripts / create-faqs-table.sql

1-- Create the faqs table if it doesn't exist
2CREATE TABLE IF NOT EXISTS faqs (
3 id SERIAL PRIMARY KEY,
4 question TEXT NOT NULL,
5 answer TEXT NOT NULL,
6 created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
7 updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
8);
9
10-- Add comment to table
11COMMENT ON TABLE faqs IS 'Stores frequently asked questions and answers';
12
13-- Add RLS (Row Level Security) policy
14ALTER TABLE faqs ENABLE ROW LEVEL SECURITY;
15
16-- Create policy for public read access if it doesn't exist
17DO $$
18BEGIN
19 IF NOT EXISTS (
20 SELECT 1
21 FROM pg_policies
22 WHERE tablename = 'faqs' AND policyname = 'Faqs are viewable by everyone'
23 ) THEN
24 CREATE POLICY "Faqs are viewable by everyone"
25 ON faqs FOR SELECT
26 USING (true);
27 END IF;
28END
29$$;
30
31-- Create policy for authenticated users to insert/update if it doesn't exist
32DO $$
33BEGIN
34 IF NOT EXISTS (
35 SELECT 1
36 FROM pg_policies
37 WHERE tablename = 'faqs' AND policyname = 'Authenticated users can insert/update faqs'
38 ) THEN
39 CREATE POLICY "Authenticated users can insert/update faqs"
40 ON faqs FOR INSERT
41 TO authenticated
42 WITH CHECK (true);
43 END IF;
44END
45$$;
46
47-- Create policy for update if it doesn't exist
48DO $$
49BEGIN
50 IF NOT EXISTS (
51 SELECT 1
52 FROM pg_policies
53 WHERE tablename = 'faqs' AND policyname = 'Authenticated users can update faqs'
54 ) THEN
55 CREATE POLICY "Authenticated users can update faqs"
56 ON faqs FOR UPDATE
57 TO authenticated
58 USING (true)
59 WITH CHECK (true);
60 END IF;
61END
62$$;
63
64-- Install the text search extension if not already installed
65CREATE EXTENSION IF NOT EXISTS pg_trgm;
66
67-- Create index on question for faster searching if it doesn't exist
68CREATE INDEX IF NOT EXISTS faqs_question_idx ON faqs USING GIN (question gin_trgm_ops);
69
70-- Create trigger function for updating the updated_at timestamp if it doesn't exist
71CREATE OR REPLACE FUNCTION trigger_set_timestamp()
72RETURNS TRIGGER AS $$
73BEGIN
74 NEW.updated_at = NOW();
75 RETURN NEW;
76END;
77$$ LANGUAGE plpgsql;
78
79-- Create trigger if it doesn't exist
80DROP TRIGGER IF EXISTS set_timestamp ON faqs;
81CREATE TRIGGER set_timestamp
82BEFORE UPDATE ON faqs
83FOR EACH ROW
84EXECUTE FUNCTION trigger_set_timestamp();
85
86-- Check if the table has been created successfully
87SELECT COUNT(*) FROM faqs;