diff --git a/etc/db/upgrades/upgrade11-v0.2.1-tstamp-functions.sql b/etc/db/upgrades/upgrade11-v0.2.1-tstamp-functions.sql index 28c14e2..7938a8e 100644 --- a/etc/db/upgrades/upgrade11-v0.2.1-tstamp-functions.sql +++ b/etc/db/upgrades/upgrade11-v0.2.1-tstamp-functions.sql @@ -73,6 +73,41 @@ BEGIN IS 'Get the timestamp of an existing shotpoint.'; + CREATE OR REPLACE FUNCTION tstamp_interpolate(s numeric, p numeric) RETURNS timestamptz + AS $inner$ + DECLARE + ts0 timestamptz; + ts1 timestamptz; + pt0 numeric; + pt1 numeric; + BEGIN + + SELECT tstamp, point + INTO ts0, pt0 + FROM raw_shots + WHERE sequence = s AND point < p + ORDER BY point DESC LIMIT 1; + + + SELECT tstamp, point + INTO ts1, pt1 + FROM raw_shots + WHERE sequence = s AND point > p + ORDER BY point ASC LIMIT 1; + + RETURN (ts1-ts0)/abs(pt1-pt0)*abs(p-pt0)+ts0; + + END; + $inner$ LANGUAGE PLPGSQL; + + COMMENT ON FUNCTION tstamp_interpolate(numeric, numeric) + IS 'Interpolate a timestamp given sequence and point values. + +It will try to find the points immediately before and after in the sequence and interpolate into the gap, which may consist of multiple missed shots. + +If called on an existing shotpoint it will return an interpolated timestamp as if the shotpoint did not exist, as opposed to returning its actual timestamp. + +Returns NULL if it is not possible to interpolate.'; END; $$ LANGUAGE plpgsql;