每个外键的多个 postgres 序列

Multiple postgres sequences for each foreign key

我使用的是 postgres 14,我的发票 table 看起来像这样:

name type
location_id uuid
invoice_id int
... ...

The location_id is a foreign key from the location table. location_id and invoice_id are a composite primary key.

我现在想实现的是每个位置的invoice id从1开始自动递增。
有没有办法用类似序列的东西来实现这个?

我使用插入前触发器解决了这个问题:

create or replace Function private.invoice_before_insert()
returns trigger
language plpgsql
as $$
  begin
    new.invoice_id = (
      select coalesce(max(invoice_id), 0) + 1
      from private.invoice
      where invoice_location_id = new.invoice_location_id
    );
    new.invoice_created_at = current_timestamp;

    return new;
  end;
$$;

create trigger invoice_before_insert
before insert
on private.invoice
for each row
execute function private.invoice_before_insert();

I'm not sure if this aprouch has any drawbacks tho. ¯_(ツ)_/¯