是时候用JSONb datatype作为模板中的输入,PostgreSQL 查询作为模板系统... Mustache将是完美的,如果有一些 PLpgSQL 的 Mustache 实现(或适用于 C )......似乎没有。
但是有一个good source-code for Javascript-mustache : 如何将其用于 PLv8?
在类似
SELECT tplEngine_plv8(input_jsonb,tpl_mustashe) as text_result FROM t
的上下文中多次调用 mustache 的最佳方式(性能)是什么?
测试和讨论注意事项
测试: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;
因此,对于 VIEW t,我们有一个 mustache 模板的名称和标题,
SELECT tplEngine_plv8(
j,
'<br/>* <b>{{title}}</b> with: {{#names}} <i>{{name}}</i>; {{/names}}'
) as result
FROM t;
并将其与 JSFiddle 结果进行比较。
性能测试
使用 EXPLAIN ANALYZE
... 或许在测试表中添加数百个随机值。并且,还测试调用策略:一次一个或按数组。
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
$$;
或
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 $$ ... $$;
最佳答案
create or replace function mustache(template text, view json, partials json) returns text
language plv8 as
<< copy https://rawgit.com/janl/mustache.js/master/mustache.js >>
var mustache=this.Mustache;
return mustache.render(template, view, partials)
$$
;
关于postgresql - 使用带有 PostgreSQL 和 JSONb 输入的 mustache 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983051/