-- Product hierarchy: a product project is a family, a product placed on the -- market, or a component of one (a machine's robot arm, PLC, edge server or -- Windows application). Components nest (robot arm -> gripper). Topics stay -- flat. A document's role follows the level of the project it is linked to. -- The rules that need the whole tree (allowed parents, depth, no cycles) are -- checked by the API; the database keeps the parent within the tenant and -- refuses to delete a project that still has children. ALTER TABLE projects ADD COLUMN level TEXT, ADD COLUMN parent_id UUID; UPDATE projects SET level = 'product' WHERE kind = 'product'; ALTER TABLE projects ADD CONSTRAINT projects_level CHECK ( (kind = 'product' AND level IN ('family', 'product', 'component')) OR (kind = 'topic' AND level IS NULL AND parent_id IS NULL)), ADD CONSTRAINT projects_not_own_parent CHECK (parent_id IS NULL OR parent_id <> id), ADD CONSTRAINT projects_tenant_id_key UNIQUE (tenant_id, id), ADD CONSTRAINT projects_parent FOREIGN KEY (tenant_id, parent_id) REFERENCES projects (tenant_id, id) ON DELETE RESTRICT; CREATE INDEX projects_parent_idx ON projects (parent_id) WHERE parent_id IS NOT NULL;