1 CREATE TABLE projects ( 2 id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, 3 team_id bigint NOT NULL REFERENCES teams (id) ON DELETE CASCADE, 4 name text NOT NULL, 5 created_at timestamptz NOT NULL DEFAULT now() 6 ); 7 CREATE INDEX projects_team_id_index ON projects (team_id); 8 9 CREATE TABLE labels ( 10 id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, 11 team_id bigint REFERENCES teams (id) ON DELETE CASCADE, 12 name text NOT NULL, 13 color char(7) NOT NULL DEFAULT '#888888', 14 UNIQUE (team_id, name) 15 ); 16 17 CREATE TABLE tasks ( 18 id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, 19 project_id bigint NOT NULL REFERENCES projects (id) ON DELETE CASCADE, 20 created_by bigint NOT NULL REFERENCES users (id) ON DELETE SET NULL, 21 title text NOT NULL, 22 done boolean NOT NULL DEFAULT false, 23 created_at timestamptz NOT NULL DEFAULT now() 24 ); 25 CREATE INDEX tasks_created_by_index ON tasks (created_by); 26 27 CREATE TABLE task_labels ( 28 task_id bigint NOT NULL REFERENCES tasks (id) ON DELETE CASCADE, 29 label_id bigint NOT NULL REFERENCES labels (id) ON DELETE CASCADE, 30 PRIMARY KEY (task_id, label_id) 31 ); 32 CREATE INDEX task_labels_label_id_index ON task_labels (label_id); 33 34 -- Project board: open tasks, oldest first 35 SELECT id, title, created_at 36 FROM tasks 37 WHERE project_id = $1 AND NOT done 38 ORDER BY created_at; 39 40 -- Team dashboard: one row per project with the title of its newest task 41 SELECT DISTINCT p.id, p.name, 42 last_value(t.title) OVER (PARTITION BY p.id ORDER BY t.created_at) AS newest_task 43 FROM projects p 44 LEFT JOIN tasks t ON t.project_id = p.id 45 WHERE p.team_id = $1;