简体   繁体   中英

Postgres insert trigger fills id

I have a BEFORE trigger which should fill record's root ID which, of course, would point to rootmost entry. Ie:

id    | parent_id | root_id
-------------------------
a     | null      | a
a.1   | a         | a
a.1.1 | a.1       | a
b     | null      | b

If entry's parent_id is null, it would point to record itself.

Question is - inside BEFORE INSERT trigger, if parent_id is null, can I or should I fetch next sequence value, fill id and root_id in order to avoid filling root_id in AFTER trigger?

According to your own definition:

if entry's parent_id is null, it would point to record itself

then you have to do:

if new.parent_id is null then
    new.root_id = new.id ;
else
  WITH RECURSIVE p (parent_id, level) AS
  (
    -- Base case
    SELECT 
        parent_id, 0 as level
    FROM 
        t 
    WHERE 
        t.id = new.id
    UNION ALL
    SELECT
        t.parent_id, level + 1
    FROM
        t JOIN p ON t.id = p.parent_id
    WHERE
        t.parent_id IS NOT NULL
  )
  SELECT
    parent_id 
  INTO 
    new.root_id
  FROM
    p
  ORDER BY
    level DESC
  LIMIT
    1 ;
end if ;
RETURN new ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM