DEV
高级 ORM 模式
超出基础 CRUD 的常见模式:多标签连接、读写分离、缓存、批量写入、外键导航、嵌套事务与自定义 SQL。
1. orm.conf 多标签与连接路由
在 orm.conf 中声明多个 [tag] 段。用 paozhu_cli orm <tag> 按标签生成模型,运行时通过 orm::tag::ModelName 选择目标数据库。
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 =为每个 tag 生成模型后(paozhu_cli orm main、paozhu_cli orm second …),在代码里切换命名空间前缀即可切换数据库:
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. 读写分离
更简洁的方式是:只要同时注册了 [main] 和 [second] 两个标签,ORM 就会自动开启读写分离。所有 exec_*_read 变体(select、count、sum、fetch)走读库,exec_*_write 变体走主库。
3. ORM::use_cache() 缓存
在任意读查询后追加 .use_cache(),结果会被缓存到 Paozhu 的进程内缓存。对返回的 rowset 可以用 is_hit_cache / effect() 判断数据来自缓存还是数据库。
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. 批量写入与列式运算更新
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. JOIN 与外键导航完整参考
假设父表为 Article,子表为 Comment,Comment.aid 引用 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 方法 | 作用 |
|---|---|
leftJoin<T>() / innerJoin<T>() | 用另一个生成的模型类型开启 JOIN 链式调用 |
joinOn("A", "B") | ON 子句列名(model.col = other.col) |
joinSelect("...") | 覆盖 SELECT 子句 — 别名与聚合场景特别好用 |
joinWhere(cond, val) | JOIN 内的 WHERE 条件(作用在被 JOIN 的表上) |
joinGroup("col") | JOIN 内的 GROUP BY |
joinOrder("col", wq::asc/desc) | JOIN 内的 ORDER BY |
joinLimit(n) | 限制 JOIN 结果条数 |
oneFkParent<T>() | 通过当前行的外键找到被引用的父行 |
manyFkChild<T>() | 用当前行的主键过滤子行,开启一个子查询 |
.decorate() | 把查询到的子行挂到父行上,避免手动合并结果集 |
6. 嵌套事务与 commit_* SQL 构建器
事务可以嵌套:最外层的 begin_commit 开启真实事务,内层的都只是 savepoint。只有外层 commit 才会真正提交。
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 本身会返回 SQL 字符串 —— 在 begin_commit 之前调用它们,就能不执行 SQL 直接预览最终拼接出来的语句。
7. 原生 SQL、预编译语句与自定义结构体
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. 协程 ORM — async_* 方法
ORM 的每个同步方法都有对应的 async_ 版本。协程 ORM 走同一个连接池,遇到 I/O 会让出当前 worker,避免阻塞。
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;
}