I'm working on an API written in rust, the API connects to a MySql database and does some basic read/writes to it.To make it as simple as possible, this is approximately what the two relevant rust functions do
#[no_mangle]
pub unsafe extern "C" fn Init()
{
const DB_CREDENTIALS: DatabaseCredentials<'static> = DatabaseCredentials {
username: "root",
password: "password",
host: "localhost",
port: "3306"
};
let rt = Runtime::new().unwrap();
let handle = rt.handle();
let dbms = handle.block_on(async {
return DBMS::connect_with_credentials(DB_CREDENTIALS).await.unwrap();
});
handle.block_on(async {
return dbms.ensure_database("test_db").await.unwrap();
});
let db = handle.block_on(async {
return dbms.connect_database("test_db").await.unwrap();
});
}
and
#[no_mangle]
pub unsafe extern "C" fn SaveValues(container_struct: &container)
{
db.insert_table(container); //NEED db from the Init function
}
Both of these functions are exported to a DLL file and called from typescript with node-ffi like this
var ffi = require('ffi-napi');
const quancy = ffi.Library('D:/Program files/node/sdk/src/framework.dll', {
"Init":["void",[]],
"SaveValues":["int", [container_pointer/*Don't worry about what this pointer is exactly stack overflow */]]
});
The problem is that I need the db variable from the init function in the SaveValues function. I can't return it as a reference because it isn't FFI safe and I can't create an identical struct in typescript. There aren't really any global variables in rust either, so how can I do this?
I tried using lazy_static in rust to make the db variable global. That doesn't seem to work because there isn't a default constructor for the database.
lazy_static!{ static ref db : DBConn<MySql> = None; //error }
Here's the DBConn struct:
pub struct DBConn<DB: Database> {
pub connection: Pool<DB>,
pub credentials: DatabaseCredentials<'static>,
pub current_database: &'static str,
}
I know that assigning it to None isn't supposed to work, but I don't know what to assign it to which would work. It seems to get compilable values to Pool you need to call connect_database or something like that, which I don't want to do before Init function.