Skip to content

Iterating over results one by one without loading all in advance #143

Description

@b4git

What is the correct way of iterating over the results one at a time without having to load large dataset in memory? It's giving an error while trying to use for of:

import { Database } from "jsr:@db/[email protected]";

// Setup and insert data
const db = new Database(":memory:");

// Create simple table
db.exec(`
  CREATE TABLE test (
    id INTEGER PRIMARY KEY,
    value TEXT
  );
`);

// Insert test data
const stmt = db.prepare("INSERT INTO test (value) VALUES (?)");
stmt.run("value1");
stmt.run("value2");
stmt.run("value3");
stmt.finalize();

// Method 1: Works fine with .all()
console.log("Testing .all():");
const rows = db.prepare("SELECT * FROM test").all();
console.log(rows);

// Method 2: Will error when using for..of
console.log("\nTesting for..of:");
try {
    const stmt2 = db.prepare("SELECT * FROM test where id > ?");
    stmt2.bind(0); 
    for (const row of stmt2) {
        console.log(row);
    }
    stmt2.finalize();
} catch (e) {
    console.error("Error occurred:", e);
}

db.close();

Console log:

Testing .all():
[
  { id: 1, value: "value1" },
  { id: 2, value: "value2" },
  { id: 3, value: "value3" }
]

Testing for..of:
Error occurred: Error: Statement already bound to values
    at Statement.#bindAll (https://jsr.io/@db/sqlite/0.12.0/src/statement.ts:376:28)
    at Statement.iter (https://jsr.io/@db/sqlite/0.12.0/src/statement.ts:703:18)
    at iter.next (<anonymous>)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions