File tree Expand file tree Collapse file tree 4 files changed +50
-39
lines changed Expand file tree Collapse file tree 4 files changed +50
-39
lines changed Original file line number Diff line number Diff line change 1+ CREATE OR REPLACE PROCEDURE set_default_address(
2+ p_user_id integer ,
3+ p_address_id integer
4+ )
5+ LANGUAGE plpgsql
6+ AS $$
7+ BEGIN
8+ -- Check if the address exists and belongs to the user
9+ IF NOT EXISTS (
10+ SELECT 1 FROM addresses
11+ WHERE id = p_address_id AND user_id = p_user_id
12+ ) THEN
13+ RAISE EXCEPTION ' Address % does not exist or does not belong to user %' ,
14+ p_address_id, p_user_id;
15+ END IF;
16+
17+ -- Start transaction
18+ BEGIN
19+ -- Set all addresses for this user to non-default
20+ UPDATE addresses
21+ SET is_default = false
22+ WHERE user_id = p_user_id;
23+
24+ -- Set the specified address as default
25+ UPDATE addresses
26+ SET is_default = true
27+ WHERE id = p_address_id;
28+
29+ -- Log the change (optional - remove if you don't need logging)
30+ RAISE NOTICE ' Default address set to % for user %' , p_address_id, p_user_id;
31+
32+ EXCEPTION
33+ WHEN OTHERS THEN
34+ -- Rollback will happen automatically
35+ RAISE EXCEPTION ' Failed to set default address: %' , SQLERRM;
36+ END;
37+ END;
38+ $$;
Original file line number Diff line number Diff line change 1+ CREATE TABLE IF NOT EXISTS addresses (
2+ id integer PRIMARY KEY ,
3+ user_id integer NOT NULL REFERENCES users(id),
4+ street_address text NOT NULL ,
5+ city text NOT NULL ,
6+ state_province text ,
7+ postal_code text ,
8+ country text NOT NULL DEFAULT ' USA' ,
9+ is_default boolean DEFAULT false
10+ );
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 55CREATE TABLE IF NOT EXISTS users (
66 id integer PRIMARY KEY ,
77 email text NOT NULL CHECK (email LIKE ' %@%' ),
8- name text NOT NULL
8+ name text NOT NULL ,
9+ city text NOT NULL
910);
1011
1112COMMENT ON TABLE users IS ' User accounts' ;
You can’t perform that action at this time.
0 commit comments