Search code examples
node.jspostgresql-9.1pgknex.js

global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)


I am using knex and pg and I want to call a postgreSQL function from node.js preferably using knex. i have used

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;
  });

But I am getting error:

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)
};

I have also tried several other hacks but I am unable to do so. My sql query is

SELECT * FROM get_allFromCompany('1');

Can someone help me out?


Solution

  • You need to initialize knex instance with dialect are you using and then create a query with bindings with knex and only after that you can use DB driver to execute it.

    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;
      });