-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.sql
98 lines (82 loc) · 2.47 KB
/
database.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
CREATE TYPE role AS ENUM ('buyer', 'merchant', 'admin');
CREATE TABLE users(
user_id SERIAL PRIMARY KEY,
password VARCHAR(200) NOT NULL,
first_name VARCHAR(15) DEFAULT '',
last_name VARCHAR(15) DEFAULT '',
email VARCHAR(30) DEFAULT '',
address VARCHAR(200) DEFAULT '',
user_role role DEFAULT 'buyer'
);
CREATE TABLE categories (
category_id SERIAL PRIMARY KEY,
category_name VARCHAR(30) DEFAULT ''
);
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(80) DEFAULT '',
description VARCHAR(5000) DEFAULT '',
price DECIMAL(10, 2) DEFAULT 0.00,
stockQty INT DEFAULT 0,
category_id INT REFERENCES categories(category_id),
created_at DATE NOT NULL,
cover VARCHAR(200) DEFAULT 'images/default.png'
);
CREATE TABLE carts (
cart_id SERIAL UNIQUE PRIMARY KEY,
user_id INT REFERENCES users(user_id)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
created_date DATE NOT NULL,
user_id INT REFERENCES users(user_id)
);
CREATE TABLE orderDetails (
order_id INT REFERENCES orders(order_id),
delivery_address VARCHAR(200) NOT NULL,
billing_address VARCHAR(200) NOT NULL
)
CREATE TABLE payments (
payment_id SERIAL PRIMARY KEY,
total DECIMAL(10,2) DEFAULT 0.0,
user_id INT REFERENCES users(user_id),
order_id INT REFERENCES orders(order_id)
);
CREATE TABLE lineItems (
cart_id INT REFERENCES carts(cart_id),
product_id INT REFERENCES products(product_id),
quantity INT NOT NULL DEFAULT 0
);
CREATE FUNCTION trigger_function()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
BEGIN
INSERT INTO carts (user_id) VALUES (new.user_id);
END;
$$
CREATE TRIGGER cartForUser
AFTER INSERT
ON users
FOR EACH ROW
EXECUTE PROCEDURE trigger_function();
CREATE FUNCTION lineItemQuantityCheck()
RETURNS TRIGGER
LANGAGE PLPGSQL
AS $$
DECLARE stock INT;
BEGIN
SELECT stockQty INTO stock from products WHERE product_id = NEW.product_id);
IF NEW.quantity > stock THEN
RAISE EXCEPTION 'Not enough in stock';
END IF;
END
$$
CREATE TRIGGER lineItemQuantityCheck
BEFORE INSERT OR UPDATE
ON lineItems
FOR EACH ROW
EXECUTE PROCEDURE lineItemQuantityCheck();
CREATE OR REPLACE FUNCTION getProducts() RETURNS table(product_name VARCHAR, description varchar, price DECIMAL, stockQty INT, category_name varchar) AS $$
SELECT products.product_name, products.description, products.price, products.stockQty, categories.category_name FROM products INNER JOIN categories ON categories.category_id = products.category_id;
$$ LANGUAGE sql;