Skip to content
Plaristote edited this page Apr 12, 2016 · 6 revisions

Databases with Crails

Crails is agnostic when it comes to databases. The only thing we provide is a tool to easily manage database configuration between several environments (production, development, test), and a tool to get a handle on a database connection.

This makes sense, because you should only maintain one connection per thread to a given database. Our CRAILS_DATABASE macro takes care of that, by returning a thread_local instance of a database, and triggering the connection if it hasn't been done yet.

Settings

Your database settings are stored in the config/databases.cpp file. Here's a sample of what it may look like:

const Databases::Settings Databases::settings = {
  {
    "production", {
      "my_sql_db", {
        { "type", "pgsql" },
        { "host", std::getenv("PGSQL_HOST") },
        { "name", std::getenv("PGSQL_NAME") },
        { "user", std::getenv("PGSQL_USER") },
        { "password", std::getenv("PGSQL_PASSWORD") }
      }
    },
    "development", {
      "my_sql_db", {
        { "type", "sqlite" },
        { "name", "mysqldb" }
      }
    },
    "test", {
    }
  }
};

Interacting with a configured database from your code

If you wanted to interact with the my_sql_db described in your code, you would get its handle using our CRAILS_DATABASE macro:

DataTree route_endpoint(Crails::Params& params)
{
  auto& database = CRAILS_DATABASE(ODB, "my_sql_db");

  // ...
}

The parameters for the CRAILS_DATABASE macro are the back-end to use (here, ODB), and the name of the configuration we want to load (here, "my_sql_db", as described in the previous chapter). The environment will be selected from the value of the Crails::environment global variable.

The value returned depends on the database backend you've selected. For more details, see the next section by chosing the type of backend you want to use:

Hot plugging of new databases

If you want to connect to a database that isn't defined in the config/databases.cpp file, you may also use the CRAILS_DATABASE_FROM_SETTINGS macro:

DataTree route_endpoint(Crails::Params& params)
{
  auto& database = CRAILS_DATABASE_FROM_SETTINGS(ODB, "unique_database_identifier", {
    {"type", "sqlite"},
    {"name", "db_name"}
  });
  // ..
}

Make sure each different configuration has a different identifier. If an existing database with the same identifier is found, it will be returned and your configuration will be ignored.