postgresql - 使用带有 PostgreSQL 和 JSONb 输入的 mustache 模板

标签 postgresql mustache plv8

是时候用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/

相关文章:

javascript - Node mustache 渲染服务器端

postgresql - 在 PostgreSQL 中调试 PLV8

sql - Postgres 不使用索引,即使返回的行少于 5%

ruby-on-rails - 第一个 Heroku、Ruby 和 Postgres 应用程序 - 本地 Postgres 错误

javascript - Mustache 模板将表达式与某个字符串串联

postgresql - PLV8 是否支持对其他服务器进行 http 调用?

javascript - plv8 在 eval() 中禁用执行和准备功能

r - 通过 RPostgreSQL 将表从 R 导出到 PostgreSQL

ruby-on-rails - 如何将 ARRAY_TO_STRING 和 ARRAY_AGG 转换为 arel?

java - 在 Velocity 中,如何使模板将空值、空指针和索引越界异常呈现为空白?