Skip to content

Instantly share code, notes, and snippets.

@areski
Created March 12, 2016 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save areski/a06520b55b68fda67c5e to your computer and use it in GitHub Desktop.
Save areski/a06520b55b68fda67c5e to your computer and use it in GitHub Desktop.
PLV8 example - accumulator
--
-- Benchmark PLV8
--
DROP TABLE accumulator;
CREATE TABLE accumulator (id BIGSERIAL PRIMARY KEY, new_value INT, sum_previous INT);
-- DROP FUNCTION IF EXISTS fillaccumulator();
CREATE OR REPLACE FUNCTION fillaccumulator () RETURNS void AS $$
var rows = plv8.execute( "SELECT count(*), SUM(new_value) FROM accumulator" );
var rand = Math.floor((Math.random() * 100) + 1)
// plv8.elog(NOTICE, rand);
plv8.execute("INSERT INTO accumulator (new_value, sum_previous) VALUES($1, $2)", [1, rows[0].sum]);
$$
LANGUAGE plv8;
SELECT fillaccumulator();
CREATE OR REPLACE FUNCTION plbench(query text, n int) returns float as $$
DECLARE
t0 timestamp with time zone;
e float;
BEGIN
t0 := clock_timestamp();
for i in 1 .. n-1 loop
execute query;
end loop;
e = extract(microseconds from clock_timestamp()) - extract(microseconds from t0);
return e / 1000000;
END;
$$ language plpgsql;
SELECT plbench('SELECT fillaccumulator()', 10000);
SELECT count(*), SUM(new_value) FROM accumulator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment