-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema_based_on_diagram.sql
55 lines (46 loc) · 1.83 KB
/
schema_based_on_diagram.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
CREATE DATABASE clinic;
CREATE TABLE patients (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
name VARCHAR NOT NULL,
date_of_birth DATE NOT NULL
);
CREATE TABLE medical_histories (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
admitted_at TIMESTAMP NOT NULL,
patient_id INT NOT NULL,
status VARCHAR NOT NULL,
CONSTRAINT fk_patients FOREIGN KEY (patient_id) REFERENCES patients(id)
);
CREATE TABLE invoices (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
total_amount DECIMAL NOT NULL,
generated_at TIMESTAMP NOT NULL,
payed_at TIMESTAMP NOT NULL,
medical_history_id INT NOT NULL,
CONSTRAINT fk_medical_histories FOREIGN KEY (medical_history_id) REFERENCES medical_histories(id)
);
CREATE TABLE invoice_items (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
unit_price DECIMAL NOT NULL,
quantity INT NOT NULL,
total_price DECIMAL NOT NULL,
invoice_id INT NOT NULL,
treatment_id INT NOT NULL,
CONSTRAINT fk_invoices FOREIGN KEY (invoice_id) REFERENCES invoices(id),
CONSTRAINT fk_treatments FOREIGN KEY (treatment_id) REFERENCES treatments(id)
);
CREATE TABLE treatments (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
type VARCHAR NOT NULL,
name VARCHAR NOT NULL
);
ALTER TABLE treatments ADD COLUMN medical_history_id INTEGER;
ALTER TABLE treatments ADD CONSTRAINT fk_medical_history FOREIGN KEY (medical_history_id) REFERENCES medical_histories(id);
CREATE TABLE treatment_histories (
treatment_id INT NOT NULL,
medical_history_id INT NOT NULL,
PRIMARY KEY (treatment_id, medical_history_id),
CONSTRAINT fk_treatments FOREIGN KEY (treatment_id) REFERENCES treatments(id),
CONSTRAINT fk_medical_histories FOREIGN KEY (medical_history_id) REFERENCES medical_histories(id)
);
ALTER TABLE treatments DROP COLUMN medical_history_id;