标签: node-postgres

node-postgres'事件发射器样式'vs'回调样式'

node-postgres声明如下:

node-postgres支持'事件发射器'样式API和'回调'样式.回调样式更简洁,通常更受欢迎,但是公平的API可以派上用场.它们可以混合搭配.

使用事件发射器API,我可以执行以下操作:

var db = new pg.Client("insert-postgres-connection-info");
db.connect();
Run Code Online (Sandbox Code Playgroud)

然后我可以使用db在我的网络应用程序中执行查询db.query('sql statement here').使用回调样式,每次我想运行查询时都会执行以下操作:

pg.connect(conString, function(err, client) {
  client.query("sql statement", function(err, result) {
    // do stuff
  });
});
Run Code Online (Sandbox Code Playgroud)

所以我的问题是为什么使用回调样式"通常更喜欢"?每次使用数据库执行某些操作时打开连接效率不高吗?使用回调样式有什么好处?

编辑

我可能会错误地认为他的意思是"回调风格"(我不是在开玩笑,我的JavaScript不是很强)但我的问题是关于连接方法.我假设以下是回调样式连接方法:

// Simple, using built-in client pool

var pg = require('pg'); 
//or native libpq bindings
//var pg = require('pg').native

var conString = "tcp://postgres:1234@localhost/postgres";

//error handling omitted
pg.connect(conString, function(err, client) {
  client.query("SELECT NOW() as when", function(err, result) {
    console.log("Row count: %d",result.rows.length);  // 1
    console.log("Current year: %d", result.rows[0].when.getYear());
  }); …
Run Code Online (Sandbox Code Playgroud)

postgresql node.js node-postgres

3
推荐指数
2
解决办法
2698
查看次数

省略列名/将对象直接插入到node-postgres中

我想传递以列名作为key 的字典,从而避免在查询本身中声明列名(直接键入它们)。


假设我有一个User包含 2 个列名的表:

  • idUser(INT)
  • fullName(VARCHAR)

要使用node-postgres创建记录,我需要在查询中声明列名称,如下所示:

    var idUser   = 2;
    var fullName = "John Doe";
    var query = 'INSERT INTO User(idUser, age) VALUES ($1, $2)';

    database.query(query, [idUser, fullName], function(error, result) {
      callback(error, result.rows);
      database.end();
    });
Run Code Online (Sandbox Code Playgroud)

我更希望有一种方法可以只传递字典并让它从键中推断出列名 - 如果有一个简单的技巧我想听听。

例如这样的事情:

    var values = {
      idUser  : 2,
      fullName: "John Doe"
    };
    var query = 'INSERT INTO User VALUES ($1)';

    database.query(query, [values], function(error, result) {
      callback(error, result.rows);
      database.end();
    });
Run Code Online (Sandbox Code Playgroud)

postgresql node.js node-postgres

3
推荐指数
1
解决办法
3977
查看次数

postgreSQL错误:“约束不存在”(但它确实存在......)

我有一个正在尝试更新的数据库,但我不明白为什么会收到有关不存在的列的奇怪错误。当我使用“heroku pg:psql”访问数据库时,我完全可以看到该列。我发现了其他几个具有类似问题的问题,但未能解决。

这是我执行插入的代码...与约束冲突...有什么想法吗?

const text = 'INSERT INTO "test2" '
+'(route_id, secupdated, retrievedate, traintimeday) '
+'VALUES($1, $2, $3, $4) '
+'ON CONFLICT ON CONSTRAINT traintimeday '
+'DO UPDATE SET (secupdated, secarrival) = (excluded.secupdated, excluded.secarrival) '
+'RETURNING *' ; 
const values = [train_id 
, Math.round(dateNow.getTime()/1000)
, Math.round(dateNow.getDate())
, Math.round(dateNow.getDate()) + stu.stop_id
]; 
pool.query(text, values, (err, res) => {
if (err) {
throw err;
}
console.log('user:', res.rows[0])
})
Run Code Online (Sandbox Code Playgroud)

错误消息显示“约束 traintimeday 不存在”

javascript postgresql node-postgres

3
推荐指数
1
解决办法
6792
查看次数

从连接获取 PostgreSQL 服务器版本?

现代 PostgreSQL 连接协议中是否有任何内容可以指示服务器版本?

如果没有,是否存在端点可以针对开放连接执行的特殊低级请求,以提取包含该版本的服务器详细信息?

我正在研究node-postgres的可能扩展,它会在每次新连接时自动提供服务器版本。我想知道这是否可能。

对于管理连接的基本驱动程序来说,必须SELECT version()在每个新连接上执行然后解析它,级别太高了。它应该在协议级别完成。

postgresql node-postgres

3
推荐指数
1
解决办法
1237
查看次数

Postgres 服务器未响应 nodejs 请求

我可以从 pgAdmin4 访问远程 postgres 数据库,也可以使用 Mac 从 nodejs 访问。现在我使用相同的代码来访问 Windows 中的数据库。我的连接代码如下:

const { Client } = require('pg'); //Importing the Postgres package
const hosts= require('../hosts'); //Using the file containig all hosts 
const connectionData = { //Begin creating the connection settings object
   host: hosts.DBHost, //DB host   
   port: hosts.DBPort, //DB hosts port
   database: hosts.DB, //DB
   user: hosts.DBUser, //DB user
   password: hosts.DBPassword, //DB user password
 } 
Run Code Online (Sandbox Code Playgroud)

我的测试如下:

var client = new Client(connectionData); //New client instance using the above connection settings
client.connect(); //Open the connection …
Run Code Online (Sandbox Code Playgroud)

postgresql node.js node-postgres

3
推荐指数
1
解决办法
1260
查看次数

您可以在 Next.js API 中保持 PostgreSQL 连接处于活动状态吗?

我正在将 Next.js 用于我的业余项目。我有一个托管在 ElephantSQL 上的 PostrgeSQL 数据库。在 Next.js 项目中,我使用 apollo-server-micro 包设置了 GraphQL API。

在设置 GraphQL API 的文件 (/api/graphql) 中,我导入一个数据库帮助程序模块。在其中,我设置了一个池连接并导出一个函数,该函数使用池中的客户端来执行查询并返回结果。这看起来像这样:

// import node-postgres module
import { Pool } from 'pg'

// set up pool connection using environment variables with a maximum of three active clients at a time
const pool = new Pool({ max: 3 })

// query function which uses next available client to execute a single query and return results on success
export async function queryPool(query) {
    let payload …
Run Code Online (Sandbox Code Playgroud)

postgresql node.js node-postgres next.js serverless

3
推荐指数
1
解决办法
2847
查看次数

无法安装node-postgres

我正在尝试为我的项目设置node-postgres.但是,当我尝试安装它时,我不断收到这些gyp错误.如何让node-postgres识别出我的pg_config位于/Library/PostgreSQL/9.3/bin/pg_config中.因为我最喜欢的搜索引擎结果告诉我这样做:

?  src git:(master) ? PG_CONFIG=/Library/PostgreSQL/9.3/bin/pg_config
?  src git:(master) ? export PG_CONFIG
?  src git:(master) ? sudo npm install pg
Password:
npm WARN package.json test@0.1.0 No repository field.
npm http GET https://registry.npmjs.org/pg
npm http 304 https://registry.npmjs.org/pg
npm http GET https://registry.npmjs.org/generic-pool/2.0.3
npm http GET https://registry.npmjs.org/buffer-writer/1.0.0
npm http GET https://registry.npmjs.org/pgpass/0.0.1
npm http GET https://registry.npmjs.org/nan
npm http 304 https://registry.npmjs.org/nan
npm http 304 https://registry.npmjs.org/pgpass/0.0.1
npm http 304 https://registry.npmjs.org/buffer-writer/1.0.0
npm http 304 https://registry.npmjs.org/generic-pool/2.0.3
npm http GET https://registry.npmjs.org/split
npm http 304 https://registry.npmjs.org/split
npm http GET https://registry.npmjs.org/through …
Run Code Online (Sandbox Code Playgroud)

postgresql node.js node-postgres

2
推荐指数
1
解决办法
4010
查看次数

如何在 pg-promise 中设置模式

我在创建客户端时专门搜索pg-promise的文档。但是我找不到设置要在连接中使用的默认架构的选项,它总是使用public架构。我该如何设置?

javascript postgresql node-postgres pg-promise

2
推荐指数
1
解决办法
3517
查看次数

node-postgres 中带有字符串文字的参数化查询

我正在尝试编写一个 node-postgres 查询,该查询采用一个整数作为参数在间隔中使用:

  const query = {
    text:
      `SELECT
        foo 
        FROM bar 
        WHERE 
          DATE(created_at) >= DATE(NOW()) - INTERVAL '$1 DAYS';`,
    values: [daysAgo]
  }
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它给出了这个错误消息,表明它没有看到,$1因为它用单引号括起来:

绑定消息提供 1 个参数,但准备好的语句 "" 需要 0

有没有支持的方法来做到这一点?如果没有,最好的解决方法是什么?

node-postgres

2
推荐指数
1
解决办法
1869
查看次数

为什么当我调用 client.connect() 时 node-postgres (pg) 挂起?

我最近不得不将我的 vue.js 应用程序(后端的 node.js)的 node.js 版本从 v13.5.0 升级到 v14.5.0。我重新安装了所有节点包,升级了我必须升级的那些,现在应用程序挂在所有数据库调用上。我们使用 pg (node-postgres) 来调用我们的数据库。我将 pg 升级到 7.18.2 版。

我们的初始化代码如下所示:

constructor() {
  this.pg = require('pg');
  this.client = null;
  this.initPromise = null;
}

async init() {
  if (!this.initPromise) {
    this.client = new this.pg.Client({
      application_name: 'Back end',
      ssl: {
        rejectUnauthorized: false
      }
    });
    this.initPromise = this.client.connect();
  }
  return this.initPromise;
}

async query(query, params) {
  await this.init();
  return await this.client.query(query, params);
}
Run Code Online (Sandbox Code Playgroud)

我将控制台日志放在对 this.init() 的调用中,如下所示:

console.log('before');
await this.init();
console.log('after');
Run Code Online (Sandbox Code Playgroud)

'after' 永远不会打印出来。

有谁知道为什么我升级了节点版本后它会挂起?

postgresql freeze node.js node-postgres

2
推荐指数
1
解决办法
1714
查看次数