Aegon

Database Config & Drivers

High-performance asynchronous PostgreSQL and SQLite drivers with thread-per-core connection pooling, libpq pipelining, and read-replica load balancing.

Aegon's SQL subsystem provides native, non-blocking asynchronous drivers for PostgreSQL and SQLite3, backed by a thread-per-core connection pool (PerCoreConnectionPool) and automated read-replica load balancing.

Designed specifically for modern microservices and high-throughput web applications, database operations run as non-blocking C++23 coroutines (co_await db.query(...)), integrating directly with Aegon's kernel event loop.


Configuration via SqlConfig

Configure database connections using SqlConfig with modern C++ designated initializers:

#include <aegon/data/orm/sql/SqlConfig.h>

using namespace aegon::data::orm::sql;

// 1. PostgreSQL Configuration
SqlConfig pg_config{
    .dialect = DatabaseDialect::PostgreSQL,
    .host = "127.0.0.1",
    .port = 5432,
    .database = "production_db",
    .user = "aegon_user",
    .password = "secret_password",
    .pool_per_core = 4 // 4 connections per worker thread / CPU core
};

// 2. SQLite Configuration (In-Memory or File-Based)
SqlConfig sqlite_config{
    .dialect = DatabaseDialect::SQLite,
    .database = "/var/data/app.db", // or ":memory:" for in-memory testing
    .pool_per_core = 2
};

SqlConfig Field Reference

FieldTypeDefaultDescription
dialectDatabaseDialectDatabaseDialect::SQLiteTarget database engine (PostgreSQL or SQLite).
hoststd::string"127.0.0.1"Database server hostname or IP address.
portuint16_t5432TCP port number (PostgreSQL default: 5432).
databasestd::string""Database name (PostgreSQL) or file path (SQLite).
userstd::string""Database username.
passwordstd::string""Database user password.
urlstd::string""Optional direct connection URI (e.g. "postgres://user:pass@host:5432/db"). Overrides individual fields if provided.
pool_per_coresize_t4Number of pre-allocated persistent connections per hardware thread.

Calling pg_config.to_conninfo() converts the struct into an RFC/libpq-compliant connection string:

host=127.0.0.1 port=5432 dbname=production_db user=aegon_user password=secret_password

Supported Database Engines

FeaturePostgreSQL (PostgresDriver)SQLite3 (SqliteDriver)
Engine ModelExternal network daemon via libpqEmbedded C library (sqlite3)
I/O ModelNon-blocking socket polling (epoll / io_uring)Fast in-process I/O with SQLITE_OPEN_NOMUTEX
ConcurrencyFull multi-client connection pool + pipeliningThread-per-core connection handles + WAL mode
Placeholder SyntaxNative positional ($1, $2, ...)Native positional (?1, ?2, ... or ?)
TransactionsBEGIN, COMMIT, ROLLBACK, SAVEPOINTBEGIN IMMEDIATE, COMMIT, ROLLBACK
Primary KeysRETURNING id auto-extractionsqlite3_last_insert_rowid()

1. PostgreSQL (drivers::PostgresDriver)

The PostgreSQL driver connects directly to PostgreSQL instances via libpq:

  • Event Loop Coroutine Polling: Non-blocking socket I/O registered directly on the worker thread's event loop (epoll or io_uring).
  • libpq Pipelining: Supports PostgreSQL 14+ pipeline mode (pipelined = true), allowing multiple SQL queries to be sent down the wire concurrently without blocking for roundtrip acknowledgments.
  • Parameterized SQL: Full support for native $1, $2, ... positional parameters and binary/text protocol decoding.
  • RETURNING Clauses: Automatically extracts auto-incremented primary keys and default timestamps in a single network roundtrip.
  • Pre-Registered Prepared Statements: Eliminates repeated query planning overhead by executing pre-compiled statements (PQexecPrepared).

2. SQLite3 (drivers::SqliteDriver)

The SQLite driver embeds the high-performance sqlite3 engine with zero external daemon dependencies:

  • Automatic WAL Mode: Automatically activates Write-Ahead Logging (PRAGMA journal_mode = WAL;) for maximum concurrency, enabling readers to execute simultaneously without blocking writers.
  • Foreign Key Constraints: Automatically enables PRAGMA foreign_keys = ON; upon connection initialization.
  • Thread-Per-Core Isolation: Every worker thread maintains independent, mutex-free SQLite connection handles opened with SQLITE_OPEN_NOMUTEX.
  • In-Memory Support: Supports ":memory:" databases for lightning-fast automated test suites and transient caching.

Per-Core Connection Pooling (PerCoreConnectionPool)

In traditional database drivers, multi-threaded applications share a single global connection pool protected by a mutex. Under high concurrency, cross-thread lock contention becomes the primary throughput bottleneck.

Aegon solves this with PerCoreConnectionPool:

[ Worker Thread 0 ] ──► Leases from Core 0 Pool (Zero lock contention)
[ Worker Thread 1 ] ──► Leases from Core 1 Pool (Zero lock contention)
[ Worker Thread 2 ] ──► Leases from Core 2 Pool (Zero lock contention)
[ Worker Thread 3 ] ──► Leases from Core 3 Pool (Zero lock contention)

Each hardware worker core manages an isolated, thread-local pool of persistent connections. When a coroutine executes a query, it acquires a connection exclusively from its current thread's pool using RAII ConnectionGuard:

#include <aegon/data/orm/sql/PerCoreConnectionPool.h>

// Acquired connection returns to the local pool automatically upon leaving scope
{
    ConnectionGuard guard = pool->acquire();
    Connection& conn = *guard;
    // Execute query...
}

Initializing the Client & Prepared Statements

PostgreSQL Pool with Prepared Statements

Pre-registering SQL queries avoids repeated string parsing and SQL planning on the PostgreSQL server:

#include <aegon/data/orm/sql/drivers/PostgresDriver.h>
#include <aegon/data/orm/sql/SqlDatabaseClient.h>

using namespace aegon::data::orm::sql;

// 1. (Optional) Define prepared statements
std::vector<PreparedStatementDef> prepared_stmts = {
    {
        .name = "find_products_by_price",
        .sql = "SELECT id, name, price FROM items WHERE price BETWEEN $1 AND $2 LIMIT $3"
    },
    {
        .name = "find_user_by_email",
        .sql = "SELECT id, email, username, balance FROM users WHERE email = $1 LIMIT 1"
    }
};

// 2. Create the per-core connection pool
auto primary_pool = drivers::create_postgres_pool(
    pg_config.to_conninfo(), 
    pg_config.pool_per_core,   // e.g. 4 connections per CPU thread
    true,                      // Enable libpq pipelining
    prepared_stmts             // Pre-register statements
);

// 3. Instantiate the SqlDatabaseClient
auto db = std::make_shared<SqlDatabaseClient>(*primary_pool);

SQLite Pool Initialization

#include <aegon/data/orm/sql/drivers/SqliteDriver.h>
#include <aegon/data/orm/sql/SqlDatabaseClient.h>

using namespace aegon::data::orm::sql;

// Create per-core SQLite pool (e.g. 2 connections per core)
auto sqlite_pool = drivers::create_sqlite_pool("/var/data/app.db", 2);

// Instantiate client
auto db = std::make_shared<SqlDatabaseClient>(*sqlite_pool);

Read-Replica Load Balancing

For high-read enterprise workloads, Aegon supports splitting read traffic across secondary replica pools while directing writes and transactions strictly to the primary write pool:

#include <aegon/data/orm/sql/SqlDatabaseClient.h>

// 1. Primary write pool
auto primary_pool = drivers::create_postgres_pool(primary_config.to_conninfo(), 4);

// 2. Secondary read-replica pools
auto replica_1_pool = drivers::create_postgres_pool(replica_1_config.to_conninfo(), 4);
auto replica_2_pool = drivers::create_postgres_pool(replica_2_config.to_conninfo(), 4);

// 3. Assemble replica list
std::vector<std::reference_wrapper<PerCoreConnectionPool>> replicas = {
    *replica_1_pool, 
    *replica_2_pool
};

// 4. Initialize client with primary + read replicas
auto db = std::make_shared<SqlDatabaseClient>(*primary_pool, replicas);

Automatic Routing Policy

  • SELECT Queries: Distributed across replica_1 and replica_2 in a lock-free round-robin sequence (rr_counter_.fetch_add(1)).
  • INSERT / UPDATE / DELETE: Directed strictly to primary_pool.
  • Transactions (db.transaction(...)): Executed entirely on the primary pool to guarantee read-your-own-writes consistency.

Automated DDL Migrations (sync_schema)

Aegon can inspect your compile-time C++ table<T>() definitions and automatically generate and execute the corresponding CREATE TABLE and CREATE INDEX DDL statements for the target database dialect:

#include <aegon/http/Server.h>
#include <aegon/data/orm/sql/SqlDatabaseClient.h>

using namespace aegon;

int main() {
    http::Server server;

    // Provide database client in ServiceRegistry
    server.provide(db);

    // Run schema synchronization during server startup
    server.on_start([](http::Server& s) -> core::Task<void> {
        auto db = s.service<data::orm::sql::SqlDatabaseClient>();

        std::cout << "Synchronizing database schema...\n";
        // Inspects User, Order, and Product schema definitions and executes DDL
        co_await db->sync_schema<User, Order, Product>();
        std::cout << "Schema synchronization complete.\n";

        co_return;
    });

    server.listen(8080);
    server.run();
}

Injecting into HTTP Request Handlers

Once provided to the Server, SqlDatabaseClient is instantly accessible inside every route handler via ctx.service<SqlDatabaseClient>():

server.router().get("/users/:id", [](http::Context& ctx) -> core::Task<void> {
    auto& db = ctx.service<data::orm::sql::SqlDatabaseClient>();
    auto id_str = ctx.req().param("id").value_or("");

    // Query entity asynchronously
    auto user = co_await db.from<User>()
                           .where(col(&User::id) == id_str)
                           .first();

    if (!user) {
        ctx.res().status(http::StatusCode::NotFound).problem(
            http::StatusCode::NotFound, "User Not Found", "No user found with the specified ID."
        );
        co_return;
    }

    ctx.res().json(*user);
    co_return;
});