Created
July 6, 2023 13:20
-
-
Save fabriziomello/ecac56dfa96f1fcc4dc9dc487d4991e7 to your computer and use it in GitHub Desktop.
Function to create calendar-based chunks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE PROCEDURE custom_create_chunk(hypertable REGCLASS, trunc_field TEXT DEFAULT 'month') AS | |
$$ | |
DECLARE | |
r RECORD; | |
range_start BIGINT; | |
range_end BIGINT; | |
slices JSONB; | |
BEGIN | |
SELECT | |
d.column_name, ds.range_end | |
INTO | |
r | |
FROM | |
_timescaledb_catalog.hypertable h | |
JOIN _timescaledb_catalog.dimension d ON d.hypertable_id = h.id | |
LEFT JOIN _timescaledb_catalog.dimension_slice ds ON ds.dimension_id = d.id | |
WHERE | |
d.column_type = 'timestamp with time zone'::regtype | |
AND format('%I.%I', h.schema_name, h.table_name)::regclass = hypertable | |
ORDER BY | |
ds.range_start DESC, ds.range_end DESC | |
LIMIT 1; | |
IF NOT FOUND THEN | |
RETURN; | |
END IF; | |
RAISE DEBUG 'r: %', r; | |
IF r.range_end IS NULL THEN | |
range_start := _timescaledb_internal.time_to_internal(date_trunc(trunc_field, now())); | |
ELSE | |
range_start := r.range_end; | |
END IF; | |
RAISE INFO 'range_start: %', range_start; | |
range_end := | |
_timescaledb_internal.time_to_internal( | |
_timescaledb_internal.to_timestamp(range_start) + | |
format('1 %s', trunc_field)::interval | |
); | |
RAISE DEBUG 'range_end: %', range_end; | |
slices := jsonb_build_object(r.column_name, array[range_start, range_end]); | |
RAISE DEBUG 'slices: %', slices; | |
PERFORM _timescaledb_internal.create_chunk(hypertable, slices); | |
RETURN; | |
END; | |
$$ | |
LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment