在 pg-promise 中使用游标
Using a cursor with pg-promise
我正在努力寻找将游标与 pg-promise 结合使用的示例。 node-postgres 支持它的 pg-cursor 扩展。有没有办法将该扩展与 pg-promise 一起使用?我正在尝试实现一个异步生成器(以支持 for-await-of)。 pg-query-stream 似乎不适合这个用例(我需要 "pull",而不是 "push")。
例如,我使用 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();
}
}
使用 pg-cursor,对 stmt
的赋值会变成类似 client.query(new Cursor(...))
,stmt.get
会变成 stmt.read(1)
而 stmt.finalize
会变成 stmt.close
.
谢谢
正在关注 the original examples, we can modify them for use with 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 > ';
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);
});
由于pg-promise doesn't support pg-cursor显式,必须手动获取连接对象并直接使用,如上例所示。
pg-query-stream doesn't seem to be appropriate for this use case (I need pull
, rather than push
).
实际上,在这些库的上下文中,流和游标都仅用于拉取数据。所以你也可以使用流式传输。
我正在努力寻找将游标与 pg-promise 结合使用的示例。 node-postgres 支持它的 pg-cursor 扩展。有没有办法将该扩展与 pg-promise 一起使用?我正在尝试实现一个异步生成器(以支持 for-await-of)。 pg-query-stream 似乎不适合这个用例(我需要 "pull",而不是 "push")。
例如,我使用 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();
}
}
使用 pg-cursor,对 stmt
的赋值会变成类似 client.query(new Cursor(...))
,stmt.get
会变成 stmt.read(1)
而 stmt.finalize
会变成 stmt.close
.
谢谢
正在关注 the original examples, we can modify them for use with 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 > ';
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);
});
由于pg-promise doesn't support pg-cursor显式,必须手动获取连接对象并直接使用,如上例所示。
pg-query-stream doesn't seem to be appropriate for this use case (I need
pull
, rather thanpush
).
实际上,在这些库的上下文中,流和游标都仅用于拉取数据。所以你也可以使用流式传输。