使用带有PostgreSQL和JSONb输入的胡子模板

时间:2017-12-26 19:44:15

标签: postgresql mustache plv8

是时候在模板中使用JSONb datatype作为输入,而PostgreSQL查询作为模板系统... Mustache将是完美的,如果有一些针对PLpgSQL的Mustache实现(或适用于{{ 3}})......似乎没有人。

但是有C如何使用/适应PLv8?

在像SELECT tplEngine_plv8(input_jsonb,tpl_mustashe) as text_result FROM t这样的上下文中多次调用小胡子的最佳方式(性能)是什么?

测试和讨论的注释

测试:good source-code for Javascript-mustache

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我们有胡子模板的名称和标题

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 $$ ... $$;

1 个答案:

答案 0 :(得分:1)

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)
 $$