Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fVKqa-00020y-2n for pgsql-general@arkaria.postgresql.org; Tue, 19 Jun 2018 17:55:16 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1fVGqt-00029g-GN for pgsql-general@arkaria.postgresql.org; Tue, 19 Jun 2018 13:39:19 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fVGqt-00029W-63 for pgsql-general@lists.postgresql.org; Tue, 19 Jun 2018 13:39:19 +0000 Received: from mail-wm0-x236.google.com ([2a00:1450:400c:c09::236]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1fVGql-0002yx-Ud for pgsql-general@postgresql.org; Tue, 19 Jun 2018 13:39:18 +0000 Received: by mail-wm0-x236.google.com with SMTP id v131-v6so531879wma.1 for ; Tue, 19 Jun 2018 06:39:11 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:content-transfer-encoding:mime-version:subject:message-id:date :to; bh=UeKmz8Imio4cmYitjPFC21nJ+s7s6buW7qN4YmX62eU=; b=gtCA6cMv8cb6K+YtkEvWQwkng0em5F6R1jlNJzrwme6Z2iX7kP/KR4tfR37u+jk0OM +nhmqRtcK1VXco357xwTYbqNr2FAwrP6qquTRHB6tmrQd79TYpuqge0HJ3m2d/TO3IFl VSNqkOT/srbJmpDxQamPCXQj88s5OMBE6RDzYFCXBEIr8CltWOX448uCHJc9wpzcbDoq dXpAm0Dh9Z6d2WiPiBG2Z2GdR9z2fkzVCqqx9VDK6ZjjrQj9UdQSjZvWtdgFCI9z1Bxe xfRODZgkqmjnz54+Zs9tVuO8XP/StxTLRZWK8Ta0+X1lwxn12TK6+FUyTOGu3z1Y7nD7 JsxA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:content-transfer-encoding:mime-version :subject:message-id:date:to; bh=UeKmz8Imio4cmYitjPFC21nJ+s7s6buW7qN4YmX62eU=; b=g8EoU4tfZ+Kb5H4rRHam9kEJIkKkWXcNjhSx+1T2T6Y+eBjiD/WvSfD9WVEa87fUWD lQycg+lzdXuHx8DtM8U0EqwtO6QMgf/pxsvlAuAXqp8FF4ViPJD7x5p3MOgbTso/ahTl dPdObIgEoVbmTt1sfD3Nn0zImH1VjC9nkFp0y/DFLKnd7W1Kk60sBDHH9UT8BVDUe0aE QkIkMCLm3d+dtWLHYHmJHPP1DCqhscxf2B/TBTnMIxaLW1oQJO5+tBos6TsYS92HB2BI fW0zMljF8yKLJRtZB/6IjZlB8R8MvMByjVpalAih56tq/IW9N+JPyZLfo+m5Zs7MsIED FEwg== X-Gm-Message-State: APt69E0PrIhMUtIUkyQkwMrqPqIgfjHwf6AN0LrAQW0dt6ixMz+U/Rt/ OlvM5SbkQIFmqF8w++69Jzf273fP X-Google-Smtp-Source: ADUXVKIcyai0RuOHyvNnC/5t/6XGnXH3VghwGuSG8mu3WbBh7x0ZQ2eOZ2SX2E5iiVYVuxVXK8Awiw== X-Received: by 2002:a50:f534:: with SMTP id t49-v6mr14778715edm.42.1529415550031; Tue, 19 Jun 2018 06:39:10 -0700 (PDT) Received: from hollewijn.internal (84-245-13-9.dsl.cambrium.nl. [84.245.13.9]) by smtp.gmail.com with ESMTPSA id d16-v6sm80701ede.21.2018.06.19.06.39.08 for (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Tue, 19 Jun 2018 06:39:09 -0700 (PDT) From: Alban Hertroys Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable Mime-Version: 1.0 (Mac OS X Mail 11.4 \(3445.8.2\)) Subject: Is postorder tree traversal possible with recursive CTE's? Message-Id: <5196CEBE-CF2E-48AF-A496-3CE2FE1B6FD2@gmail.com> Date: Tue, 19 Jun 2018 15:39:07 +0200 To: Postgres General X-Mailer: Apple Mail (2.3445.8.2) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Hi all, I'm struggling with a hierarchical query where I'm tasked to calculate = weights of items in an (exploded) Bill of Materials, based on the = weights of their components. Not all components are measured with a = weight, sometimes there are pieces, meters, areas, etc, and the = hierarchy is of varying levels of depth. It would help if I could track a sum() throughout the explosion that = would write back onto parent rows when the recursion returns: postorder = traversal. I created a simplified example about making pizza: CREATE TABLE ingredient ( name text NOT NULL ); CREATE TABLE recipe ( name text NOT NULL, ingredient text NOT NULL, quantity numeric(6,2) NOT NULL, unit text NOT NULL, step integer NOT NULL ); COPY ingredient (name) FROM stdin; tomato basil salt tomato sauce flour water yeast dough pizza bottom pizza \. COPY recipe (name, ingredient, quantity, unit, step) FROM stdin; tomato sauce tomato 100.00 g 1 dough flour 150.00 g 1 tomato sauce basil 10.00 g 2 pizza pizza bottom 1.00 pcs 2 tomato sauce salt 3.00 g 3 dough salt 1.00 pinch 3 pizza tomato sauce 1.00 pcs 1 pizza bottom dough 1.00 pcs 2 dough water 50.00 g 2 \. ALTER TABLE ONLY ingredient ADD CONSTRAINT ingredient_pkey PRIMARY KEY (name); ALTER TABLE ONLY recipe ADD CONSTRAINT recipe_pkey PRIMARY KEY (name, ingredient); ALTER TABLE ONLY recipe ADD CONSTRAINT recipe_ingredient_fkey FOREIGN KEY (ingredient) = REFERENCES ingredient(name); ALTER TABLE ONLY recipe ADD CONSTRAINT recipe_name_fkey FOREIGN KEY (name) REFERENCES = ingredient(name); A query listing the recipe for 'pizza' would be as follows: development=3D> with recursive pizza (name, step, ingredient, quantity, = unit, rel_qty, path, weight) as ( select name, step, ingredient, quantity, unit , quantity::numeric(10,2) , step::text , case when unit =3D 'g' then quantity::numeric(10,2) else = null end from recipe where name =3D 'pizza' union all select recipe.name, recipe.step, recipe.ingredient, = recipe.quantity, recipe.unit , (pizza.rel_qty * recipe.quantity)::numeric(10,2) , pizza.path || '.' || recipe.step , case when recipe.unit =3D 'g' then (pizza.rel_qty * = recipe.quantity)::numeric(10,2) else null end from pizza join recipe on (recipe.name =3D pizza.ingredient) ) select path, ingredient, quantity, rel_qty, unit, weight from pizza order by path; path | ingredient | quantity | rel_qty | unit | weight=20 -------+--------------+----------+---------+-------+-------- 1 | tomato sauce | 1.00 | 1.00 | pcs | =20 1.1 | tomato | 100.00 | 100.00 | g | 100.00 1.2 | basil | 10.00 | 10.00 | g | 10.00 1.3 | salt | 3.00 | 3.00 | g | 3.00 2 | pizza bottom | 1.00 | 1.00 | pcs | =20 2.2 | dough | 1.00 | 1.00 | pcs | =20 2.2.1 | flour | 150.00 | 150.00 | g | 150.00 2.2.2 | water | 50.00 | 50.00 | g | 50.00 2.2.3 | salt | 1.00 | 1.00 | pinch | =20 (9 rows) With these results, I somehow need to calculate that the weights of = 'tomato sauce', 'dough' and 'pizza bottom' are 113 g, 200 g and 200 g = respectively, bringing the total weight of 'pizza' to 313 g. My first thought was to traverse the result of this recursive CTE using = another one, but in the opposite direction. But since this tends to be = kept as a temporary materialized result set with no indices, that's not = performing great and it adds a fair amount of complexity to the query = too. Then I realised that if we somehow could track the sum() of 'weight' = throughout exploding these recipe items, by using a postorder tree = traversal, the desired result would be readily available to pick up when = the recursive CTE travels up through the hierarchy. In above example; When the CTE would reach '1.3 salt', it would write = the summed 'weight' value 113 back on the result for '1 tomato sauce' = and when it reached '2.2.2 salt' it would write back 200 to '2.2 dough' = and then 200 to '2 pizza bottom'. Is that possible? I've seen a couple of "solutions" on the internet that just summed up = the results of the CTE, but that won't do as it would not put the = correct weights onto intermediate levels of the tree as far as I can see = (in above, the weight of 'dough'). Regards, Alban Hertroys PS. Don't try to make pizza using this recipe, it probably won't = succeed. I forgot the yeast, for one thing, and quantities are probably = way off. Not to mention that there are probably more ingredients = missing=E2=80=A6 PS2. In my real case the ingredients have a base quantity and unit, = which makes adjusting to relative quantities actually viable. Those = aren't necessary to describe the problem though. -- If you can't see the forest for the trees, cut the trees and you'll find there is no forest.