Considering table1 which have the follow fields: id1 uuid, id2 uuid, value text.
I'm creating a mecanism which I would like to check if after a insert in table1, already exists the same record but with ids inverted. Example:
CREATE OR REPLACE FUNCTION func_chk_new_pair()
RETURNS trigger AS $$
DECLARE
P_viewd_profile_id uuid;
found_uuids CURSOR FOR
SELECT id1 FROM table1 WHERE id1 = NEW.id2 and id2 = NEW.id1 and value = 'some_value';
current_uuid UUID;
BEGIN
OPEN found_uuids;
-- this insert to log and see if the values are correct works properly
insert into public.temp_log (log_text) values ('id1 : '
|| NEW.id1|| ' - id2: ' || NEW.id2);
LOOP
FETCH found_uuids INTO current_uuid;
EXIT WHEN NOT FOUND;
-- My problem is that my code never enter here
insert into table2 (id1, value) values (NEW.id1, NEW.value);
END LOOP;
CLOSE found_uuids;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Trigger Creation Code
CREATE TRIGGER chk_insert_new_pair
AFTER INSERT
ON "table1 "
FOR EACH ROW
EXECUTE PROCEDURE func_chk_new_pair();
The above piece of code I developed to be fired within a trigger. Unfortunately I have developed years in Oracle, so I'm strugling with this mindset. I have tried a lot of approaches... but here I'm.
How can I solve this?
I have tried a lot of approachesss: if EXISTS (select 1 FROM table 1 WHERE id1 = new.id1 and id2 = new.id2 and value = new.value)
Using pk constraint exception forcing insert; loop with inner select;