BEGIN;

SET LOCAL client_min_messages TO ERROR;

DO
$$
DECLARE
	const_colid CONSTANT text := ((random() * 10)::smallint % 10)::text;
	parent_tables_a text[];
	child_tables_b text[];
	child_tables_c text[];
        sqltext_nomerge text;
        sqltext text;
BEGIN

	-- PARENT Tables
	FOR i IN 1..10
	LOOP

		IF const_colid::smallint = i THEN		   
		   EXECUTE 'CREATE TABLE A' || i || '(acol' || i || ' integer, ' || quote_ident('col' || (-1 * const_colid::smallint)::text) || ' integer)';
		ELSE
		   EXECUTE 'CREATE TABLE A' || i || '(acol' || i || ' integer, col' || const_colid || ' integer)';
		END IF;

		parent_tables_a[i] := 'A' || i;
	
	END LOOP;

	FOR i IN 1..10
	LOOP

		IF const_colid::smallint = i THEN		   
		   EXECUTE 'CREATE TABLE B' || i || '(bcol' || i || ' integer, ' || quote_ident('col' || (-1 * const_colid::smallint)::text) || ' integer) INHERITS(' 
		   	   || array_to_string(parent_tables_a, ',') || ')';
		ELSE
		   EXECUTE 'CREATE TABLE B' || i || '(bcol' || i || ' integer, col' || const_colid || ' integer) INHERITS('
		   	   || array_to_string(parent_tables_a, ',') || ')';
		END IF;

		child_tables_b[i] := 'B' || i;	
	END LOOP;

	FOR i IN 1..10
	LOOP

		IF const_colid::smallint = i THEN		   
		   EXECUTE 'CREATE TABLE C' || i || '(ccol' || i || ' integer, ' || quote_ident('col' || (-1 * const_colid::smallint)::text) || ' integer) INHERITS(' 
		   	   || array_to_string(child_tables_b, ',') || ')';
		ELSE
		   EXECUTE 'CREATE TABLE C' || i || '(ccol' || i || ' integer, col' || const_colid || ' integer) INHERITS('
		   	   || array_to_string(child_tables_b, ',') || ')';
		END IF;

		child_tables_c[i] := 'C' || i;	
	END LOOP;

	FOR i IN 1..1000
	LOOP

		IF const_colid::smallint = i THEN		   
		   EXECUTE 'CREATE TABLE D' || i || '(dcol' || i || ' integer, ' || quote_ident('col' || (-1 * const_colid::smallint)::text) || ' integer) INHERITS(' 
		   	   || array_to_string(child_tables_c, ',') || ')';
		ELSE
		   EXECUTE 'CREATE TABLE D' || i || '(dcol' || i || ' integer, col' || const_colid || ' integer) INHERITS('
		   	   || array_to_string(child_tables_c, ',') || ')';
		END IF;

	END LOOP;

        for i IN 1..16384
        LOOP
                EXECUTE 'CREATE TABLE sss' || i || '(ssscol' || i || ' integer, col' || const_colid || ' integer)';
        END LOOP;

END;
$$ LANGUAGE plpgsql;

COMMIT;
