Is time to use JSONb datatype as input in a template, and PostgreSQL queries as template system... Mustache will be perfect, if there are some Mustache implementation for PLpgSQL (or adapted for C)... Seems there are no one.
But there are a good source-code for Javascript-mustache: how to use/adapt it for PLv8?
What the best way (performance) to call mustache many times in a context like
SELECT tplEngine_plv8(input_jsonb,tpl_mustashe) as text_result FROM t
?
NOTES for test and discuss
Test with: http://jsfiddle.net/47x341wu/
CREATE TABLE story (
id int NOT NULL PRIMARY KEY,
title text NOT NULL,
UNIQUE(title)
);
CREATE TABLE story_character (
id_story int REFERENCES story(id) NOT NULL,
name text NOT NULL,
UNIQUE(id_story,name)
);
INSERT INTO story (id,title) VALUES (1,'African jungle story'),
(2,'Story of India jungle');
INSERT INTO story_character(id_story,name) VALUES
(1,'Tarzan'), (1,'Jane'), (2,'Mowgli'), (2,'Baloo');
CREATE VIEW t AS
select id_story, jsonb_build_object('title',title,
'names', jsonb_agg( jsonb_build_object('name', name) )
) AS j
from story s INNER JOIN story_character c ON s.id=c.id_story
group by id_story,title;
So with VIEW t we have names and titles for a mustache template,
SELECT tplEngine_plv8(
j,
'<br/>* <b>{{title}}</b> with: {{#names}} <i>{{name}}</i>; {{/names}}'
) as result
FROM t;
and compare it with the JSFiddle result.
Performance tests
Using EXPLAIN ANALYZE
... Perhaps adding a few hundreds of random values at the testing tables. And, testing also calling strategies: one at a time or by array.
CREATE FUNCTION mustache_engine(
p_input JSONB,
p_template TEXT
) RETURNS TEXT language plv8 as $$
// copy https://rawgit.com/janl/mustache.js/master/mustache.js
// and somethings more
$$;
or
CREATE FUNCTION mustache_engine(
p_inputs JSONB[], -- many inputs
p_templates TEXT -- one template
) RETURNS TEXT[] -- many resuts
language plv8 as $$ ... $$;
CREATE FUNCTION mustache_engine( -- many input-template pairs
p_inputs JSONB[],
p_templates TEXT[]
) RETURNS TEXT[] -- many resuts
language plv8 as $$ ... $$;
;