-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.sql
96 lines (81 loc) · 2.31 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
CREATE TABLE "products" (
"id" SERIAL PRIMARY KEY,
"category_id" int NOT NULL,
"user_id" int,
"name" text NOT NULL,
"description" text NOT NULL,
"old_price" int,
"price" int NOT NULL,
"quantity" int DEFAULT 0,
"status" int DEFAULT 1,
"created_at" timestamp DEFAULT (now()),
"updated_at" timestamp DEFAULT (now())
);
CREATE TABLE "categories" (
"id" SERIAL PRIMARY KEY,
"name" text NOT NULL
);
CREATE TABLE "files" (
"id" SERIAL PRIMARY KEY,
"name" text,
"path" text NOT NULL,
"product_id" int
);
ALTER TABLE "products" ADD FOREIGN KEY ("category_id") REFERENCES "categories" ("id");
ALTER TABLE "files" ADD FOREIGN KEY ("product_id") REFERENCES "products" ("id");
CREATE TABLE "users" (
"id" SERIAL PRIMARY KEY,
"name" text UNIQUE NOT NULL,
"email" text NOT NULL,
"password" text NOT NULL,
"cpf_cnpj" text UNIQUE NOT NULL,
"cep" text,
"address" text,
"created_at" timestamp DEFAULT (now()),
"updated_at" timestamp DEFAULT (now())
);
-- Foreign Key
ALTER TABLE "products" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id")
-- create procedure
CREATE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW
END;
$$ LANGUAGE plpgsql;
-- connect pg simple table
CREATE TABLE "session" (
"sid" varchar NOT NULL COLLATE "default",
"sess" json NOT NULL,
"expire" timestamp(6) NOT NULL
)
WITH (OIDS=FALSE);
ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;
CREATE INDEX "IDX_session_expire" ON "session" ("expire");
-- token password recovery
ALTER TABLE "users" ADD COLUMN reset_token text;
ALTER TABLE "users" ADD COLUMN reset_token_expires text;
--auto updated_at products
CREATE TRIGGER set_timestamp
BEFORE UPDATE ON products
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();
--auto updated_at users
CREATE TRIGGER set_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();
-- cascade efect when delete users
ALTER TABLE "products"
DROP CONSTRAINT products_user_id_fkey
ADD CONSTRAINT products_user_id_fkey
FOREIGN KEY ("user_id")
REFERENCES "users" ("id")
ON DELETE CASCADE;
ALTER TABLE "files"
DROP CONSTRAINT files_product_id_fkey
ADD CONSTRAINT files_product_id_fkey
FOREIGN KEY ("product_id")
REFERENCES "products" ("id")
ON DELETE CASCADE