使用Node pg库的pool.query和client.query有什么区别?

时间:2019-05-29 04:06:54

标签: node.js postgresql express client connection-pooling

我试图了解pool.queryclient.query以及两者之间的区别以及何时使用它们。

我有一个Express应用程序,该应用程序在某个端点上运行以下代码。

// am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
  const { username, password } = req.params;
  // crypt & gen_salt function from pgcrypto
  pool // *** here ***
    .query(
      ` SELECT username, email, password FROM users 
        WHERE users.username = $1
        AND users.password = crypt($2, password)
      `, [username, password]
    )
    .then(user => {
      console.log("Users ==>", user.rows);
      const userCount = user.rows.length;
      if (userCount < 1) {
        res.status(204).json({ userFound: "No User Found" });
      } else {
        res.status(200).json(user.rows[0]);
      }
    })
    .catch(err => console.log(err));
});

// am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
  const { username, password } = req.params;
  // crypt & gen_salt function from pgcrypto
  client // *** here ***
    .query(
      ` SELECT username, email, password FROM users 
        WHERE users.username = $1
        AND users.password = crypt($2, password)
      `, [username, password]
    )
    .then(user => {
      console.log("Users ==>", user.rows);
      const userCount = user.rows.length;
      if (userCount < 1) {
        res.status(204).json({ userFound: "No User Found" });
      } else {
        res.status(200).json(user.rows[0]);
      }
    })
    .catch(err => console.log(err));
});
// index.js (starting point of application)
require("dotenv").config({ debug: true });
const app = require("./middleware");


// Port Listener
app.listen(process.env.PORT, () =>
  console.log(
    "Server running on PORT <======= " + process.env.PORT + " =======>"
  )
);

我击中了API端点,并且两种方式都返回了完全相同的结果,并且我读到使用池化实例化一个新的客户端实例会更好,但是老实说我不确定这是否成立,因为Node应该保持同一客户端实例,因为它的导出方式超出了我当前的知识范围。我在该主题上发现的读物很少,因此,如果有人推荐他们的文章,那么我也很乐意将它们检查出来。

1 个答案:

答案 0 :(得分:1)

我相信两者都是一样的。但是pool.query允许您在需要从客户端线程池访问的客户端执行时执行基本的单个查询。

因此pool.query可用于直接运行查询,而不是获取客户端,然后使用该客户端运行查询。

从池中获取客户端

const { Pool } = require('pg')

const pool = new Pool()

pool.connect((err, client, release) => {
  if (err) {
    return console.error('Error acquiring client', err.stack)
  }
  client.query('SELECT NOW()', (err, result) => { // Default client query which is same as that used when connect to DB with one client.
    release()
    if (err) {
      return console.error('Error executing query', err.stack)
    }
    console.log(result.rows)
  })
})

与上述相同,但没有游泳池

const { Client } = require('pg').Client
const client = new Client()
client.connect()
client.query('SELECT NOW()', (err, res) => {
  if (err) throw err
  console.log(res)
  client.end()
})

直接在池中调用查询

const { Pool } = require('pg')

const pool = new Pool()

// Direct query without acquiring client object.
pool.query('SELECT $1::text as name', ['brianc'], (err, result) => {
  if (err) {
    return console.error('Error executing query', err.stack)
  }
  console.log(result.rows[0].name) // brianc
})