Search code examples
node-sqlite3node-async

Node Express - Database is created too late causing error


My problem is with creating a database. It is created too late and causes problems with further queries. I tried to use async and await but it seems it doesn't solve the problem.

async function storeDailyDealToDB(dailyDeal) {
    const db = new sqlite3.Database('database.db');

    await new Promise((resolve) => {
        const QUERY_CREATE_TABLE =
            "CREATE TABLE IF NOT EXISTS daily_deal ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,)";
        db.run(QUERY_CREATE_TABLE);
        resolve("done")
    });

    await new Promise((resolve) => {
        const insert =
            "INSERT INTO daily_deal (title) VALUES (?)";
        const stmt = db.prepare(insert);
        stmt.run([dailyDeal['title']]);
        stmt.finalize();
        resolve("done")
    });

    let lastRow = await new Promise((resolve) => {
        db.each("SELECT * FROM daily_deal ORDER BY id DESC LIMIT 1", function (err, row) {
            resolve(err == null ? {} : row)
        });
    });

    db.close();

    return lastRow
}

Here is the error I get:

[Error: SQLITE_ERROR: no such table: daily_deal
Emitted 'error' event on Statement instance at:
] {
  errno: 1,
  code: 'SQLITE_ERROR'
}

Node.js v17.9.0

I did a lot of research and I am stuck. I read to use Promise but it works partially. I am not sure how to tackle this problem.


Solution

  • After looking at the reference docs, of Database#run, you should pass a callback to the run method. Inside this callback, you want to either resolve or reject the promise depending on the outcome.

    await Promise((res, rej) => {
        db.run(..., (err, result) => {
            if (err) rej(err) else res(result)
        });
    });
    

    I think this is correct (untested however).