Skip to content

Commit 3cbc88c

Browse files
committed
feat: add address. remove orders
1 parent d461a01 commit 3cbc88c

File tree

4 files changed

+50
-39
lines changed

4 files changed

+50
-39
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
$$;

multifile/tables/addresses.sql

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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+
);

multifile/tables/orders.sql

Lines changed: 0 additions & 38 deletions
This file was deleted.

multifile/tables/users.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
CREATE 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

1112
COMMENT ON TABLE users IS 'User accounts';

0 commit comments

Comments
 (0)