|
| 1 | +DROP INDEX shop.idx_orders_placed_at; |
| 2 | + |
| 3 | +CREATE TABLE shop.product_reviews ( |
| 4 | + id uuid DEFAULT gen_random_uuid() NOT NULL, |
| 5 | + product_id uuid NOT NULL, |
| 6 | + customer_id uuid NOT NULL, |
| 7 | + rating int NOT NULL, |
| 8 | + body text, |
| 9 | + created_at timestamptz DEFAULT now() NOT NULL, |
| 10 | + CONSTRAINT product_reviews_pkey PRIMARY KEY (id), |
| 11 | + CONSTRAINT product_reviews_rating_check |
| 12 | + CHECK ( |
| 13 | + rating >= 1 |
| 14 | + AND rating <= 5 |
| 15 | + ) |
| 16 | +); |
| 17 | + |
| 18 | +GRANT SELECT, INSERT ON shop.product_reviews TO app_user; |
| 19 | + |
| 20 | +ALTER TABLE ONLY shop.product_reviews |
| 21 | + ADD CONSTRAINT product_reviews_product_id_fkey |
| 22 | + FOREIGN KEY(product_id) |
| 23 | + REFERENCES shop.products (id) |
| 24 | + ON DELETE CASCADE; |
| 25 | + |
| 26 | +ALTER TABLE ONLY shop.product_reviews |
| 27 | + ADD CONSTRAINT product_reviews_customer_id_fkey |
| 28 | + FOREIGN KEY(customer_id) |
| 29 | + REFERENCES shop.customers (id); |
| 30 | + |
| 31 | +COMMENT ON TABLE shop.product_reviews IS 'Customer product reviews, 1-5 stars.'; |
| 32 | + |
| 33 | +CREATE INDEX idx_product_reviews_product_id ON shop.product_reviews (product_id); |
| 34 | + |
| 35 | +CREATE POLICY orders_insert_own |
| 36 | + ON shop.orders |
| 37 | + AS PERMISSIVE |
| 38 | + FOR INSERT |
| 39 | + TO PUBLIC |
| 40 | + WITH CHECK ( |
| 41 | + customer_id = (current_setting('app.current_customer_id', true))::uuid |
| 42 | + ); |
| 43 | + |
| 44 | +ALTER TABLE shop.customers |
| 45 | + ADD COLUMN marketing_opt_in boolean |
| 46 | + DEFAULT false |
| 47 | + NOT NULL; |
| 48 | + |
| 49 | +ALTER TABLE shop.customers |
| 50 | + DROP COLUMN phone RESTRICT; |
| 51 | + |
| 52 | +ALTER TABLE shop.orders |
| 53 | + DROP CONSTRAINT orders_status_check RESTRICT; |
| 54 | + |
| 55 | +ALTER TABLE shop.orders |
| 56 | + ADD CONSTRAINT orders_status_check |
| 57 | + CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled', 'refunded')); |
| 58 | + |
| 59 | +COMMENT ON FUNCTION shop.order_total(p_order_id uuid) IS NULL; |
| 60 | + |
| 61 | +DROP FUNCTION shop.order_total(uuid); |
| 62 | + |
| 63 | +CREATE FUNCTION shop.order_total( |
| 64 | + p_order_id uuid |
| 65 | +) RETURNS int LANGUAGE sql STABLE AS $EOFCODE$ |
| 66 | + SELECT COALESCE(SUM(quantity * unit_price_cents), 0)::integer |
| 67 | + FROM shop.order_items |
| 68 | + WHERE order_id = p_order_id |
| 69 | + AND quantity > 0; |
| 70 | +$EOFCODE$; |
| 71 | + |
| 72 | +COMMENT ON FUNCTION shop.order_total(p_order_id uuid) IS 'Sum of line totals for an order, in cents.'; |
0 commit comments