nodejs 和 postgres:选择更新的最佳方式

问题描述 投票:0回答:3

我需要从 Node.js 在 postgres 数据库中进行“选择更新”,即获取一个游标,对其进行迭代并根据需要更新值。

我不知道在 Node.js 中是否可能以及如何实现。

我发现https://github.com/brianc/node-pg-cursor这似乎适合读取光标,但没有用于更新它。

有没有一个模块或模式可以实现这一点?

非常感谢

sql node.js postgresql cursor
3个回答
1
投票

2023 年更新:

您现在可以使用 pg-package 和行级锁来执行此操作。

class DBConnector {
constructor(){
    const { Client } = require('pg');
    this.client = new Client({
        user: process.env.DB_USERNAME,
        host: process.env.DB_HOST,
        database: process.env.DATABASE,
        password: process.env.DB_PASSWORD,
        port: process.env.DB_PORT,
      });
    this.client.connect();
}

async acquireLockForRow(table, rowId) {
    await this.client.query('START TRANSACTION');
    try {
        // If it is locked, it throws an error
        const res = await this.client.query('SELECT id FROM ' + table + ' WHERE id=' + rowId + ' FOR UPDATE SKIP LOCKED;');
        
        // If there is no lock
        if (res.rows[0].id === rowId) {
            // Release the lock after 5 minutes (if not already done, just to avoid forgetting to unlock it)
            setTimeout(async () => {await this.releaseLock()}, 1000 * 60 * 5);
        }
    } catch(e) {
        return "Could not obtain";
    }
}

async releaseLock() {
    await this.client.query('COMMIT;');
}
}

0
投票

截至目前,Node JS 平台中还没有实现此功能,因此唯一可行的选择是在 Postgres 函数中实现它,然后从 Node JS 调用它。


0
投票

截至今天,Node JS 平台内还没有实现此功能

嗯,怎么会这样:) 如果您正在使用 ORM,则有一个选项,您可以执行类似的操作

await this.dataSource.transaction(<IsolationLevel>'REPEATABLE READ',async(entityManager)=>{
            return await entityManager.query('select * ... FOR UPDATe', [params_here]);
        })
© www.soinside.com 2019 - 2024. All rights reserved.