drogonframework / drogon

Drogon: A C++14/17/20 based HTTP web application framework running on Linux/macOS/Unix/Windows
MIT License
11.52k stars 1.1k forks source link

Dynamic Creation Of SQLite3 Databases after drogon::app().run() executes #1151

Closed sardar01 closed 2 years ago

sardar01 commented 2 years ago

Scenario: We want to create new SQLite3 databases after the event loop starts. Say:

void test() {

    auto dbc = drogon::orm::DbClient::newSqlite3Client("filename=db/test.db", 5);

    auto dbPtr = drogon::app().getDbClient("db/test.db");

    ...

}

Evidently this fails since newSqlite3Client() must be executed before drogon::app().run() starts.

This negatives the ability to create databases at run-time. Is there a way around this? Thank you very much.

sardar01 commented 2 years ago

Please ignore. In Drogon it is possible to dynamically create a database independent of the framework and after the event loop starts. Here is the test code (not cleaned up):

// sample SQLite3 database is copied over to db/psingh.db but we can create schema dynamically with CREATE TABLE // once we have connection ptr;

inline optional<std::shared_ptr> v1::UserDb::getDbClient(const string& email) {

auto iter = db_map_.find(email);
if (iter != db_map_.end()) {
    return iter->second;
}

string db = "db/" + email + ".db";

try {

        auto dbc = drogon::orm::DbClient::newSqlite3Client("filename=db", 4);
        dbc.get()->execSqlSync( "INSERT INTO password (password, logged_in) VALUES ('abcdefg', 1);" );
       // cache connection
        db_map_.insert({email, dbc});
        return dbc;
}
catch(...) {
    LOG_ERROR << "failed to create connection to database for " << db;
    return nullopt;
}

}