-- This is a cut-and-paste of the select_note_collection_from_title.sql
-- file with one line changed.  This is necessary because Larry
-- Ellison didn't trust programmers to understand recursion and
-- composition in 1983 (https://www.holistics.io/blog/quel-vs-sql/)
-- and that still makes me angry to this day.

SELECT
  id,
  parent_id,
  content,
  location,
  kind,
  creation_date,
  updated_date,
  lastview_date,
  deleted_date

FROM (

  WITH RECURSIVE zettelntree (
    id,
    parent_id,
    content,
    location,
    kind,
    creation_date,
    updated_date,
    lastview_date,
    deleted_date,
    cycle
  )

  AS (

    -- The seed query.  Finds the root node of any tree of zetteln,
	-- which by definition has a location of zero and a type of
	-- 'page'.
    SELECT
      zetteln.id,
      zetteln.id AS parent_id,
      zetteln.content,
	  zetteln.location,
      zetteln.kind,
      zetteln.creation_date,
      zetteln.updated_date,
      zetteln.lastview_date,
      zetteln.deleted_date,
      ','||zetteln.id||','  -- Cycle monitor
     FROM zetteln
     WHERE zetteln.kind = "page"
	   AND zetteln.location = 0
	   AND QUERYPARAMETER = ? -- The Query Parameter

    -- RECURSIVE expression
	--
	-- Here, for each recursion down the tree, we collect the child
	-- nodes for a given node, eliding any cycles.
	--
	-- TODO: Figure out what to do when a cycle DOES occur.
    UNION SELECT
      zetteln.id,
      zettelntree.id AS parent_id,
      zetteln.content,
      zettle_relationships.location,
      zetteln.kind,
      zetteln.creation_date,
      zetteln.updated_date,
      zetteln.lastview_date,
      zetteln.deleted_date,
      zettelntree.cycle||zetteln.id||','
        FROM zetteln
          INNER JOIN zettle_relationships 
            ON zetteln.id = zettle_relationships.zettle_id
          -- For a given ID in the level of zettelntree in *this* recursion,
          -- we want each note's branches one level down.
          INNER JOIN zettelntree 
            ON zettle_relationships.parent_id = zettelntree.id
          -- And we want to make sure there are no cycles.  There shouldn't
          -- be; we're supposed to prevent those.  But you never know.
          WHERE zettelntree.cycle NOT LIKE '%,'||zetteln.id||',%'
          ORDER BY zettle_relationships.location
    )

  SELECT * from zettelntree);

