I develop a multi-tenant application in a single database. My table
DROP TABLE IF EXISTS account_default;
CREATE TABLE account_default
(
id smallint,
ref_type smallint not null,
ref_type_name character varying(256),
voucher_type smallint not null,
column_name character varying(64) not null,
column_caption character varying(128) not null,
filter_condition character varying(1024),
default_value character varying(32),
sort_order smallint,
created timestamp with time zone,
created_by character varying(64),
modified timestamp with time zone,
modified_by character varying(64),
tenant_id smallint,
PRIMARY KEY (id, tenant_id),
CONSTRAINT fk_tenant FOREIGN KEY (tenant_id) REFERENCES tenant (id)
);
CREATE INDEX account_default_idx ON account_default (id, tenant_id);
I need composite keys like these
(id, tenant_id)
(1, 1)
(2, 1)
(3, 1)
(1, 2)
(2, 2)
(3, 2)
(4, 2)
(1, 3)
(2, 3)
I tried something like this (base on insert value of tenant_id).
select (coalesce(max(id), 0) + 1) as next_val from account_default where tenant_id = 1;
CREATE TRIGGER account_default_id_trigger AFTER UPDATE ON account_default
FOR EACH ROW
...
When run insert script
INSERT INTO public.account_default(
ref_type, ref_type_name, voucher_type, column_name, column_caption, filter_condition, default_value, sort_order, created, created_by, modified, modified_by, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 5);
INSERT INTO public.account_default(
ref_type, ref_type_name, voucher_type, column_name, column_caption, filter_condition, default_value, sort_order, created, created_by, modified, modified_by, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 5);
INSERT INTO public.account_default(
ref_type, ref_type_name, voucher_type, column_name, column_caption, filter_condition, default_value, sort_order, created, created_by, modified, modified_by, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 5);
for example, tenant_id = 5, id auto insert based on trigger.
I hope you understand my needs and my idea. I need you revise it, make it work.