Partitioning and Sequence Increment

2019-08-28 06:03发布

问题:

I have table call it scdr_buz and have partitioned it on monthly basis, I have created trigger on insert which take care of upsert and create table if not present then upsert. I have sequence i_buz_scdr sequence with 1 increment but it's behavior while added rows in random not increment of 1. here is code of my trigger:

CREATE OR REPLACE FUNCTION tbl_scdr_buz_insert_trigger() RETURNS TRIGGER AS $$
BEGIN
    EXECUTE 'UPDATE scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' sc SET c_total_calls = sc.c_total_calls + ($1).c_total_calls WHERE (sc.c_prefix_id = ($1).c_prefix_id AND sc.v_prefix_id = ($1).v_prefix_id AND sc.start_time = ($1).start_time)'
    USING NEW;
    EXECUTE 'INSERT INTO scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||'(customer_name, ...) Select ($1).* 
 WHERE NOT EXISTS (SELECT * FROM scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' WHERE (...))'
    USING NEW;
    RETURN NULL;
    EXCEPTION
        WHEN undefined_table THEN
            EXECUTE 'CREATE TABLE IF NOT EXISTS scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (CHECK ( start_time >= '''|| to_char(NEW.start_time, 'YYYY-MM-01 00:00') ||''' AND start_time < '''|| to_char(NEW.start_time + INTERVAL '1 month', 'YYYY-MM-01 00:00') ||''' )) INHERITS (scdr_buz)';
            EXECUTE 'CREATE INDEX i_buz_scdr_'|| to_char(NEW.start_time, 'YYYY_MM') ||' ON scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (switch_name, customer_name, client_name_id, vendor_name_id, vendor_connection, c_prefix_id, v_prefix_id, start_time, c_billing_prefix, v_billing_prefix)';
            EXECUTE 'CREATE INDEX i_buz_scdr_starttime_'|| to_char(NEW.start_time, 'YYYY_MM') ||' ON scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (start_time)';

        EXECUTE 'UPDATE scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' sc SET c_total_calls = sc.c_total_calls + ($1).c_total_calls WHERE (sc.c_prefix_id = ($1).c_prefix_id AND sc.v_prefix_id = ($1).v_prefix_id AND sc.start_time = ($1).start_time)'
        USING NEW;
        EXECUTE 'INSERT INTO scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||'(customer_name, ...) Select ($1).* 
     WHERE NOT EXISTS (SELECT * FROM scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' WHERE (...))'
        USING NEW;
        RETURN NULL;
END
$$
LANGUAGE plpgsql;


CREATE TRIGGER fk_checkTrigger_buz_scdr
BEFORE INSERT ON scdr_buz
FOR EACH ROW
EXECUTE PROCEDURE tbl_scdr_buz_insert_trigger();

回答1:

It's probably incrementing by 1, but keep in mind that each insert to any partition increases by one. Also note that roll-backs do not roll back the sequence.