-- Create tables

CREATE OR REPLACE FUNCTION create_test_table(table_num INTEGER, num_rows INTEGER DEFAULT 1000)
RETURNS void AS $$
BEGIN
    EXECUTE format('
        CREATE TABLE t_tab_%s (
            id INTEGER PRIMARY KEY,
            c1 INTEGER,
            c2 INTEGER,
            c3 INTEGER
        )', table_num);
    
    EXECUTE format('
        INSERT INTO t_tab_%s (id, c1, c2, c3)
        SELECT 
            gs as id,
            (random() * 1000)::int as c1,
            (random() * 10)::int as c2,
            (random() * 100)::int as c3
        FROM generate_series(1, %s) gs', table_num, num_rows);
    
    EXECUTE format('CREATE INDEX idx_t_tab_%s_c3 ON t_tab_%s(c3)', table_num, table_num);
    EXECUTE format('CREATE INDEX idx_t_tab_%s_c2 ON t_tab_%s(c2)', table_num, table_num);
    EXECUTE format('CREATE INDEX idx_t_tab_%s_c2_c3 ON t_tab_%s(c2, c3)', table_num, table_num);
END $$ LANGUAGE plpgsql;

DO $$
DECLARE
    i INTEGER;

BEGIN
    FOR i IN 1..1000 LOOP
        PERFORM create_test_table(i, 1000);
    END LOOP;
END $$;

ANALYZE;


-- Generate some queries to fill in pg_stat_statements statistics
SELECT 'SELECT max(c1) FROM t_tab_' || (random() * 1000 + 1)::int || ' WHERE c3 = ' || (random() * 100)::int
FROM generate_series(1, 1000)
\gexec
