You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
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.
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 recfa x =if x =0then 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.
These Recursive CTE tree traversals are quite common in my experience. Another common example is traversing organograms and employee management structures.
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.
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.
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).
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).
@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.
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 ONmanager.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.)
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.
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:
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.
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.
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.
Activity
aljazerzen commentedon Apr 25, 2022
That's an interesting use of a database. The
WITH-RECURSIVEcould maybe be expressed with our s-string, but in place of pipeline during a table definition:which could be packed into a function for easier use.
This would require #376 and a table flag to add the
RECURSIVEkeyword.max-sixty commentedon Apr 25, 2022
Possibly we could also have an s-string that doesn't bind to anything; it's just:
...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.
AntonioL commentedon Apr 25, 2022
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 recExample:
I guess it can be a
rec table. Since today you materializetablewith aCTEexpression. 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.
snth commentedon Jun 29, 2022
I picked up another example today from someone interested in PRQL that calls for recursive CTEs:
snth commentedon Jun 29, 2022
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
recursivekeyword. I've been using Postgresql for so long that I had forgotten that.snth commentedon Jun 29, 2022
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
reckeyword before thetablefunction that makes it arec tableas suggested above (with the dialect awareness that for MS SQL Server for examplerecbecomes a no-op)?I think we're currently also lacking
VALUESandUNION ALLbut that's kinda orthogonal to this and addressed elsewhere.max-sixty commentedon Jun 30, 2022
I think we could add a
table recursive:trueparameter to table. I admittedly haven't ever usedRECURSIVE, 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.snth commentedon Jun 30, 2022
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 untilUNIONlands).cfv1984 commentedon Dec 28, 2022
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
I use it to produce records of this shape:
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
aljazerzen commentedon Dec 30, 2022
Thank you for posting your use-case. This will be useful when designing recursive functions/CTEs/something else that will handle these cases.
[-]WITH-RECURSIVE based iteration[/-][+]WITH RECURSIVE based iteration[/+][-]WITH RECURSIVE based iteration[/-][+]`WITH RECURSIVE` based iteration[/+]23 remaining items
snth commentedon Mar 11, 2023
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.
aljazerzen commentedon Mar 11, 2023
Update: BigQuery also allows "other than first recursive CTEs"
aljazerzen commentedon May 16, 2023
@snth What's left to do here? Lambda functions? Nicer SQL output?
snth commentedon May 25, 2023
I'll get back to this again soon.
snth commentedon Jun 4, 2023
@aljazerzen , because
loopdefines 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 withjoin, which is the most common use case for real-life recursive CTEs, because our currentjoinspecification forces you to explicitly name the source relations.So for example the following simple example doesn't work in the playground.
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.
aljazerzen commentedon Jun 4, 2023
I do still have reservations toward
name=(pipeline).The upside is that in the meantime, the syntax for lamdba functions was added!
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".snth commentedon Jun 4, 2023
So you're saying the following doesn't work:
I assume there is nothing special about the name
prev_step, just that you need one reassignment?The following works on current main:
and produces
I'm not sure what's easier to explain, the use of
_frameorprev_step.I guess the benefit of
_frameis 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.)
aljazerzen commentedon Jun 4, 2023
Yes, exactly.
prev_stepis a variable that contains a relation, whileemployeeis a tuple within the relation.But yes,
_frameis 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 torelationor something.Playground is on 0.8, it probably does not support most of this.
saolof commentedon Aug 30, 2024
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
snth commentedon Aug 30, 2024
Hi @saolof ,
Thank you for the link to those examples. They are great!
This has been implemented as the
looptransform. See the docs here: https://prql-lang.org/book/reference/stdlib/transforms/loop.htmlI 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. 😀
saolof commentedon Aug 30, 2024
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.
snth commentedon Aug 30, 2024
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.