\pset linestyle old-ascii
\t on

select 'create sequence seq1;';
select 'create table maintb(id int,name char(10));';

select 'create table childtb_' || id ||' (CHECK ( id BETWEEN ' || (id-1)*(:total/:pnum)+1 ||' AND ' || (id)*(:total/:pnum) || ')) inherits(maintb);' from (select generate_series(1,:pnum)) ids(id);

select 'CREATE INDEX childtb_idx_'|| id || ' ON childtb_'|| id ||' (id);' from (select generate_series(1,:pnum)) ids(id);

select 'CREATE OR REPLACE FUNCTION maintb_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN';

select CASE WHEN id>1 THEN ' ELS' ELSE ' ' END || 'IF( NEW.id BETWEEN ' || (id-1)*(:total/:pnum)+1 ||' AND ' || (id)*(:total/:pnum) || ' ) THEN
        INSERT INTO childtb_'|| id || ' VALUES (NEW.*); ' from (select generate_series(1,:pnum)) ids(id);

select' ELSE
        RAISE EXCEPTION ''id out of range!'';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;';

select 'CREATE TRIGGER insert_maintb_trigger
    BEFORE INSERT ON maintb
    FOR EACH ROW EXECUTE PROCEDURE maintb_insert_trigger();';