-
-
Save richardartoul/23b66ea6924f28fc6ec8dfcd06901302 to your computer and use it in GitHub Desktop.
Test stored procedure
This file contains 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 TYPE metric as ( | |
ts integer, | |
val double precision | |
); | |
CREATE TABLE IF NOT EXISTS metrics ( | |
sdk_run_uuid UUID REFERENCES model_runs(sdk_uuid) NOT NULL, | |
name varchar(20) NOT NULL, | |
ts timestamptz NOT NULL, | |
data metric[] CHECK (array_length(data, 1) <= 100), | |
PRIMARY KEY(sdk_run_uuid, name, ts) | |
); | |
CREATE OR REPLACE FUNCTION write_metric(ts_param timestamptz, sdk_run_uuid_param UUID, name_param varchar(30), val double precision) | |
RETURNS void AS $$ | |
DECLARE | |
latest_entry RECORD; | |
BEGIN | |
-- TODO: Acquire lock on sdk_run_uuid | |
SELECT INTO latest_entry | |
metrics.sdk_run_uuid as sdk_run_uuid, | |
metrics.ts as ts, | |
array_length(metrics.data, 1) as data_length | |
FROM metrics | |
WHERE | |
metrics.sdk_run_uuid = sdk_run_uuid_param AND | |
metrics.name = name_param | |
ORDER BY metrics.ts DESC | |
LIMIT 1; | |
IF latest_entry IS NULL THEN | |
-- New metric, create a new row | |
INSERT INTO | |
metrics ( | |
sdk_run_uuid, | |
name, | |
ts, | |
data | |
) | |
VALUES (sdk_run_uuid_param, name_param, ts_param, ARRAY[(0, val)::metric]); | |
raise notice 'ITS NULL'; | |
ELSE | |
-- If latest row has less than 100 entries, write to it | |
IF latest_entry.data_length < 100 THEN | |
UPDATE metrics | |
SET | |
data = array_append(data, (EXTRACT (EPOCH FROM ts_param - latest_entry.ts) * 1000, val)::metric) | |
WHERE | |
metrics.sdk_run_uuid = sdk_run_uuid_param AND | |
metrics.name = name_param AND | |
metrics.ts = latest_entry.ts; | |
-- Otherwise create a new row | |
ELSE | |
INSERT INTO | |
metrics ( | |
sdk_run_uuid, | |
name, | |
ts, | |
data | |
) | |
VALUES (sdk_run_uuid_param, name_param, ts_param, ARRAY[(0, val)::metric]); | |
END IF; | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; | |
SELECT write_metric(NOW(), '5f8e71ba-1dca-4dc7-b81f-adb3b03dd711', 'test_metric', 10.0); | |
SELECT * FROM metrics where metrics.sdk_run_uuid = '5f8e71ba-1dca-4dc7-b81f-adb3b03dd711'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wtf breh