游标可用于高效读取大型结果集,而无需提前将整个结果集加载到内存中。它对于模拟 'streaming' 样式的数据读取或从大型结果集中提早退出非常有用。游标传递给 client.query
并以与发送正常查询非常相似的方式在内部调度,但它展示的用于使用结果集的 API 是不同的。
¥A cursor can be used to efficiently read through large result sets without loading the entire result-set into memory ahead of time. It's useful to simulate a 'streaming' style read of data, or exit early from a large result set. The cursor is passed to client.query
and is dispatched internally in a way very similar to how normal queries are sent, but the API it presents for consuming the result set is different.
install
$ npm install pg pg-cursor
构造函数
¥constructor
new Cursor(text: String, values: Any[][, config: CursorQueryConfig])
实例化一个新的 Cursor。游标是 Submittable
的一个实例,应直接传递给 client.query
方法。
¥Instantiates a new Cursor. A cursor is an instance of Submittable
and should be passed directly to the client.query
method.
import pg from 'pg'
const { Pool } = pg
import Cursor from 'pg-cursor'
const pool = new Pool()
const client = await pool.connect()
const text = 'SELECT * FROM my_large_table WHERE something > $1'
const values = [10]
const cursor = client.query(new Cursor(text, values))
cursor.read(100, (err, rows) => {
cursor.close(() => {
client.release()
})
})
type CursorQueryConfig {
// by default rows come out as a key/value pair for each row
// pass the string 'array' here to receive rows as an array of values
rowMode?: string;
// custom type parsers just for this query result
types?: Types;
}
read
cursor.read(rowCount: Number) => Promise<pg.Result>
从游标实例读取 rowCount
行。当行可用、加载到内存、解析并转换为 JavaScript 类型时,将调用回调。
¥Read rowCount
rows from the cursor instance. The callback will be called when the rows are available, loaded into memory, parsed, and converted to JavaScript types.
如果游标已读到结果集的末尾,则对 cursor#read 的所有后续调用都将返回长度为 0 的行数组。在已读到末尾的游标上调用 read
。
¥If the cursor has read to the end of the result sets all subsequent calls to cursor#read will return a 0 length array of rows. Calling read
on a cursor that has read to the end.
这是一个读取到游标末尾的示例:
¥Here is an example of reading to the end of a cursor:
import pg from 'pg'
const { Pool } = pg
import Cursor from 'pg-cursor'
const pool = new Pool()
const client = await pool.connect()
const cursor = client.query(new Cursor('select * from generate_series(0, 5)'))
let rows = await cursor.read(100)
assert(rows.length == 6)
rows = await cursor.read(100)
assert(rows.length == 0)
close
cursor.close() => Promise<void>
用于提早关闭光标。如果你想在获取所有返回的行之前停止从光标读取,请调用此方法。
¥Used to close the cursor early. If you want to stop reading from the cursor before you get all of the rows returned, call this.