Skip to main content

Cursor

Cursor provides unidirectional (optionally cached/bidirectional) row-by-row access to a query result, instead of buffering every row into QueryResult.rows at once. It's returned in QueryResult.cursor when a query is executed with cursor: true. See Cursors & Streaming for the full usage guide.

Cursor extends an AsyncEventEmitter and emits move, fetch, eof, reset, close and error.

Constructor

new Cursor(connection: SqbConnection, fields: FieldInfoMap, adapterCursor: Adapter.Cursor, request: QueryRequest)

You don't construct a Cursor yourself — instances are returned via QueryResult.cursor when a query is run with cursor: true.

Properties

PropertyTypeDescription
connectionSqbConnectionThe connection this cursor was created on.
fieldsFieldInfoMapMetadata describing the result's columns.
rowanyThe current row.
rowNumnumberThe current row number (0 before the first row).
isBofbooleantrue before the first row has been fetched.
isEofbooleantrue once you've stepped past the last row of an exhausted cursor.
isClosedbooleantrue once the cursor has been closed.
fetchedRowsnumberTotal rows fetched from the database so far.

Methods

cached()

cached(): void

Enables an internal cache so the cursor can move backward and be re-read. Must be called before any row has been fetched — throws otherwise.

close()

close(): Promise<void>

Closes the underlying adapter cursor and emits close.

fetchAll()

fetchAll(): Promise<number>

Requires caching to be enabled. Fetches every remaining row into the cache and returns the number of rows fetched; after this you can safely close() the cursor and keep reading from the in-memory cache.

moveTo()

moveTo(rowNum: number): Promise<ObjectRow>

Moves to an absolute row number and returns that row. Moving to an earlier row requires caching.

cursor.cached();
await cursor.seek(10);
const row = await cursor.moveTo(3);

next()

next(): Promise<ObjectRow>

Moves forward by one row and returns it, or resolves to undefined once the cursor is exhausted (closing it automatically).

let row;
while ((row = await cursor.next())) {
console.log(row);
}

prev()

prev(): Promise<ObjectRow>

Moves back by one row and returns it. Requires caching to be enabled.

reset()

reset(): void

Rewinds the cursor to before the first row and emits reset. Requires caching to be enabled.

seek()

seek(step: number): Promise<ObjectRow>

Moves the cursor forward (or backward, with caching enabled) by step rows and returns the resulting row.

toStream()

toStream(options?: CursorStreamOptions): CursorStream

Wraps the cursor in a CursorStream for use as a Node.js Readable.