Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion multifile/main.sql
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
\i functions/update_timestamp.sql

-- Include core tables (with their constraints, indexes, and policies)
\i tables/addresses.sql
\i tables/users.sql
\i tables/orders.sql

-- Include other functions (after tables that they reference)
\i functions/get_user_count.sql
Expand Down
38 changes: 38 additions & 0 deletions multifile/procedures/set_default_address.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
CREATE OR REPLACE PROCEDURE set_default_address(
p_user_id integer,
p_address_id integer
)
LANGUAGE plpgsql
AS $$
BEGIN
-- Check if the address exists and belongs to the user
IF NOT EXISTS (
SELECT 1 FROM addresses
WHERE id = p_address_id AND user_id = p_user_id
) THEN
RAISE EXCEPTION 'Address % does not exist or does not belong to user %',
p_address_id, p_user_id;
END IF;

-- Start transaction
BEGIN
-- Set all addresses for this user to non-default
UPDATE addresses
SET is_default = false
WHERE user_id = p_user_id;

-- Set the specified address as default
UPDATE addresses
SET is_default = true
WHERE id = p_address_id;

-- Log the change (optional - remove if you don't need logging)
RAISE NOTICE 'Default address set to % for user %', p_address_id, p_user_id;

EXCEPTION
WHEN OTHERS THEN
-- Rollback will happen automatically
RAISE EXCEPTION 'Failed to set default address: %', SQLERRM;
END;
END;
$$;
10 changes: 10 additions & 0 deletions multifile/tables/addresses.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS addresses (
id integer PRIMARY KEY,
user_id integer NOT NULL REFERENCES users(id),
street_address text NOT NULL,
city text NOT NULL,
state_province text,
postal_code text,
country text NOT NULL DEFAULT 'USA',
is_default boolean DEFAULT false
);
38 changes: 0 additions & 38 deletions multifile/tables/orders.sql

This file was deleted.

3 changes: 2 additions & 1 deletion multifile/tables/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
email text NOT NULL CHECK (email LIKE '%@%'),
name text NOT NULL
name text NOT NULL,
city text NOT NULL
);

COMMENT ON TABLE users IS 'User accounts';
Expand Down
Loading