-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.sql
70 lines (60 loc) · 1.66 KB
/
db.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
CREATE TABLE owners (
id SERIAL PRIMARY KEY,
first_name VARCHAR(175) NOT NULL,
last_name VARCHAR(175) NOT NULL
);
CREATE TABLE hotels_locations (
id SERIAL PRIMARY KEY,
address VARCHAR(75) NOT NULL,
city VARCHAR(75) NOT NULL,
area VARCHAR(75)
);
CREATE TYPE hotels_types AS ENUM (
'Hotel',
'Hostel',
'Bed&Breakfast',
'Apartments'
);
CREATE TABLE hotels (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE,
location INTEGER NOT NULL REFERENCES hotels_locations(id) ON DELETE CASCADE,
owner_id INTEGER NOT NULL REFERENCES owners(id) ON DELETE CASCADE,
category hotels_types NOT NULL,
price SMALLINT NOT NULL,
avg_rating DECIMAL(2,1),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE reviews (
id SERIAL PRIMARY KEY,
hotel_id INTEGER NOT NULL REFERENCES hotels(id) ON DELETE CASCADE,
rating SMALLINT NOT NULL CHECK (rating >= 0 AND rating <= 5),
body TEXT
);
CREATE OR REPLACE FUNCTION trigger_update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
NEW.updated_at = now();
RETURN NEW;
ELSE
RETURN OLD;
END IF;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_modified_column
BEFORE UPDATE ON hotels
FOR EACH ROW
EXECUTE PROCEDURE trigger_update_modified_column();
CREATE OR REPLACE FUNCTION calculate_avg_rating()
RETURNS TRIGGER AS $$
BEGIN
UPDATE hotels SET avg_rating = (SELECT AVG(rating) FROM reviews WHERE hotel_id=NEW.hotel_id);
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER calculcate_avg_rating
AFTER INSERT OR DELETE OR UPDATE OF rating ON reviews
FOR EACH ROW
EXECUTE PROCEDURE calculate_avg_rating();