WiseLibs / better-sqlite3

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

identifying a better-sqlite3 Database object #1115

Closed punkish closed 3 months ago

punkish commented 7 months ago

I am writing a plugin wherein the user can pass in a readymade better-sqlite3 connection as an option. I want to test if the passed in option is indeed a better-sqlite3 connection. If it is, we work with it. If not, we create a new connection for the user. How can I do this? That is, how can I identify a passed in option to be a better-sqlite3 connection? consider simplified code like so

import Database from 'better-sqlite3';

function foo(option) {
    let db;

    if (!(option is a better-sqlite3 connection)) {   ← this is where I want help)
        db = new Database('./path/to/db');
    }

    // do other things
}

const db = new Database('./path/to/db');
foo(db);
neoxpert commented 7 months ago

Have you tried instanceof?

punkish commented 7 months ago

thanks. I think I know what is going on… my db connection is created in one file, and the plugin is in a different file like so

// file1.js
import Database from 'better-sqlite3';
const db = new Database('./path/to/db');
foo(db);

// file2.js
import Database from 'better-sqlite3';

function foo(option) {
    let db;

    if (option is a better-sqlite3 connection) {   ← this is where I want help)
        // do other things
    }
    else {
        db = new Database('./path/to/db');
    }

}

Because file2.js has a different instance of Database, the following evaluates to false

if (options instanceof Database) {     ← evaluates to false
    // do other things
}
else {
    db = new Database('./path/to/db');
}

The following seems to work but I am not sure if it is the right way to test

if (options.__proto__.constructor.name === 'Database') {     ← evaluates to true
    // do other things
}
else {
    db = new Database('./path/to/db');
}
neoxpert commented 6 months ago

To my knowledge that would be the best that you can get as the problem is not related to better-sqlite3 but the used programming language and runtime environment we are tied to here.

You might be able to attach some arbitrary value to a Database instance like

const db = new Database('./path/to/db');
db.valueOnlyIKnowAbout = 'Something'

and check for that, but in the end you won't get better than the things JavaScript and the interpretation environment will offer you.