DROP FUNCTION IF EXISTS partition_by_hash(VARCHAR, INT);
CREATE FUNCTION partition_by_hash(table_name VARCHAR, num_partitions INT) RETURNS VOID AS $$
DECLARE
  n INT;
BEGIN
    FOR n IN 1..num_partitions LOOP
        EXECUTE '
            CREATE TABLE ' || table_name || '__part_' || n || '
            PARTITION OF ' || table_name || '
            FOR VALUES WITH (MODULUS ' || num_partitions || ', REMAINDER ' || n - 1  || ')';
    END LOOP;
END;
$$ LANGUAGE plpgsql;

CREATE TABLE parent (col0 INT NOT NULL, col1 double precision NOT NULL) PARTITION BY HASH(col0);
SELECT partition_by_hash('parent', 500);
INSERT INTO parent SELECT n, n+10 FROM generate_series(1, 10000000) n;
ANALYZE parent;
-- max out one of the children so that we get a lot of workers
ALTER TABLE parent__part_1 SET (parallel_workers=50);

-- enable all jit options to emulate a more expensive query
SET jit_above_cost = 0;
SET jit_inline_above_cost = 0;
SET jit_optimize_above_cost = 0;
SET jit_tuple_deforming = on;
SET jit_expressions = on;

-- Use quite some workers
SET max_parallel_workers_per_gather=50;

--ALTER SYSTEM SET max_parallel_workers=50;
--ALTER SYSTEM SET max_worker_processes=100;

\timing on
\echo =======================================
\echo without jit
\echo =======================================
SET jit=off;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;

\echo =======================================
\echo with jit
\echo =======================================
SET jit=on;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;
SELECT SUM(a.col1) / 7.0 as avg_yearly FROM parent a;

