#Passing sql connection between scripts as a global variable

16 messages · Page 1 of 1 (latest)

fair basalt

Heya, this isn't strictly a discord.js question, but I'm having a hard time finding a good answer searching the internet.

My bot uses a mysql connection to create and manage its database, but for readability I've sectioned out my sql functions into their own scripts. The issue I'm currently running into is that the 'sql' global variable I pass to those scripts using module.exports isn't initialized during compile time, so I get the error that 'sql.query()' cannot be read because it isn't a property of 'undefined'. I'd prefer not having to constantly pass 'sql' as a parameter into every method call if possible, but I'm not finding a good solution to assure js that the property will be defined during runtime

fair basalt

the relevant parts from my current code:
src/core.js


const initialize = function() {
    sql = connectDB();
    useDB();
};

// Conect to DB
const connectDB = function() {
    return mysql.createConnection({
        host: dbHost,
        port: dbPort,
        user: dbUser,
        password: dbPassword,
    });
};
// USE DB
const useDB = function() {
    sql.connect(function(err) {
        if (err) throw err;
        sql.query(''.concat('USE ', dbName, ';'), function(err) {
            if (err) throw err;
        });

        // Build database if empty
        sql.query('SHOW TABLES;', function(err, result) {
            if (err) throw err;
            console.log(result.length);
            if (result.length == 0) {
                databaseBuilder(sql);
            }
        });
        // @DEBUG: Rebuild Database on every launch
        databaseBuilder(sql);
    });
};

module.exports = { sql };```
**sql/userSQL.js**
```const { sql } = require('../src/core');

const getID = function(discordID) {
    sql.query(String.concat('SELECT User_ID FROM Users \
                WHERE Discord_ID = \'', discordID, '\';'),
    function(err, result) {
        if (err) throw err;

        if (result.length != 0) {
            return result[0].User_ID;
        }
        return null;
    });
};```
wise haven

Why don’t you have the connectDB function in the userSQL file too? Would make sense to have the database connection where you also use the connection.

Oh wait, I misunderstood… you have several files that run queries for different types of things, right?

fair basalt

correct

wise haven

Export a getDB() function from your core.js that returns the sql variable and import and use that in your subfiles. Exporting a let is not really a good idea (and not even possible in esm for that reason)

fair basalt

that is a good suggestion, guess I was overthinking this quite a bit haha

okay that is weird, I made the function

    return sql;
};```
and replaced every instance of ``sql.query()`` with ``getDB().query()`` and now the compiler complains with ``TypeError: getDB is not a function``
wise haven

Did you export/import it?

fair basalt

it's in module exports and I import it in the other script. the IDE also correctly identifies getDB as a function in the sql script

I also tried to change invoking it with

sql.query()```
but same difference
wise haven

Can you show how you export and import? And show the full error?

fair basalt

besides naming affected files this is the full extend of the error message

searching around, the error can be caused by circular dependency, but core.js doesn't import or call any methods from userSQL.js

wise haven

Can you show the full error please?

fair basalt

not sure how that error came out, but the root issue was with my setInterval and setTimeout functions it seems. putting just the function name into the callback seems to have caused issues, but changingt it to () => functionName() seems to have done the trick