my-tenant-id-in-column@0.1.0.sql 773 Bytes
-- Deploy 0814-tenants-and-users:tenants/set-tenant-id-in-column to pg
-- requires: tenants/my-tenant-id

BEGIN;

\ir ../../defaults.sql

create or replace function :"id_schema".my_tenant_id_in_column()
returns trigger
as $$
declare
  tenant_id text := my_tenant_id();
  column_name text := coalesce(tg_argv[0], 'tenant_id');
begin
  assert tg_nargs <= 1, 'my_tenant_id_in_column() accepts one argument, the column name.';

  if tg_nargs > 0 then
    column_name := tg_argv[0];
  end if;

  if tenant_id is not null then
    -- This is the same like NEW."updated_by_id" := tenant_id
    -- However, "updated_by_id" is replaced by the quoted value of column_name;
    new := new #= hstore(column_name, tenant_id);
  end if;

  return new;
end;
$$ language plpgsql;

COMMIT;