1

我正在使用knex并且pg我想从 node.js 调用 postgreSQL 函数,最好使用 knex。我用过

const knex = require("knex");

exports.getAll = async (companyID) => {
  console.log("from here", companyID);
  const getAll = await databaseProvider
    .knex("attendance")
    .select(knex.raw("select * from get_allFromCompany('?')",[companyID]));
  return databaseProvider.executeQuery(getAll).then((result) => {
    return result.rows;
  });

但我收到错误:

global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)
(node:25) UnhandledPromiseRejectionWarning: Error: Unable to acquire a connection
    at Client_PG.acquireConnection (/app/node_modules/knex/lib/client.js:340:13)
    at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:264:8)
    at Runner.run (/app/node_modules/knex/lib/runner.js:26:12)
    at Builder.Target.then (/app/node_modules/knex/lib/interface.js:19:43)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:25) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
};

我还尝试了其他几种黑客方法,但我无法这样做。我的 sql 查询是

SELECT * FROM get_allFromCompany('1');

有人可以帮我吗?

4

1 回答 1

1

您需要使用您正在使用的方言初始化 knex 实例,然后创建一个与 knex 绑定的查询,然后才能使用 DB 驱动程序执行它。

const knex = require("knex")({client: 'pg'});

exports.getAll = async (companyID) => {
  console.log("from here", companyID);
  
  const getAllQuery = databaseProvider
    .knex("attendance")
    .select(knex.raw("select * from get_allFromCompany('?')",[companyID])).toSQL().toNative();

  return databaseProvider.executeQuery(getAllQuery .sql, getAllQuery .bindings).then((result) => {
    return result.rows;
  });
于 2021-07-28T20:33:26.450 回答