Skip to content

WITH RECURSIVE based iteration #407

Open

Description

@AntonioL

At my shop we do lot of ELT where the T happens in database.
A typical use case is the following:

  • We get JSON files and we insert them inside the database, this is our E and L
  • We write materialized views/queries to process those JSON files, this is our T

This has the benefit that everything happens in database, and if there is an error in the business logic we only need to refresh the materialized views. We love materialized views. Our E are literally scripts which do a single request and a single INSERT query. And when we need to dump the database, the only content are the JSON files content + definition, so our dumps are very light.

In our context some times we need iteration, for example, we have a feed of events, a single JSON document, we need to process those events accumulating some state, to process the message T[n], we need the state derived from T[1],...,T[n-1].
In functional programming languages this is called a fold.

In postgres we use WITH-RECURSIVE queries, https://www.postgresql.org/docs/14/queries-with.html#QUERIES-WITH-RECURSIVE

WITH RECURSIVE t(n) AS (
    VALUES (1)
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;

I can see a world where I would write the body of materialized views in PRQL.

Activity

  1. aljazerzen commented on Apr 25, 2022

    @aljazerzen
    Member

    That's an interesting use of a database. The WITH-RECURSIVE could maybe be expressed with our s-string, but in place of pipeline during a table definition:

    table t = s"VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n < 100"
    

    which could be packed into a function for easier use.

    This would require #376 and a table flag to add the RECURSIVE keyword.

  2. added
    language-design
    on Apr 25, 2022
  3. max-sixty commented on Apr 25, 2022

    @max-sixty
    Member

    This would require #376 and a table flag to add the RECURSIVE keyword.

    Possibly we could also have an s-string that doesn't bind to anything; it's just:

    s"""
    WITH RECURSIVE t(n) AS (
        VALUES (1)
      UNION ALL
        SELECT n+1 FROM t WHERE n < 100
    )
    """

    ...and then there's always an escape hatch.


    I would probably put this feature into the "ensure compatible" bucket, rather than "support natively", but if there were lots of 👍 s on the issue as PRQL becomes more used, then we would work on supporting it in PRQL itself.

  4. AntonioL commented on Apr 25, 2022

    @AntonioL
    Author

    What about adding the concept of a table-valued function which can be marked as explicitly recursive?
    In FSharp if a function is recursive is defined with let rec

    Example:

    let rec fa x = if x = 0 then x else x + fa (x-1)

    I guess it can be a rec table. Since today you materialize table with a CTE expression. The only thing left would be to supply the starting items in the iteration.

    In the above example it is the first part of the query VALUES(1).

    But I want to stress that the above is not really "recursive", it is more iteration, wish it had a different term. However I like the escape hatch approach, this will allow us to defer any decisions on this matter.

  5. snth commented on Jun 29, 2022

    @snth
    Member

    I picked up another example today from someone interested in PRQL that calls for recursive CTEs:

    with recursive dim_balance_sheet(account_key, parent_account_key, account_name) as (
    values
        (1221,null,'Balance Sheet'),
        (1272,1221,'Assets'),
        (1300,1272,'Current Assets'),
        (1301,1300,'Cash & Cash Equivalent'),
        (1302,1301,'Bank Accounts'),
        (1307,1300,'Inventories'),
        (1222,1221,'Equity and Liabilities'),
        (1223,1222,'Capital and Reserves'),
        (1236,1222,'Current Liabilities'),
        (1266,1236,'Deferred Tax'),
        (2093,1236,'Deposits'),
        (1380,1236,'Short Term Loans'),
        (1232,1222,'Non-Current Liabilities'),
        (1662,1232,'Long-term Loans'),
        (1224,1662,'Shareholders')),
     bs as (
            select account_key,
                   account_name
              from dim_balance_sheet
             where parent_account_key is null
             union 
            select dim_balance_sheet.account_key,
                   bs.account_name || ' > ' || dim_balance_sheet.account_name
              from dim_balance_sheet
              join bs
                on bs.account_key = dim_balance_sheet.parent_account_key
           )
    select *
      from bs
     order by account_name
  6. snth commented on Jun 29, 2022

    @snth
    Member

    These Recursive CTE tree traversals are quite common in my experience. Another common example is traversing organograms and employee management structures.

    See this example for finding a Manager and Employee Hierarchy using the AdventureWorks database for example:
    SQL SERVER – Simple Example of Recursive CTE

    Interesting that MS SQL Server doesn't need the recursive keyword. I've been using Postgresql for so long that I had forgotten that.

  7. snth commented on Jun 29, 2022

    @snth
    Member

    Given the use cases for this, I think it would be good if we could support this.

    @max-sixty @aljazerzen Does the compiler need to be smart about this or couldn't we simply have an optional rec keyword before the table function that makes it a rec table as suggested above (with the dialect awareness that for MS SQL Server for example rec becomes a no-op)?

    I think we're currently also lacking VALUES and UNION ALL but that's kinda orthogonal to this and addressed elsewhere.

  8. max-sixty commented on Jun 30, 2022

    @max-sixty
    Member

    I think we could add a table recursive:true parameter to table. I admittedly haven't ever used RECURSIVE, but I can definitely understand the appeal.

    I probably wouldn't prioritize it that highly without more signal from people who want to use it (good point re not having UNION!), but would be happy to see it as a contribution.

  9. snth commented on Jun 30, 2022

    @snth
    Member

    Another example is in #716 in what appears to be a graph traversal algorithm.

    Another example I have seen in my $dayjob is for security classification trees, so you start with portfolio at the top and then walk down through asset classes. industries, sectors, subsectors, ... . For multi-asset class funds you might want variable depths of the classification tree in different asset classes. It's very similar to the balance sheet example above just with different labels.

    I think it's definitely lower priority than UNION (especially since it's dependent on it) but sounds like it shouldn't be that hard to do. I'll see if I can take a stab at it (since I have some time until UNION lands).

  10. cfv1984 commented on Dec 28, 2022

    @cfv1984

    Hi! Just chiming in with an example query I use to retrieve threaded topics on a side project of mine.

    I don't believe this is currently possible with prql, but would be amazing if it did.

    The following is sqlite, but I understand there are equivalents in most modern RDBMS

    -- This is the recursive Common Table Expression 
    WITH RECURSIVE 'POSTS_CTE' AS (
        SELECT 'p'.'id',
            'p'.'author_id',
            'p'.'parent_id',
            'p'.'content_id',
            (COALESCE(p.parent_id, "x") || ' > ' || p.id) AS path
        FROM 'posts' AS 'p'
        UNION
        SELECT 'p'.'id',
            'p'.'author_id',
            'p'.'parent_id',
            'p'.'content_id',
            (
                pr.path || ' > ' || p.parent_id || ' > ' || pr.id
            ) AS path
        FROM 'POSTS_CTE' AS 'pr'
            INNER JOIN 'posts' AS 'p' ON 'pr'.'id' = 'p'.'parent_id'
    )
    -- And this is a simple SELECT statement consuming it
    SELECT 'pct'.'id' AS 'post_id',
        'pu'.'id' AS 'post_author_id',
        'pct'.'parent_id' AS 'post_parent_id',
        'cu'.'id' AS 'content_owner_id',
        'c'.'id' AS 'content_id',
        'pct'.'path' AS 'post_path',
        'cu'.'username' AS 'content_owner_username',
        'pu'.'username' AS 'post_author_username',
        'c'.'type' AS 'content_type',
        'p'.'title' AS 'post_title',
        'c'.'content' AS 'content_content'
    FROM 'POSTS_CTE' AS 'pct'
        INNER JOIN 'content' AS 'c' on 'pct'.'content_id' = 'c'.'id'
        AND  'c'.'type' = 'topic'
        INNER JOIN 'users' AS 'cu' on 'c'.'owner_id' = 'cu'.'id'
        INNER JOIN 'users' AS 'pu' on 'pct'.'author_id' = 'pu'.'id'
        INNER JOIN 'posts' AS 'p' on 'pct'.'id' = 'p'.'id'
    WHERE post_path LIKE "x > %"
    ORDER BY post_parent_id, LENGTH('post_path') ASC
    

    I use it to produce records of this shape:

    post_id post_author_id post_parent_id content_owner_id content_id post_path content_owner_username post_author_username content_type post_title content_content
    4c5e55b2-59ae-42de-96a0-7ebc72827c7d b1caac6b-8761-411c-93c4-e62d91f61174 NULL b1caac6b-8761-411c-93c4-e62d91f61174 cdadc188-3bea-4799-a4a5-bf31b5ba63bd x > 4c5e55b2-59ae-42de-96a0-7ebc72827c7d moderator moderator topic moderator {"title":"moderator","personal":false}

    Which I then use as base structure for a forum type platform, through a simple sqlite view (CREATE VIEW AS that whole thing described above).

    As for the potential DX for such a feature, I'm not sure I'm in a position to choose? But I do find the S-string format proposed by max-sixty fairly interesting

  11. added this to the 0.5 milestone on Dec 30, 2022
  12. aljazerzen commented on Dec 30, 2022

    @aljazerzen
    Member

    Thank you for posting your use-case. This will be useful when designing recursive functions/CTEs/something else that will handle these cases.

  13. changed the title [-]WITH-RECURSIVE based iteration[/-] [+]WITH RECURSIVE based iteration[/+] on Dec 31, 2022
  14. changed the title [-]WITH RECURSIVE based iteration[/-] [+]`WITH RECURSIVE` based iteration[/+] on Dec 31, 2022
  15. 23 remaining items

  16. snth commented on Mar 11, 2023

    @snth
    Member

    The performance impact statement was a comment from Mark, one of the DuckDB core devs. It's in the DuckDB discord discussion I linked to above.

  17. aljazerzen commented on Mar 11, 2023

    @aljazerzen
    Member

    Update: BigQuery also allows "other than first recursive CTEs"

  18. aljazerzen commented on May 16, 2023

    @aljazerzen
    Member

    @snth What's left to do here? Lambda functions? Nicer SQL output?

  19. snth commented on May 25, 2023

    @snth
    Member

    I'll get back to this again soon.

  20. snth commented on Jun 4, 2023

    @snth
    Member

    @aljazerzen , because loop defines a new, recursive relation, we need a way to reference that relation because of the recursive part. For the simple examples that are in our current documentation it works without that because unqualified columns reference the current frame. However this breaks down with join, which is the most common use case for real-life recursive CTEs, because our current join specification forces you to explicitly name the source relations.

    So for example the following simple example doesn't work in the playground.

    from employees
    filter last_name=="Mitchell"
    loop (
      join manager=employees [manager.employee_id==reports_to]
      select manager.*
    )

    Given compiler code changes and refactors since we last discuss this, how do you now feel about the loop name=(pipeline) proposal? Do your concerns from #407 (comment) still hold?

    It would be great if we could get either this or the lambda syntax into 0.9 still then I can write up some examples with the release announcement.

  21. aljazerzen commented on Jun 4, 2023

    @aljazerzen
    Member

    I do still have reservations toward name=(pipeline).

    The upside is that in the meantime, the syntax for lamdba functions was added!

    from employees
    filter last_name=="Mitchell"
    loop (prev_step -> (
      employee = prev_step
      join manager=employees (employee.reports_to == manager.employee_id)
      select manager.*
    ))

    I know you are going to ask "why the employee = prev_step" and my answer is "it's a consequence of current pipeline name inference rules".

  22. snth commented on Jun 4, 2023

    @snth
    Member

    So you're saying the following doesn't work:

    from employees
    filter last_name=="Mitchell"
    loop (employee -> (
      employee
      join manager=employees (employee.reports_to == manager.employee_id)
      select manager.*
    ))

    I assume there is nothing special about the name prev_step, just that you need one reassignment?


    The following works on current main:

    from employees
    filter last_name=="Mitchell"
    loop (
      join manager=employees (manager.employee_id==_frame.reports_to)
      select manager.*
    )

    and produces

    WITH table_2 AS (
      WITH RECURSIVE _loop AS (
        SELECT
          *
        FROM
          employees
        WHERE
          last_name = 'Mitchell'
        UNION
        ALL
        SELECT
          manager.*
        FROM
          _loop AS table_0
          JOIN employees AS manager ON manager.employee_id = table_0.reports_to
      )
      SELECT
        *
      FROM
        _loop
    )
    SELECT
      *
    FROM
      table_2 AS table_1
    
    -- Generated by PRQL compiler version:0.8.1 (https://prql-lang.org)

    I'm not sure what's easier to explain, the use of _frame or prev_step.

    I guess the benefit of _frame is that you don't have to do any more work and I can just add some more documentation to the release.


    (Incidentally, I keep having issues with this in the playground. I'll try again and open an issue if need be.)

  23. aljazerzen commented on Jun 4, 2023

    @aljazerzen
    Member

    So you're saying the following doesn't work:

    Yes, exactly.

    I assume there is nothing special about the name prev_step, just that you need one reassignment?

    prev_step is a variable that contains a relation, while employee is a tuple within the relation.

    But yes, _frame is probably easier to explain.

    I wouldn't want to document that as a part of the language - the _ screams "internal" or "unused". We could at least change the name to relation or something.


    Playground is on 0.8, it probably does not support most of this.

  24. modified the milestones: 0.9, 1.0 on Jun 14, 2023
  25. saolof commented on Aug 30, 2024

    @saolof

    Just chiming in with the most urgently necessary usecase of this. The sqlite docs has a mandelbrot fractal display and a sudoku solver as two of the primary examples of CTE usage:

    https://www.sqlite.org/draft/lang_with.html#outlandish_recursive_query_examples

    Of course, having both window functions and recursive CTEs is what makes basic SQL turing complete, since you can implement a cyclic tag system with that. See slide 47 here: https://cdn.oreillystatic.com/en/assets/1/event/27/High%20Performance%20SQL%20with%20PostgreSQL%20Presentation.pdf

  26. snth commented on Aug 30, 2024

    @snth
    Member

    Hi @saolof ,

    Thank you for the link to those examples. They are great!

    This has been implemented as the loop transform. See the docs here: https://prql-lang.org/book/reference/stdlib/transforms/loop.html

    I also have some example demos in this Colab notebook: https://colab.research.google.com/drive/146ohCI_WlnOKpQQ6sPMWu4uKGqZvwaIZ#scrollTo=loctSkQYFA_w

    Unfortunately there's a regression bug in latest version which we'll resolve. In the meantime you can pin to a previous version like I do in that notebook.

    Edit: For an equally outlandish query, you can also look at my Calculate the digits of Pi with DuckDB and PRQL blogpost. 😀

  27. saolof commented on Aug 30, 2024

    @saolof

    Ah neat. Does loop as it exists now support dynamic programming and graph traversals?

    A common usecase is when you have a table, and want to join it with an ancestor relation, but only have a parent relation in the DB because the ancestor relation would be prohibitively large. In those cases the dynamic aspect (being able to use union instead of union all) can be rather important to avoid double-counting paths.

  28. snth commented on Aug 30, 2024

    @snth
    Member

    Yes, the paragraph linked here https://colab.research.google.com/drive/146ohCI_WlnOKpQQ6sPMWu4uKGqZvwaIZ#scrollTo=loctSkQYFA_w goes through exactly that, variable depth tree traversal.

    Good point about UNION vs UNION ALL. It uses UNION ALL by default. I can't recall offhand whether there's a parameter to ask for UNION instead. We should add that if not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementlanguage-designmajor-feature

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions