better-sqlite3 icon indicating copy to clipboard operation
better-sqlite3 copied to clipboard

identifying a better-sqlite3 Database object

Open punkish opened this issue 2 years ago • 3 comments

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);

punkish avatar Dec 09 '23 21:12 punkish

Have you tried instanceof?

neoxpert avatar Dec 09 '23 22:12 neoxpert

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');
}

punkish avatar Dec 10 '23 09:12 punkish

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.

neoxpert avatar Dec 21 '23 21:12 neoxpert