-- This file and its contents are licensed under the Timescale License.
-- Please see the included NOTICE for copyright information and
-- LICENSE-TIMESCALE for a copy of the license.
SET timezone TO 'America/Los_Angeles';
\set TEST_BASE_NAME jit
SELECT format('include/%s_load.sql', :'TEST_BASE_NAME') as "TEST_LOAD_NAME",
       format('include/%s_query.sql', :'TEST_BASE_NAME') as "TEST_QUERY_NAME",
       format('include/%s_cleanup.sql', :'TEST_BASE_NAME') as "TEST_CLEANUP_NAME",
       format('%s/results/%s_results_optimized.out', :'TEST_OUTPUT_DIR', :'TEST_BASE_NAME') as "TEST_RESULTS_OPTIMIZED",
       format('%s/results/%s_results_unoptimized.out', :'TEST_OUTPUT_DIR', :'TEST_BASE_NAME') as "TEST_RESULTS_UNOPTIMIZED"
\gset
SELECT format('\! diff -u --label "Unoptimized results" --label "Optimized results" %s %s', :'TEST_RESULTS_UNOPTIMIZED', :'TEST_RESULTS_OPTIMIZED') as "DIFF_CMD"
\gset
-- enable all jit optimizations
SET jit=on;
SET jit_above_cost=0;
SET jit_inline_above_cost=0;
SET jit_optimize_above_cost=0;
SET jit_tuple_deforming=on;
SET enable_hashagg=off;
\ir :TEST_LOAD_NAME
-- This file and its contents are licensed under the Timescale License.
-- Please see the included NOTICE for copyright information and
-- LICENSE-TIMESCALE for a copy of the license.
CREATE TABLE jit_test(time timestamp NOT NULL, device int, temp float);
SELECT create_hypertable('jit_test', 'time');
psql:include/jit_load.sql:6: WARNING:  column type "timestamp without time zone" used for "time" does not follow best practices
   create_hypertable   
-----------------------
 (1,public,jit_test,t)

ALTER TABLE jit_test DROP COLUMN device;
CREATE TABLE jit_test_interval(id int NOT NULL, temp float);
SELECT create_hypertable('jit_test_interval', 'id', chunk_time_interval => 10);
       create_hypertable        
--------------------------------
 (2,public,jit_test_interval,t)

CREATE TABLE jit_test_contagg (
  observation_time  TIMESTAMPTZ       NOT NULL,
  device_id         TEXT              NOT NULL,
  metric            DOUBLE PRECISION  NOT NULL,
  PRIMARY KEY(observation_time, device_id)
);
SELECT table_name FROM create_hypertable('jit_test_contagg', 'observation_time');
    table_name    
------------------
 jit_test_contagg

CREATE MATERIALIZED VIEW jit_device_summary
WITH (timescaledb.continuous, timescaledb.materialized_only=false)
AS
SELECT
  time_bucket('1 hour', observation_time) as bucket,
  device_id,
  avg(metric) as metric_avg,
  max(metric)-min(metric) as metric_spread
FROM
  jit_test_contagg
GROUP BY bucket, device_id WITH NO DATA;
INSERT INTO jit_test_contagg
SELECT ts, 'device_1', (EXTRACT(EPOCH FROM ts)) from generate_series('2018-12-01 00:00'::timestamp, '2018-12-31 00:00'::timestamp, '30 minutes') ts;
INSERT INTO jit_test_contagg
SELECT ts, 'device_2', (EXTRACT(EPOCH FROM ts)) from generate_series('2018-12-01 00:00'::timestamp, '2018-12-31 00:00'::timestamp, '30 minutes') ts;
CALL refresh_continuous_aggregate('jit_device_summary', NULL, NULL);
\set PREFIX 'EXPLAIN (VERBOSE, TIMING OFF, BUFFERS OFF, COSTS OFF, SUMMARY OFF)'
\ir :TEST_QUERY_NAME
-- This file and its contents are licensed under the Timescale License.
-- Please see the included NOTICE for copyright information and
-- LICENSE-TIMESCALE for a copy of the license.
-- github issue #1262
--
:PREFIX
INSERT INTO jit_test VALUES('2017-01-20T09:00:01', 22.5) RETURNING *;
--- QUERY PLAN ---
 Custom Scan (ModifyHypertable)
   Output: jit_test."time", jit_test.temp
   ->  Insert on public.jit_test
         Output: jit_test."time", jit_test.temp
         ->  Result
               Output: 'Fri Jan 20 09:00:01 2017'::timestamp without time zone, NULL::integer, '22.5'::double precision

:PREFIX
INSERT INTO jit_test VALUES ('2017-01-20T09:00:02', 2),
                            ('2017-01-20T09:00:03', 5),
                            ('2017-01-20T09:00:04', 10);
--- QUERY PLAN ---
 Custom Scan (ModifyHypertable)
   ->  Insert on public.jit_test
         ->  Values Scan on "*VALUES*"
               Output: "*VALUES*".column1, NULL::integer, "*VALUES*".column2

:PREFIX
SELECT * FROM jit_test WHERE temp > 5 and temp <= 10 ORDER BY time;
--- QUERY PLAN ---
 Sort
   Output: "time", temp
   Sort Key: jit_test."time"
   ->  Result
         Output: "time", temp
         One-Time Filter: false

-- update with iteration over chunks
--
:PREFIX
INSERT INTO jit_test_interval (SELECT x, x / 2.3 FROM generate_series(0, 100) x) RETURNING *;
--- QUERY PLAN ---
 Custom Scan (ModifyHypertable)
   Output: jit_test_interval.id, jit_test_interval.temp
   ->  Insert on public.jit_test_interval
         Output: jit_test_interval.id, jit_test_interval.temp
         ->  Function Scan on pg_catalog.generate_series x
               Output: x.x, ((x.x)::numeric / 2.3)
               Function Call: generate_series(0, 100)

:PREFIX
SELECT * FROM jit_test_interval WHERE id >= 23 and id < 73 ORDER BY id;
--- QUERY PLAN ---
 Sort
   Output: id, temp
   Sort Key: jit_test_interval.id
   ->  Result
         Output: id, temp
         One-Time Filter: false

:PREFIX
UPDATE jit_test_interval SET temp = temp * 2.3 WHERE id >= 23 and id < 73;
--- QUERY PLAN ---
 Custom Scan (ModifyHypertable)
   ->  Update on public.jit_test_interval
         ->  Index Scan using jit_test_interval_id_idx on public.jit_test_interval
               Output: (temp * '2.3'::double precision), ctid
               Index Cond: ((jit_test_interval.id >= 23) AND (jit_test_interval.id < 73))

:PREFIX
SELECT * FROM jit_test_interval ORDER BY id;
--- QUERY PLAN ---
 Sort
   Output: id, temp
   Sort Key: jit_test_interval.id
   ->  Result
         Output: id, temp
         One-Time Filter: false

:PREFIX
SELECT time_bucket(10, id), avg(temp)
FROM jit_test_interval
GROUP BY 1
ORDER BY 1;
--- QUERY PLAN ---
 GroupAggregate
   Output: (time_bucket(10, id)), avg(temp)
   Group Key: (time_bucket(10, jit_test_interval.id))
   ->  Sort
         Output: (time_bucket(10, id)), temp
         Sort Key: (time_bucket(10, jit_test_interval.id))
         ->  Result
               Output: time_bucket(10, id), temp
               One-Time Filter: false

-- test continuous aggregates usage with forced jit (based on continuous_aggs_usage.sql)
--
:PREFIX
SELECT * FROM jit_device_summary WHERE metric_spread = 1800 ORDER BY bucket DESC, device_id LIMIT 10;
--- QUERY PLAN ---
 Limit
   Output: _hyper_4_6_chunk.bucket, _hyper_4_6_chunk.device_id, _hyper_4_6_chunk.metric_avg, _hyper_4_6_chunk.metric_spread
   ->  Sort
         Output: _hyper_4_6_chunk.bucket, _hyper_4_6_chunk.device_id, _hyper_4_6_chunk.metric_avg, _hyper_4_6_chunk.metric_spread
         Sort Key: _hyper_4_6_chunk.bucket DESC, _hyper_4_6_chunk.device_id
         ->  Append
               ->  Index Scan using _hyper_4_6_chunk__materialized_hypertable_4_bucket_idx on _timescaledb_internal._hyper_4_6_chunk
                     Output: _hyper_4_6_chunk.bucket, _hyper_4_6_chunk.device_id, _hyper_4_6_chunk.metric_avg, _hyper_4_6_chunk.metric_spread
                     Index Cond: (_hyper_4_6_chunk.bucket < 'Mon Dec 31 01:00:00 2018 PST'::timestamp with time zone)
                     Filter: (_hyper_4_6_chunk.metric_spread = '1800'::double precision)
               ->  GroupAggregate
                     Output: (time_bucket('@ 1 hour'::interval, _hyper_3_5_chunk.observation_time)), _hyper_3_5_chunk.device_id, avg(_hyper_3_5_chunk.metric), (max(_hyper_3_5_chunk.metric) - min(_hyper_3_5_chunk.metric))
                     Group Key: (time_bucket('@ 1 hour'::interval, _hyper_3_5_chunk.observation_time)), _hyper_3_5_chunk.device_id
                     Filter: ((max(_hyper_3_5_chunk.metric) - min(_hyper_3_5_chunk.metric)) = '1800'::double precision)
                     ->  Sort
                           Output: (time_bucket('@ 1 hour'::interval, _hyper_3_5_chunk.observation_time)), _hyper_3_5_chunk.device_id, _hyper_3_5_chunk.metric
                           Sort Key: (time_bucket('@ 1 hour'::interval, _hyper_3_5_chunk.observation_time)), _hyper_3_5_chunk.device_id
                           ->  Result
                                 Output: time_bucket('@ 1 hour'::interval, _hyper_3_5_chunk.observation_time), _hyper_3_5_chunk.device_id, _hyper_3_5_chunk.metric
                                 ->  Index Scan using _hyper_3_5_chunk_jit_test_contagg_observation_time_idx on _timescaledb_internal._hyper_3_5_chunk
                                       Output: _hyper_3_5_chunk.observation_time, _hyper_3_5_chunk.device_id, _hyper_3_5_chunk.metric
                                       Index Cond: (_hyper_3_5_chunk.observation_time >= 'Mon Dec 31 01:00:00 2018 PST'::timestamp with time zone)

-- generate the results into two different files
\set ECHO errors
--TEST END--
