我在我的应用程序中使用node-postgres。我想知道我想要遵循的最佳实践以确保稳定的连接。
以下是我现在使用的代码,
exports.getAll = function (args, callback) {
helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();
helper.client.query('select count(1) as total_records from facilities', function(err,response){
helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities',
function(err,response){
callback(response);
helper.client.end.bind(helper.client);
});
});
};
Run Code Online (Sandbox Code Playgroud)
正如您在代码中看到的,我为每个请求连接数据库,并在查询执行后断开连接。我还有一个想法,我可以仅全局连接一次数据库并使用打开的连接执行查询。代码看起来像
helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();
exports.getAll = function (args, callback) {
helper.client.query('select count(1) as total_records from facilities', function(err,response){
helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities',
function(err,response){
callback(response);
});
});
};
Run Code Online (Sandbox Code Playgroud)
这里的联系永远不会结束。据我所知,我无法决定哪一个最好。请建议。
谢谢..
阅读文档后:https : //github.com/brianc/node-pg-pool,我有点担心重用该new Pool()方法。
文档建议我需要像这样放置new Pool()beforeexports和return它
// db.js
const pool = new Pool();
module.exports = () => { return pool; }
Run Code Online (Sandbox Code Playgroud)
这样我就可以重用,Pool直到idleTimeoutMillis或client.release(),通过使用require()其他文件,例如:
const connect = require('./db')
connect().query(' .... ');
Run Code Online (Sandbox Code Playgroud)
如果这是正确的,它是如何工作的?node.js 是否缓存new Pool(), 因为它不在里面module.exports?
我正在尝试使用node-postgres (PG)连接到在端口5432上运行的 localhost PostgreSQL 数据库。为此,我设置了ngrok来隧道传输我的请求。
./ngrok tcp 5432
Run Code Online (Sandbox Code Playgroud)
下面的代码在本地运行时有效(即使在使用 ngrok 进行隧道传输时)。当我连接到外部数据库时,它也适用于 lambda - 在我的情况下由 Heroku 托管。
'use strict';
const PG = require('pg');
// These credentials work locally
var credentials = {
user: 'MyUsername',
host: 'tcp://0.tcp.ngrok.io',
database: 'MyDatabase',
password: 'MyPassword',
port: '12829',
ssl: true
};
const pool = new PG.Pool(credentials);
const connectionPromise = function(){
return new Promise(function (resolve, reject) {
pool.connect(function (err, client, done) {
if(err) console.log(err);
err ? reject(err) : resolve({
client: client,
done: …Run Code Online (Sandbox Code Playgroud) 预先声明,我对 TypeScript 相当陌生,所以这可能是一个愚蠢的问题!
我正在尝试对我的 Express/Postgres 应用程序使用与node-postgres 文档中所述相同的设置中所述相同的设置,其中我有一个连接到 PostgreSQL 服务器的模块,并且包含在我需要访问它的任何地方,但我TypeScript 类型遇到一些问题。
在这个例子中,我简化了一切以完全删除 Express。如果我这样做,一切都会正常,并且 TypeScript 的编译器也很高兴:
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT),
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
});
(async function getRows() {
const result = await pool.query('SELECT id, message, created FROM media');
interface dbObject {
id: number,
message: string,
created: Date
}
await result.rows.map((row: dbObject) => {
console.log(row.id);
console.log(row.message);
console.log(row.created);
})
})()
Run Code Online (Sandbox Code Playgroud)
但是,如果我将这些pg函数移至其自己的单独db.ts模块中:
import { Pool …Run Code Online (Sandbox Code Playgroud) 我们可以为Client设置 2 个超时时间:
statement_timeout: 查询语句超时前的毫秒数,默认为无超时query_timeout
查询调用超时前的毫秒数,默认为无超时我是这样理解的:
statement_timeout将被传递到数据库中(见Postgres的-文档:statement_timeout),当一份声明中花费比这更长的时间,该数据库将中止查询,并返回一个错误query_timeout. 这由驱动器 ( node-postgres)处理。当达到此超时时间时,node-postgres将停止侦听响应,但数据库可能仍在执行查询问题 1是否应该将查询超时设置得比语句超时稍长?
我认为是因为那时:
我们在使用事务时是什么情况?
例如,当我们查看文档中的示例时:
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await …Run Code Online (Sandbox Code Playgroud) 我想使用PostgreSQL 事务隔离来通过乐观并发控制模式确保数据正确性, 其中冲突事务会自动重试,而不是我的应用程序预先锁定数据库行和表。
实现这一点的一种常用方法是,Web 应用程序在代码块内重试事务特定次数,或通过中间件层重放 HTTP 请求,也称为 HTTP 请求重放。这是 Pyramid 和 Python Web 应用程序 web 的此类中间件的示例。
我没有找到任何关于 Node.js 及其 PostgreSQL 驱动程序如何处理有两个并发事务正在进行中而一个由于读写冲突而无法通过的情况的好信息。PostgreSQL 将回滚其中一个事务,但这是如何向应用程序发出信号的?在 Python 中,PSQL 驱动程序会psycopg2.extensions.TransactionRollbackError在这种情况下引发。对于其他 SQL 数据库驱动程序,这里有一些它们会引发的异常。
当您将 SQL 事务隔离级别设置为 SERIALIZABLE 时,这种行为更常见,因为您在负载下往往会遇到更多冲突,因此我想优雅地处理它,而不是向用户提供 HTTP 500。
我的问题是:
如何使用 PostgreSQL 和一些常见的 ORM 框架(如 TypeORM)检测脏读回滚 - 如果需要特殊处理并且重试库不能独立?
是否有中间件 (NestJS/Express.js/others) 来处理这个问题,并在数据库驱动程序发生事务回滚时自动尝试重放 HTTP 请求 N 次?
我需要使用 node.js 获取特定 Postgres 数据库中的所有表。但没有找到任何方法来实现这一目标。有没有办法得到它?
例如,假设我有一个名为“TestDatabase”的数据库,它包含 4 个表(假设它可以有更少或更多)人、公司、衣服、动物。我需要使用 node.js 获取所有这些的名称。
我还使用 node-postgres ('pg') 连接数据库。
我想分享一个Noderepo,理想情况下它应该在通常的yarn install && yarn start.
但是,pg既不能连接SELECT到/从尚不存在的数据库和表。
这很麻烦,但目前需要这些前面的步骤:
docker run --name my-postgres -e POSTGRES_PASSWORD={MY_PASSWORD} -p 5432:5432 -d --rm postgres:13.0docker exec -it -u postgres my-postgres psqlCREATE DATABASE MY_DB\connect MY_DBCREATE TABLE my_table (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
field_1 VARCHAR ( 50 ) UNIQUE NOT NULL,
field_2 INT NOT NULL,
);
Run Code Online (Sandbox Code Playgroud)
因为我已经从泊坞窗获得的Postgres,是docker-componse在合理的解决方案?我不太熟悉dockerfile,有没有其他选择?
在节点中初始化 postgres 数据库的最佳实践是什么? …
当我运行以下测试时:
afterAll(async () => {
await runDbBuild();
await pool.end();
});
describe("queries.newteetypes.select.all():", () => {
test("Test 1: object keys ", async () => {
const awaitedResponse = await queries.newteetypes.select.all();
expect(awaitedResponse).toStrictEqual(anticipatedResponse);
});
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误:Jest has detected the following 1 open handle potentially keeping Jest from exiting:

上面显示的代码在生产中工作得非常好。问题只是jest给我一个潜在的打开句柄警告。
setTimeout()我可以通过使用和引入延迟来修复它Promise,但放置位置让我感到困惑。这是解决方案(相同的代码,但在查询调用上方添加了一行):
afterAll(async () => {
await runDbBuild();
await pool.end();
});
describe("queries.newteetypes.select.all():", () => {
test("Test 1: object keys ", async () => {
await new Promise((resolve) => setTimeout(() => …Run Code Online (Sandbox Code Playgroud) 我了解参数化查询,但由于我必须以编程方式构造where 条件,因此计算参数的数量并构建参数数组是一项比在需要时简单地调用转义函数要复杂得多的任务。所以:
node-postgres 中有参数转义函数吗?
node-postgres ×10
node.js ×8
postgresql ×5
docker ×1
express ×1
jestjs ×1
lambda ×1
ngrok ×1
node-pg-pool ×1
pg-promise ×1
typeorm ×1
typescript ×1