Search code examples
postgresqllibpqxxcockroachdb

libbqxx C++ API to connect to PostgreSQL without DB name


I am using libpqxx C++ client API for PostgreSQL as the driver on cockroachDB. From cockroachDB doc:

pqxx::connection c("postgresql://maxroach@localhost:26257/bank")

This requires user and database as precondition. Are there any C++ APIs to separate this into two steps as below ?

1) First connect just with user.
2) create data base.

I have tried the below code, but it failed as it needs root user privileges.

void roachDB::createDB(const string &dbName)
{
    pqxx::nontransaction w(roachDBconn);
    w.exec("CREATE DATABASE " + dbName);
    w.commit();
}

Thanks for your help!

======= Edit 1 : Working code based on @clemens tip ===========

void roachDB::createDB(const string &dbName, const string &user)
{
    pqxx::connection c("postgresql://root@localhost:26257/template1");
    pqxx::nontransaction w(c);
    try {
        w.exec("CREATE DATABASE " + dbName);
    } catch (pqxx::sql_error &e) {
        string sqlErrCode = e.sqlstate();
        if (sqlErrCode == "42P04") { // catch duplicate_database
            cout << "Database: " << dbName << " exists, proceeding further\n";
            c.disconnect();
            return;
        }
        std::cerr << "Database error: " << e.what()
            << ", error code: " << e.sqlstate()
            << "SQL Query was: " << e.query() << "\n";
        abort();
    }
    w.exec("GRANT ALL ON DATABASE " + dbName + " TO " + user);
    w.commit();
    c.disconnect();
}

Solution

  • It isn't possible to connect to the Postgres server without specifying a database. But there is always the database template1 which you may use for your purposes. So, connect with

    pqxx::connection c("postgresql://maxroach@localhost:26257/template1")
    

    and create your new database with that connection.

    You should also grant maxroach the privilege to create databases with:

    GRANT CREATE DATABASE TO maxroach;
    

    But this must be executed by a database user with superuser privileges (e.g. postgres).