1+ -- Create table for Shopify integrations
2+ CREATE TABLE public .shopify_integrations (
3+ id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY ,
4+ user_id UUID NOT NULL ,
5+ campaign_id TEXT NOT NULL ,
6+ shop_domain TEXT NOT NULL ,
7+ access_token TEXT NOT NULL ,
8+ shop_info JSONB,
9+ settings JSONB DEFAULT ' {"scriptsInstalled": false, "webhooksInstalled": false, "autoInject": true}' ::jsonb,
10+ active BOOLEAN DEFAULT true,
11+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
12+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
13+ UNIQUE(shop_domain, campaign_id)
14+ );
15+
16+ -- Enable RLS
17+ ALTER TABLE public .shopify_integrations ENABLE ROW LEVEL SECURITY;
18+
19+ -- Create policies for user access
20+ CREATE POLICY " Users can view their own integrations"
21+ ON public .shopify_integrations
22+ FOR SELECT
23+ USING (auth .uid ()::text = user_id::text );
24+
25+ CREATE POLICY " Users can create their own integrations"
26+ ON public .shopify_integrations
27+ FOR INSERT
28+ WITH CHECK (auth .uid ()::text = user_id::text );
29+
30+ CREATE POLICY " Users can update their own integrations"
31+ ON public .shopify_integrations
32+ FOR UPDATE
33+ USING (auth .uid ()::text = user_id::text );
34+
35+ CREATE POLICY " Users can delete their own integrations"
36+ ON public .shopify_integrations
37+ FOR DELETE
38+ USING (auth .uid ()::text = user_id::text );
39+
40+ -- Create function to update timestamps
41+ CREATE OR REPLACE FUNCTION public .update_updated_at_column()
42+ RETURNS TRIGGER AS $$
43+ BEGIN
44+ NEW .updated_at = now();
45+ RETURN NEW;
46+ END;
47+ $$ LANGUAGE plpgsql;
48+
49+ -- Create trigger for automatic timestamp updates
50+ CREATE TRIGGER update_shopify_integrations_updated_at
51+ BEFORE UPDATE ON public .shopify_integrations
52+ FOR EACH ROW
53+ EXECUTE FUNCTION public .update_updated_at_column ();
54+
55+ -- Create table for OAuth state management
56+ CREATE TABLE public .shopify_oauth_states (
57+ id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY ,
58+ state_token TEXT NOT NULL UNIQUE,
59+ user_id UUID NOT NULL ,
60+ campaign_id TEXT NOT NULL ,
61+ shop_domain TEXT NOT NULL ,
62+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
63+ expires_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT (now() + INTERVAL ' 10 minutes' )
64+ );
65+
66+ -- Enable RLS for OAuth states
67+ ALTER TABLE public .shopify_oauth_states ENABLE ROW LEVEL SECURITY;
68+
69+ -- Policies for OAuth states
70+ CREATE POLICY " Users can manage their own OAuth states"
71+ ON public .shopify_oauth_states
72+ FOR ALL
73+ USING (auth .uid ()::text = user_id::text );
74+
75+ -- Index for performance
76+ CREATE INDEX idx_shopify_integrations_user_campaign ON public .shopify_integrations (user_id, campaign_id);
77+ CREATE INDEX idx_shopify_oauth_states_token ON public .shopify_oauth_states (state_token);
78+ CREATE INDEX idx_shopify_oauth_states_expires ON public .shopify_oauth_states (expires_at);
0 commit comments