Search code examples
pythonsqlitepeewee

Can Peewee+sqlite make a recursive CTE query?


Is it possible with Peewee to execute the following recursive CTE query?

The code creates a self-referencing table representing a tree structure, and the query finds all the parents of one element. (I am a SQL beginner, any advice for improvement is welcome).

CREATE TABLE Parts ( 
    Id       INTEGER PRIMARY KEY,
    Desc     TEXT,
    ParentId INTEGER
);

INSERT INTO Parts VALUES (1,  'CEO',                  NULL);
INSERT INTO Parts VALUES (2,  'VIP Sales',            1);
INSERT INTO Parts VALUES (3,  'VIP Operations',       1);
INSERT INTO Parts VALUES (4,  'Sales Manager Europe', 2);
INSERT INTO Parts VALUES (5,  'Sales Manager USA',    2);
INSERT INTO Parts VALUES (6,  'Sales Rep Europe 1',   4);
INSERT INTO Parts VALUES (7,  'Sales Rep Europe 2',   4);
INSERT INTO Parts VALUES (8,  'Sales Rep USA 1',      5);
INSERT INTO Parts VALUES (9,  'Sales Rep USA 2',      5);

WITH RECURSIVE Cte (
    Level,
    Id,
    Desc,
    ParentId,
    ParentDesc
  ) AS (
    SELECT 0,
           Child.Id,
           Child.Desc,
           Parent.Id,
           Parent.Desc
      FROM Parts AS Child
           JOIN Parts AS Parent ON Child.ParentId = Parent.Id
     WHERE Child.Desc = 'Sales Rep USA 1'

     UNION ALL

    SELECT Cte.Level + 1,
           Child.Id,
           Child.Desc,
           Parent.Id,
           Parent.Desc
      FROM Parts as Child, Cte
           JOIN Parts AS Parent ON Child.ParentId = Parent.Id
     WHERE Child.Id = Cte.ParentId
)
SELECT * FROM Cte;

Solution

  • Peewee doesn't have any built-in facilities for constructing recursive queries. While it would be possible to hack it together using some of the SQL building-block classes, you're honestly probably better off just passing the whole SQL query into peewee's raw() method:

    http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.raw