Re: exclusion constraint question

From: Greg Sabino Mullane <htamfids(at)gmail(dot)com>
To: Achilleas Mantzios - cloud <a(dot)mantzios(at)cloud(dot)gatewaynet(dot)com>
Cc: "Rhys A(dot)D(dot) Stewart" <rhys(dot)stewart(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: exclusion constraint question
Date: 2025-03-11 14:29:05
Message-ID: CAKAnmmLpoCh=rRLA3k9Qypk34uH5appTa-RULq26-KS3kozGvw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, Mar 11, 2025 at 3:06 AM Achilleas Mantzios asked:

> is it still harder than the trigger ?
>
I think the trigger wins: no extension needed, arguably better error
output, easier to understand at a glance, and can quickly change the
business logic by adjusting the function. Pretty short too. Don't know what
the op tried, but here's a version I came up with. Note that this trigger
allows you to remove all the UNIQUE column specifiers and the CHECK clause
from the original table.

create table mugs (
mug_id bigint PRIMARY KEY,
shelf bigint -- not needed for the trigger to work, but nice to have
);

create or replace function add_a_mug() returns trigger
language plpgsql as $$
begin
if tg_op in ('UPDATE','DELETE' then
delete from mugs where mug_id in (old.l_mug_id, old.c_mug_id,
old.r_mug_id);
end if;
if tg_op in ('UPDATE','INSERT') then
with mugs as (select
unnest(array[new.l_mug_id,new.c_mug_id,new.r_mug_id]) as mug)
insert into mugs(mug_id, shelf) select mug, new.shelf_id
from mugs where mug is not null;
end if;
return null;
end
$$;

create trigger take_one_down_pass_it_around after insert or update or delete
on shelves for each row execute function add_a_mug();

Cheers,
Greg

--
Crunchy Data - https://www.crunchydata.com
Enterprise Postgres Software Products & Tech Support

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Greg Sabino Mullane 2025-03-11 14:33:22 Re: Duplicate Key Values
Previous Message mark bradley 2025-03-11 14:28:55 Re: Duplicate Key Values