Skip to content
Aditya Bhalsod
← Web
WebAdvanced

Running One C Backend on PostgreSQL, MySQL and SQLite With Two Vtables

How headless-cms runs one C11 backend against PostgreSQL, MySQL or SQLite with a driver vtable, a SQL dialect vtable and string-only query parameters.

  • #c
  • #databases
  • #orm
  • #postgresql
  • #sqlite
Contents
  1. What "zero framework" means here
  2. Layer one: a vtable per driver
  3. Every parameter is a string
  4. Layer two: a vtable per SQL dialect
  5. Getting the new row's ID back
  6. Where the split leaks, and what I would change

headless-cms is a self-hosted, Strapi-style headless CMS. The backend is C11, compiled with gcc into one native binary. The admin panel is a React 19 and TypeScript app built with Vite, and content types you define there become real database tables at runtime.

The part I want to write about is the database layer. The same binary runs against PostgreSQL, MySQL/MariaDB or SQLite, chosen by DB_DRIVER in config.json. There is no ORM library underneath, so all of that portability is hand-written C, and the way it is split up is a pattern you can reuse in any language.

What "zero framework" means here

It means no web framework and no ORM library. It does not mean no dependencies. The Makefile always links libpq, libmicrohttpd, OpenSSL (-lssl -lcrypto), libsodium, cJSON, jansson, libb64, libuuid, pthread and libm. It adds SQLite and the MariaDB/MySQL client library when pkg-config or mariadb_config finds them.

HTTP parsing and connection handling come from libmicrohttpd: server.c calls MHD_start_daemon. What I wrote by hand sits above that: the router and middleware, the endpoint handlers, the ORM and its migration system, and the JWT code built on OpenSSL's HMAC.

Layer one: a vtable per driver

The lowest layer is db_adapter_t, a struct of function pointers in adapter.h. Each engine fills one in, in postgres.c, mysql.c and sqlite.c.

C
typedef struct db_adapter {
    const char *name;
    db_driver_type_t driver_type;

    db_connection_t *(*connect)(db_config_t *config);
    db_result_t *(*query)(
        db_connection_t *conn,
        const char *sql,
        db_param_t *params,
        int param_count
    );
    int (*begin_transaction)(db_connection_t *conn);
    db_row_t *(*result_fetch_row)(db_result_t *result);
    uint64_t (*last_insert_id)(db_connection_t *conn);
    /* plus disconnect, ping, execute, commit, rollback, ... */
} db_adapter_t;

A connection carries a pointer to its adapter and an opaque void *handle. The public db_query, db_execute and the rest in db.c check that pointer and forward the call, so the ORM and the endpoints call db_* functions instead of libpq, MySQL or SQLite APIs.

The engine is chosen twice. At build time, the Makefile drops sqlite.c or mysql.c when the library is missing, and db_adapter_for_driver wraps those cases in #ifdef WITH_MYSQL and #ifdef WITH_SQLITE. PostgreSQL is always compiled in. At run time, main.c maps the DB_DRIVER string to an enum and hands it to orm_set_active_driver.

Every parameter is a string

The adapters agree on exactly one parameter format, db_param_t: a const char *value, a length and an is_null flag. Integers, booleans, floats and timestamps are all converted to text before they reach a driver, in orm_convert_to_db_value. That lowest common denominator is what lets three client libraries with very different binding APIs share one function signature:

  • PostgreSQL passes the array to PQexecParams with every parameter format set to text.
  • SQLite binds each value with sqlite3_bind_text, or sqlite3_bind_null.
  • MySQL does not use mysql_stmt_* binding. The adapter walks the SQL, swaps each ? for an escaped, single-quoted literal and sends the result with mysql_real_query.
C
for (const char *cursor = sql; *cursor; cursor++) {
    if (*cursor == '?' && param_index < param_count) {
        db_param_t *param = &params[param_index++];
        /* NULL check and buffer allocation trimmed */
        unsigned long escaped_len = mysql_real_escape_string(
            mysql, escaped, param->value, (unsigned long) value_len);

        bool ok =
            mysql_adp_buf_append(&out, &out_len, &capacity, "'", 1)
            && mysql_adp_buf_append(&out, &out_len, &capacity, escaped, escaped_len)
            && mysql_adp_buf_append(&out, &out_len, &capacity, "'", 1);
        /* error handling trimmed */
        continue;
    }
    /* every other character is copied through unchanged */
}

The comment above that function explains why quoting every value is safe: MySQL converts quoted literals for numeric columns.

Text parameters also force decisions about values one engine rejects. A zero time_t goes out as NULL because, as the comment in result.c says, 1970-01-01 is outside MySQL's TIMESTAMP range and strict mode rejects it.

Layer two: a vtable per SQL dialect

The SQL text differs too, so the ORM has a second struct, ORM_Dialect in dialect.h. It holds function pointers for placeholders, identifier quoting, type mapping, DDL and JSON access. A few of the differences it hides:

ConcernPostgreSQLMySQLSQLite
Placeholder$1, $2??
Identifier quotingdouble quotesbackticksdouble quotes
Auto-increment INTSERIALINT AUTO_INCREMENTINTEGER
Boolean columnBOOLEANTINYINT(1)INTEGER
JSON columnJSONBJSONTEXT
JSON field readdata->>'title'JSON_EXTRACT(data, '$.title')json_extract(data, '$.title')

schema_builder.c calls dialect->map_type for every column it creates, and the dynamic content-type migrations go through that builder. A boolean field defined in the admin becomes BOOLEAN on PostgreSQL, TINYINT(1) on MySQL and INTEGER on SQLite without the migration code knowing which.

Content entries keep their field values in a JSON data column, and filtering uses the dialect's JSON accessor. That accessor writes the field name straight into SQL with snprintf, so content_query.c checks the name against the content type's schema first:

C
cJSON *field_def = find_schema_field(schema, field_name);
if (!field_def) {
    snprintf(error_msg, error_size, "Unknown filter field '%s'", field_name);
    return -1;
}

ORM_Dialect *dialect = orm_get_dialect(orm_active_driver());
char *expr = dialect->generate_json_access("data", field_name);

Getting the new row's ID back

Inserts use a capability check instead of a driver check. db_driver_supports_returning returns true only for PostgreSQL. The INSERT builder in executor.c appends RETURNING when it can, and the caller falls back to the adapter when no ID came back:

C
// RETURNING clause (PostgreSQL only)
if (db_driver_supports_returning(orm_active_driver())) {
    ORM_Field *pk = get_primary_key_field(model);
    if (pk != NULL && (pk->constraints & ORM_AUTO_INCREMENT)) {
        buffer_append(&sql, &sql_size, &sql_capacity, " RETURNING ");
        buffer_append(&sql, &sql_size, &sql_capacity, pk->name);
    }
}

/* later, after the INSERT has run */
if (insert_id < 0) {
    insert_id = (int64_t) db_last_insert_id(pooled_conn->conn);
}

Behind db_last_insert_id, MySQL calls mysql_insert_id, SQLite calls sqlite3_last_insert_rowid and PostgreSQL runs SELECT lastval(). Asking "does this engine support X" ages better than asking "which engine is this", because a new engine means answering the question once.

Where the split leaks, and what I would change

The two-vtable split is the part I would keep. The adapter changes when a client library changes, the dialect changes when syntax differs, and keeping them apart stops one from dragging the other along. String-only parameters are what make the adapter signature possible, at the cost of losing type information at the boundary. That cost comes back as small rules like "zero timestamp means NULL".

The abstraction is not airtight. content_relation.c asks the dialect for placeholders, but executor.c and query.c each have a static helper that compares the dialect name to "postgresql" and picks $N or ? itself. Timestamps differ as well: orm_format_timestamp_param sends epoch integers to SQLite and %Y-%m-%d %H:%M:%S strings to the other two.

Schema changes are where it really stops. SQLite cannot change a column's type or add a foreign key with ALTER TABLE, so schema_builder.c turns both into logged no-ops on SQLite, and the comment says referential integrity is then checked in the application layer. That is a reasonable call, but it means the same migration does not give the same schema on every engine.

The two changes I would make next are routing every placeholder through the dialect and moving the MySQL adapter to prepared statements. The pytest suite can already run against each engine with node setup.js test --db=all, which is the only way a three-database promise stays true.

Found this useful? Share it with your team.

Keep reading

More from Web and beyond