create domain dmn_code as text not null;
create domain dmn_money as numeric(22, 4);
create domain dmn_qty numeric(18, 6);
create domain dmn_rate as numeric(5, 2);
create domain dmn_clid bigint not null check ( value > 0 );
create domain dmn_usrid bigint not null check ( value > 0 );


create function iif(condition boolean, true_result anyelement, false_result anyelement) returns anyelement
    immutable
    language sql
as
$$
SELECT CASE
           WHEN condition THEN true_result
           ELSE false_result
           END
$$;

CREATE
    OR REPLACE FUNCTION zllog()
    RETURNS trigger
    LANGUAGE plpgsql
AS
$BODY$
BEGIN
    if
        (TG_OP = 'INSERT') then
        if (new.zlins_dttm is null) then
            new.zlins_dttm = current_timestamp;
        END if;
    end if;

    if
        (TG_OP = 'UPDATE') then
        if (new.zlupd_dttm is null) then
            new.zlupd_dttm = current_timestamp;
        end if;
    end if;

    RETURN NEW;
END;
$BODY$;


create table logdml
(
    id        bigint generated by default as identity
        primary key,
    opr       text,
    dttm      timestamp with time zone default CURRENT_TIMESTAMP not null,
    src_table text,
    src_id    bigint,
    usr_id    bigint,
    msg       text,
    old_val   jsonb,
    new_val   jsonb
);

create index ndx_logdml_dttm
    on logdml (dttm);

create index ndx_logdml_dttm_desc
    on logdml (dttm desc);

create index ndx_logdml_table
    on logdml (src_table, src_id);


create table sykv
(
    key text not null
        primary key,
    val text
);

create table symigrate
(
    id            bigint generated by default as identity
        primary key,
    tracking_name text,
    dttm          timestamp default CURRENT_TIMESTAMP,
    last_script   integer,
    log           text
);
