基于节点的SQL构建器,支持Common Table Expression(WITH子句)

时间:2015-01-07 23:39:47

标签: sql node.js postgresql amazon-redshift

我正在构建一个需要使用CTE查询Redshift数据库(基于postgres 8.0.2)的Node.js应用程序。不幸的是,到目前为止我看过的SQL查询构建器(node-sqlknex.js和sequelize)似乎不支持公用表表达式(CTE)。

我使用Jeremy Evans的Sequel gem在Ruby中形成公共表表达式非常成功,它有一个with方法,它接受两个参数来定义表的别名和数据集引用。我想在Node中有类似的东西。

我是否错过了Node.js SQL查询构建器的任何明显竞争者?据我所知,这些是最明显的四个:

  • 节点-SQL
  • nodesql(没有postgres支持?)
  • knex.js
  • sequelize

4 个答案:

答案 0 :(得分:2)

我能够使用knex.js的公用表表达式(CTE),这很容易。

假设您正在使用socket.io以及knex.js,

<强> knex-example.js

function knexExample (io, knex) {
  io.on('connection', function (socket) {
    var this_cte = knex('this_table').select('this_column');

    var that_cte = knex('that_table').select('that_column');

    knex.raw('with t1 as (' + this_cte + 
    '), t2 as (' + that_cte + ')' + 
    knex.select(['this', 'that'])
      .from(['t1', 't2'])
    )
    .then(function (rows) {
      socket.emit('this_that:update', rows);
    });
  })
}

module.exports = knexExample;

答案 1 :(得分:1)

knex.js现在支持WITH子句:

knex.with('with_alias', (qb) => {
  qb.select('*').from('books').where('author', 'Test')
}).select('*').from('with_alias')

输出:

with "with_alias" as (select * from "books" where "author" = 'Test') select * from "with_alias"

答案 2 :(得分:0)

来自this issuethis issue我明白您可以将CTE与Sequelize一起使用。

您需要使用原始查询,并且可能需要精确的类型,以确保Sequelize了解它是Select查询。见第一个链接。

示例代码为:

sequelize.query(
  query, //raw SQL
  tableName,
  {raw: true, type: Sequelize.QueryTypes.SELECT}
).success(function (rows) {
  // ...
})

有关模式详情,请参阅here

答案 3 :(得分:0)

xql.js支持版本1.4.12中的WITH子句。一个小例子:

const xql = require("xql");
const SELECT = xql.SELECT;

return SELECT()
 .WITH("with_alias", SELECT().FROM("books").WHERE("author", "=", "Test"))
 .FROM("with_alias");

SELECT,INSERT,UPDATE,DELETE和复合查询也支持WITH子句。