I am trying to update the table after deleting value in different table.
This is my simplified function query for this question:
create function updateoutfit(_id uuid, _title text DEFAULT NULL::text, _garments json)
returns TABLE(id uuid, title text, garments json)
language sql
as
$$
WITH del AS (DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = _id RETURNING outfit_id),
updateOutfit AS (
UPDATE outfit SET
title = _title
FROM del
WHERE outfit.id = _id
RETURNING id, title
),
saveOutfitGarment as (
insert into outfit_garment (position_x, outfit_id)
SELECT "positionX",
(SELECT updateOutfit.id from updateOutfit)
from json_to_recordset(_garments) as x("positionX" float,
outfit_id uuid) RETURNING json_build_object('positionX', position_x) as garments)
SELECT id,
title,
json_agg(garments)
from updateOutfit as outfit,
saveOutfitGarment as garments
group by id, title;
$$;
It works well if there is outfit_id returned from delete:
DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = _id RETURNING outfit_id
but fails if there is no row to delete. I tried something like this:
DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = '1234' RETURNING (SELECT '1234' as outfit_id );
but it still returns 0 rows.
Is there a way to fix that or better way to do it?
I am using Postgres 13.2