WiseLibs / better-sqlite3

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

Failed to execute SQL with error: TypeError: The database connection is not open #1104

Closed idavollen closed 8 months ago

idavollen commented 8 months ago

I spent my night starting with better-sqlite3, however, I've got stuck with the simple code snippet.

import Database from 'better-sqlite3'
import * as fs from 'fs';
const db = new Database('tax.db', { verbose: console.log });
db.pragma('journal_mode = WAL');

fs.readFile('foobar.sql', 'utf8', function(err, data) {
    if (err) {
        console.error('failed to read tax.sql: ', err)
        throw err;
    }
    console.log('read SQL:', data)
    try {
        db.exec(data)
    } catch (err) {
        console.error('Failed to execute SQL with error:', err)
    }

});

db.close()

The foobar.sql just contains SQL for initially creating two tables:

CREATE TABLE IF NOT EXISTS EMP (
   ID                   INT PRIMARY KEY AUTOINCREMENT,
   FULLNAME             CHAR(50) NOT NULL,
   BIRTHYEAR            INT      NOT NULL,
   POSTPLACE            CHAR(50),
   CREATED              datetime default current_timestamp
);

CREATE TABLE IF NOT EXISTS SAL (
   ID                   INT PRIMARY KEY AUTOINCREMENT,
   INCOME               REAL NOT NULL,
   YEAR                 INT NOT NULL,
   TAXPLACE             CHAR(50),
   UPDATED              datetime default current_timestamp,
   TAXEE_ID             INT NOT NULL REFERENCES EMP
);

My personal experiences of my initial playing with better-sqlite3 in three hours is that it lacks of good enough tutorials/documentations, why not make some code examples for those APIs helping new beginners to start with. When I googled that error message in the title, there are not too many hits. A good documentation will definitely help better-sqlite3 to speed up its popularity over node-sqlite3, IMHO

Failed to execute SQL with error: TypeError: The database connection is not open at Database.exec (/Users/dupapa/tmp/appiumjs/skatte/node_modules/better-sqlite3/lib/methods/wrappers.js:9:14) at file:///Users/hallo/myapp/internal/db-init.js:13:12 at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read/context:68:3)

mceachen commented 8 months ago

The error is precisely correct. You're closing the db immediately after scheduling the fs.readFile.

If you want to close the db, you need to do it in your callback, after you run your db.exec().

It might help to go through a tutorial or two on how node schedules callbacks--as this shows, it can be decidedly confusing!

idavollen commented 8 months ago

Thanks! It's my bad! it now works well after calling db.close() in the try-finally block. Before starting with better-sqlite3, I've investigated a lot and read diff between node-sqlite3 and the better-sqlite3, in brief async against sync. While trying better-sqlite3, my head is full of sync and have forgotten the async fs.readFile() :)