WiseLibs / better-sqlite3

The fastest and simplest library for SQLite3 in Node.js.
MIT License
5.23k stars 390 forks source link

db.prepare is not a function #1119

Closed impactcolor closed 6 months ago

impactcolor commented 6 months ago
    const dbPath = path.join(app.getPath("userData"), "posty.db");
    const db = new Database(dbPath, { verbose: console.log });

I then run:

export async function selectDB(db) {
    const result = await db.prepare("SELECT * from Settings").get();
    console.log(242)
    console.log(result)
    return result;
  }

The error I get is: (node:61449) UnhandledPromiseRejectionWarning: TypeError: db.prepare is not a function

Any idea what I"m doing wrong?

neoxpert commented 6 months ago

Well, how do you "run" the selectDB function? Do you pass the correct db object into it? Also, neither prepare nor get do return a Promise. Await is not required here.

I would guess your problem is located somewhere on the JavaScript level, if you can share more information we might be able to give a better hint.

impactcolor commented 6 months ago

I believe you are correct. I moved the initialization of the db to main.ts (in an Electron app). import Database from 'better-sqlite3'; const dbPath = path.join(app.getPath("userData"), "posty.db"); const db = new Database(dbPath);

This crashes my electron app. Am I incorrectly initializing the database? @neoxpert

neoxpert commented 6 months ago

And how does "db" end up in selectDB? While I am firm with it, I do not use TypeScript in any of my projects ..

A minimal, plain NodeJS / Electron compatible, working example might be:

const Database = require('better-sqlite3');
const db = new Database(':memory:');

db.exec('CREATE TABLE test(num bigint)')
db.exec('INSERT INTO test(num) VALUES(5)');

function selectDB(db) {
    const i = db.prepare('SELECT * FROM test').get();

    console.log(i);  // This should output "{num: 5}"

    return i;
}

selectDB(db);

I would not blame the initialization of the database, but handling the reference to the created instance might be the issue,