yagil
yagil

Reputation: 83

Database client is not initialized when Connecting to Neon PostgreSQL

I'm currently working on a C++ project using the Drogon web framework, aiming to connect to a PostgreSQL database hosted on Neon. However, I'm encountering a persistent issue where the database client fails to initialize, and I'm unable to determine the root cause.

When attempting to initialize my database client, getDbClient() returns nullptr, indicating an unsuccessful connection attempt. This is confirmed by the error message: "Database client is not initialized".

Here's the relevant portion of my config.json for setting up the database client (password omitted for security):

"dbClients": [
  {
    "rdbms": "postgresql",
    "host": "ep-proud-hall-a29l37uu.eu-central-1.aws.neon.tech",
    "port": 5432,
    "dbname": "patrol_system",
    "user": "users_owner",
    "passwd": "[Password Omitted for Security]",
    "sslmode": "require",
    "filename": "",
    "isFast": false,
    "timeout": 5,
    "client_encoding": "UTF8"
  }
]

Function to Initialize Database Table

void AuthController::initUsersTable() {
    auto client = drogon::app().getDbClient();
    if (!client) {
        LOG_ERROR << "Database client is not initialized";
        return;
    }
    std::string createTableSql = R"(
        CREATE TABLE IF NOT EXISTS users (
            id SERIAL PRIMARY KEY,
            username VARCHAR(255) UNIQUE NOT NULL,
            password_hash VARCHAR(255) NOT NULL
        );
    )";
    client->execSqlAsync(
            createTableSql,
            [](const drogon::orm::Result& result) {
                LOG_INFO << "Table 'users' checked/created successfully.";
            },
            [](const drogon::orm::DrogonDbException& e) {
                LOG_ERROR << "Error checking/creating table 'users': " << e.base().what();
            }
    );
}

Here is how I invoke the initialization in my main function:

int main()
{
  LOG_DEBUG << "Server is running"
            << "\n";

  drogon::app().loadConfigFile("../config.json");

  AuthController::initUsersTable();

  drogon::app().run();

  return 0;
}

What I've Tried

Has anyone encountered a similar issue, or does anyone have insights on what might be causing this and how to resolve it?

Thanks in advance for your help!

Upvotes: 0

Views: 317

Answers (1)

Poll Star
Poll Star

Reputation: 1

Try to do it through a plugin

  • create a plugin with the command
    drogon_ctl create plugin AuthController
  • add your method initUsersTable() and add a call to the AuthController::initAndStart function
    AuthController::initUsersTable()
  • add lines to the config.json file
    "plugins": [
        {
        "name": "AuthController",
        "dependencies": [],
        "config": {
        }
        }
    ]

Upvotes: 0

Related Questions