Paozhu logoPaozhu Docs
Documentation
DEV

Advanced ORM patterns

Patterns that go beyond the basic CRUD page — multi-tag connections, read/write splitting, caching, batch writes, FK navigation, nested transactions and custom SQL.

1. Multi-tag orm.conf & connection routing

Declare more than one [tag] section in orm.conf. Generate models per-tag with paozhu_cli orm <tag>, then use orm::tag::ModelName to pick a database at runtime.

conf/orm.confini
[default]            # fallback tag
host = 127.0.0.1
port = 3306
...

[main]               # primary read/write
host = 10.0.0.11
port = 3306
dbtype = mysql
dbname = shop
user   = shop
password = secret
minpool = 5
maxpool = 20
pretable = pz_

[second]             # read replica
host = 10.0.0.12
port = 3306
dbtype = mysql
dbname = shop
user   = shop_r
password = secret_r
minpool = 2
maxpool = 10
pretable = pz_

[cms]                # content system on a different host
host = 127.0.0.1
port = 5432
dbtype = postgresql
dbname = cms
user   = cms
password = secret_pg

[lite]               # local SQLite (no daemon)
host = ./temp/local.db
dbtype = sqlite
user =
password =

After generating models for each tag (paozhu_cli orm main, paozhu_cli orm second, …), switch databases in code by swapping the namespace prefix:

controller/src/shop.cppcpp
// Write goes to main (primary)
orm::main::Order o;
o.userid = 42;
o.total  = 1990;
o.save();

// Read goes to second (replica)
auto rows = orm::second::Order()
    .where("userid", 42)
    .order("id", wq::desc)
    .page(1, 20, 100)
    .fetch();

2. Read/write splitting

For a cleaner approach, the ORM has built-in read/write splitting when you register a [main] tag and a [second] tag. All exec_*_read variants (select, count, sum, fetch) route to the read replica, while exec_*_write variants route to the primary.

3. Caching with ORM::use_cache()

Append .use_cache() to any read query to cache the result in Paozhu's in-process cache. Use is_hit_cache / effect() on the rowset to branch on whether the data came from cache or the DB.

controller/src/testormcache.cppcpp
// Implicit cache key — generated from query conditions
auto a = orm::cms::Article()
    .where("aid", 1)
    .where("isopen", 1)
    .use_cache()
    .fetch_one();
if (a.is_hit_cache()) {
    // came from cache
} else {
    // came from DB, cache will be populated
}

// Explicit named cache — useful for expensive aggregate queries
{
    orm::cms::Article::cache_result cr;
    bool hit = orm::cms::Article::try_get(
        "article:homepage:featured", cr);
    if (!hit) {
        auto rows = orm::cms::Article()
            .where("isopen", 1)
            .desc("aid")
            .limit(10)
            .fetch();
        orm::cms::Article::save_cache(
            "article:homepage:featured", rows, 30); // 30s TTL
        // copy rows into cr for downstream code
    }
}

4. Batch writes & arithmetic column updates

controller/src/test_ormprepared.cppcpp
// Insert one row directly (bypasses model field layer)
orm::cms::Article a;
a.title  = "Hello";
a.content = "World";
a.exec_insert();

// Batch insert — pass a vector of filled models
std::vector<orm::cms::Article> batch;
for (int i = 0; i < 500; ++i) {
    orm::cms::Article row;
    row.title  = "Batch " + std::to_string(i);
    row.content = "payload";
    batch.push_back(row);
}
a.exec_insert_batch(batch);

// Increment a counter in SQL — no round-trip fetch
orm::cms::Article()
    .where("aid", 1)
    .exec_update_col("viewnum = viewnum + 1");

// Conditional value replace
orm::cms::Article()
    .where("aid", 1)
    .exec_replace_col({"isopen"}, {1, 0});

5. Joins & FK navigation — full reference

Given a parent table Article and a child table Comment with Comment.aid referencing Article.aid.

controller/src/test_ormfk.cppcpp
// LEFT JOIN with group + aggregate
auto rows = orm::cms::Article()
    .leftJoin<orm::cms::Comment>()
      .joinOn("aid", "aid")
      .joinSelect("article.*, COUNT(comment.aid) AS cmt_cnt")
      .joinWhere("comment.isopen", 1)
      .joinGroup("article.aid")
      .joinDesc("cmt_cnt")
      .joinLimit(10)
    .fetch();

// Get the parent of a child (oneFkParent — outgoing FK)
auto comment = orm::cms::Comment()
    .where("cid", 99)
    .fetch_one();
auto parent_article = comment.oneFkParent<orm::cms::Article>();

// Get children of a parent (manyFkChild — incoming FK)
auto article = orm::cms::Article()
    .where("aid", 1)
    .fetch_one();
auto comments = article.manyFkChild<orm::cms::Comment>()
    .desc("cid").limit(20).fetch();

// Decorate a parent row with its FK children — one query returns everything
auto article2 = orm::cms::Article()
    .where("aid", 1)
    .fetch_one();
article2.manyFkChild<orm::cms::Comment>().decorate();
// article2.fk_data now contains the child rows as a property
Join methodWhat it does
leftJoin<T>() / innerJoin<T>()Start a join chain with another generated model type
joinOn("A", "B")ON clause columns (model.col = other.col)
joinSelect("...")SELECT clause override — useful for aliases and aggregates
joinWhere(cond, val)WHERE for the join (applies to the JOINed table)
joinGroup("col")GROUP BY inside the JOIN
joinOrder("col", wq::asc/desc)ORDER BY inside the JOIN
joinLimit(n)LIMIT the join result
oneFkParent<T>()Resolve the parent row pointed to by this row's FK columns
manyFkChild<T>()Start a child-row query filtered by this row's PK
.decorate()Attach child rows to the parent row so you don't have to merge manually

6. Nested transactions & commit_* SQL builders

Transactions can nest: the outermost begin_commit starts the real TX, inner ones are savepoints. Commit only takes effect on the outer layer.

controller/src/test_sql_commit.cppcpp
db_conn conn;
conn.tag = "main";
conn.connect();
conn.begin_commit();

try {
    // Outer insert
    orm::main::Order order;
    order.userid = 42;
    conn.commit_insert(order);            // builds INSERT + saves to TX buffer

    // Inner savepoint — rollback here doesn't cancel the outer TX
    conn.begin_commit();
    orm::main::OrderItem item;
    item.orderid = conn.lastid;
    item.sku = "sku_001";
    conn.commit_insert(item);
    conn.commit();                        // inner commit (savepoint release)

    // Update through the model, bound to this transaction's connection
    orm::main::User u;
    u.lock_conn(conn);                    // bind model to the TX connection
    u.where("userid", 42).exec_update_col("credit = credit - 1990");
    u.unlock_conn();

    conn.commit();                        // outer commit — flushes everything
} catch (...) {
    conn.rollback();
}

commit_insert / commit_update / commit_remove produce SQL strings on their own — call them before begin_commit to preview the SQL without executing it.

7. Raw SQL, prepared statements & custom structs

controller/src/testcrud.cppcpp
// Custom result struct — no ORM model required
struct UserRow {
    ORM_NAMES(userid, username, credit)  // macro to bind column names
    int    userid;
    string username;
    int    credit;
};

// Prepared query into a custom struct vector
db_conn conn;
conn.tag = "main";
conn.connect();
vector<UserRow> rows;
auto st = conn.prepare("SELECT userid, username, credit FROM pz_user WHERE credit > ?");
st.bind(1000);
conn.exec_fetch_to(st, rows);

// Async prepared — co_await-friendly
async_await conn.async_exec_fetch_to(st, rows);

8. Coroutine ORM — async_* methods

Every sync method on the ORM has an async_ variant. Coroutine ORM routes through the same connection pool but yields the current worker while waiting on I/O.

controller/src/test_ormfk.cppcpp
//@urlpath(null, async_article_list)
async_gen async_article_list(std::shared_ptr<httppeer> peer)
{
    auto rows = co_await orm::cms::Article()
        .where("isopen", 1)
        .desc("aid")
        .limit(20)
        .async_fetch();

    for (auto &a : rows) {
        co_yield a;                         // stream rows back to template
    }

    auto cnt = co_await orm::cms::Article()
        .where("isopen", 1)
        .async_exec_count();               // counter without materialising rows
    peer->get_peer() << "total: " << cnt;
}