简体   繁体   English

使用带有 pg-promise 的 cursor

[英]Using a cursor with pg-promise

I'm struggling to find an example of using a cursor with pg-promise.我正在努力寻找将 cursor 与 pg-promise 结合使用的示例。 node-postgres supports its pg-cursor extension. node-postgres 支持其 pg-cursor 扩展。 Is there a way to use that extension with pg-promise?有没有办法将该扩展与 pg-promise 一起使用? I'm attempting to implement an asynchronous generator (to support for-await-of).我正在尝试实现一个异步生成器(以支持 for-await-of)。 pg-query-stream doesn't seem to be appropriate for this use case (I need "pull", rather than "push"). pg-query-stream 似乎不适合这个用例(我需要“拉”,而不是“推”)。

As an example, I use SQLite for my unit tests and my (abridged) generator looks something like this...例如,我使用 SQLite 进行单元测试,我的(删节)生成器看起来像这样......

async function* () {

    const stmt = await db.prepare(...);

    try {

        while (true) {

            const record = await stmt.get();

            if (isUndefined(record)) {

                break;
            }

            yield value;
        }
    }
    finally {

        stmt.finalize();
    }
}

Using pg-cursor, the assignment to stmt would become something like client.query(new Cursor(...)) , stmt.get would become stmt.read(1) and stmt.finalize would become stmt.close .使用 pg-cursor,对stmt的赋值会变成类似client.query(new Cursor(...))的东西, stmt.get会变成stmt.read(1)stmt.finalize会变成stmt.close

Thanks谢谢

Following the original examples , we can modify them for use with pg-promise :按照原始示例,我们可以修改它们以与pg-promise一起使用:

const pgp = require('pg-promise')(/* initialization options */);
const db = pgp(/* connection details */);

const Cursor = require('pg-cursor');

const c = await db.connect(); // manually managed connection

const text = 'SELECT * FROM my_large_table WHERE something > $1';
const values = [10];

const cursor = c.client.query(new Cursor(text, values));

cursor.read(100, (err, rows) => {
  cursor.close(() => {
    c.done(); // releasing connection
  });
  // or you can just do: cursor.close(c.done);
});

Since pg-promise doesn't support pg-cursor explicitly, one has to manually acquire the connection object and use it directly, as shown in the example above.由于pg-promise不明确支持pg-cursor ,因此必须手动获取连接 object 并直接使用它,如上例所示。

pg-query-stream doesn't seem to be appropriate for this use case (I need pull , rather than push ). pg-query-stream 似乎不适合这个用例(我需要pull ,而不是push )。

Actually, in the context of these libraries, both streams and cursors are only for pulling data.实际上,在这些库的上下文中,流和游标都仅用于拉取数据。 So it would be ok for you to use streaming also.所以你也可以使用流媒体。

UPDATE更新

For reading data in a simple and safe way, check out pg-iterator .要以简单安全的方式读取数据,请查看pg-iterator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM