T
T
Taras Labiak2016-01-19 07:18:22
PostgreSQL
Taras Labiak, 2016-01-19 07:18:22

How to limit recursive view in PostgreSQL?

Is it possible to somehow limit the recursive view in PostgreSQL in case it becomes infinite?
View code https://gist.github.com/kissarat/5d45c69a068192c17d36
Infinity occurs when the article hierarchy becomes cyclic when, for example, parent_id article(2) refers to id article(1), in which parent_id refers to id article(1)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Taras Labiak, 2016-01-19
@kissarat

In this case, the number of levels is limited (nesting) WHERE r.category_level < 8

CREATE OR REPLACE VIEW category AS
  WITH RECURSIVE r(id, title, lang, category_level, category_id, parent_id) AS (
    SELECT
      a.id,
      a.title,
      a.lang,
      0    AS category_level,
      a.id AS category_id,
      a.parent_id
    FROM article a
    UNION
    SELECT
      a.id,
      a.title,
      a.lang,
      r.category_level + 1 AS category_level,
      r.category_id,
      a.parent_id
    FROM article a
      JOIN r ON r.parent_id = a.id AND r.lang = a.lang
    WHERE r.category_level < 8
  )
  SELECT
    r.id,
    r.title,
    r.lang,
    r.parent_id,
    first_value(r.id) OVER (PARTITION BY category_id ORDER BY r.id) AS root_id,
    row_number() OVER (PARTITION BY category_id ORDER BY r.id) - 1 AS "level",
    r.category_level,
    r.category_id
  FROM r
    WHERE category_level > 0
  ORDER BY category_id DESC;

A
Andrey Mokhov, 2016-01-19
@mokhovcom

see the documentation , there is an example where loops are cut off

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question