Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
b4git opened this issue Dec 17, 2024 · 0 comments
Open

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

b4git opened this issue Dec 17, 2024 · 0 comments

Comments

@b4git
Copy link

b4git commented Dec 17, 2024

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>)
@b4git b4git changed the title Iterating over result Iterating over results one by one without loading all in advance Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant