-- Second recursive case: Add a default unit conversion to the *start* of the conversion chain
SELECT
c.depth+1,
c.product_id,
s.from_qu_id,
c.to_qu_id,
s.factor*c.factor,
'/'||s.from_qu_id||c.path
FROMclosurec
JOINdefault_conversionss
ONs.to_qu_id=c.from_qu_id
WHERENOTEXISTS(SELECT1FROMconversion_factorsciWHEREci.product_id=c.product_idANDci.from_qu_id=s.from_qu_idANDci.to_qu_id=s.to_qu_id)-- Do this only, if there is no product_specific conversion between the units in s
-- Third recursive case: Add a default unit conversion to the *end* of the conversion chain
SELECT
c.depth+1,
c.product_id,
c.from_qu_id,
s.to_qu_id,
c.factor*s.factor,
c.path||s.to_qu_id||'/'
FROMclosurec
JOINdefault_conversionss
ONc.to_qu_id=s.from_qu_id
WHERENOTEXISTS(SELECT1FROMconversion_factorsciWHEREci.product_id=c.product_idANDci.from_qu_id=s.from_qu_idANDci.to_qu_id=s.to_qu_id)-- Do this only, if there is no product_specific conversion between the units in s
-- Fourth case: Add the default unit conversions that are reachable by a given product.
-- We cannot start with them directly, as we only want to add default conversions,
-- where at least one of the units is 'reachable' from the product's stock quantity unit
-- (and thus the conversion is sensible). Thus we add these cases here.
SELECT
1,
c.product_id,
s.from_qu_id,
s.to_qu_id,
s.factor,
'/'||s.from_qu_id||'/'||s.to_qu_id||'/'
FROMclosurec
JOINdefault_conversionss
ONc.pathLIKE('%/'||s.from_qu_id||'/'||s.to_qu_id||'/%')-- the conversion has been used as part of another path ...
WHERENOTEXISTS(SELECT1FROMconversion_factorsciWHEREci.product_id=c.product_idANDci.from_qu_id=s.from_qu_idANDci.to_qu_id=s.to_qu_id)-- ... and is itself new