ORM & CRUD
From database config to model generation, then CRUD, pagination, joins, transactions and async operations.
1. Configure the database
Each section in conf/orm.conf is a tag. type = main is the write pool and type = second the optional read pool. dbtype supports mysql, postgresql and sqlite. Every tag can have a main pool alone, or both pools for read/write splitting.
1.1 Create the database and user
MySQL
CREATE DATABASE hello_world DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'benchmarkdbuser'@'localhost' IDENTIFIED BY 'benchmarkdbpass';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP
ON hello_world.* TO 'benchmarkdbuser'@'localhost';
FLUSH PRIVILEGES;PostgreSQL
CREATE USER hello WITH PASSWORD '12345678';
CREATE DATABASE hello_world OWNER hello ENCODING 'UTF8';
-- after connecting to the new database:
GRANT ALL ON SCHEMA public TO hello;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO hello;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO hello;SQLite (zero configuration)
No SQL, no server. Just point host at the .db file you want to use — it is created on first open.
1.2 Complete conf/orm.conf example
[default]
type = main
host = 127.0.0.1
port = 3306
dbname = hello_world
user = benchmarkdbuser
password = benchmarkdbpass
pretable =
minpool = 1
maxpool = 5
dbtype = mysql
charset = utf8mb4
#ssl=ON
#sslverify=ON
#sslhost=db.example.com
type = second
host = 127.0.0.1
port = 3306
dbname = hello_world
user = benchmarkdbuser
password = benchmarkdbpass
pretable =
minpool = 5
maxpool = 20
dbtype = mysql
charset = utf8mb4
[cms]
type = main
host = 127.0.0.1
port = 3306
dbname = cppcms
user = root
password = 12345678
pretable =
minpool = 1
maxpool = 16
dbtype = mysql
charset = utf8mb4
[pg]
type = main
host = 127.0.0.1
port = 5432
dbname = hello_world
user = hello
password = 12345678
pretable =
minpool = 1
maxpool = 5
dbtype = postgresql
charset = utf8
[lite]
type = main
host = /Users/hzq/paozhu/docs/sqlite_lite.db
port =
dbname = lite
user =
password =
pretable =
minpool = 1
maxpool = 5
dbtype = sqlite
charset = utf8mb41.3 All configuration keys
| Key | Required | Meaning |
|---|---|---|
type | Yes | main (write pool) or second (read pool) |
dbtype | Yes | mysql, postgresql, or sqlite |
host | Yes | Hostname or IP; for SQLite the absolute .db file path |
port | Yes (empty SQLite) | MySQL 3306, PostgreSQL 5432, empty for SQLite |
dbname | Yes | Database name; logical label for SQLite |
user | Yes (empty SQLite) | Database username |
password | Yes (empty SQLite) | Database password |
charset | Recommended | utf8mb4 for MySQL, utf8 for PostgreSQL |
minpool | Yes | Minimum connections kept alive in the pool |
maxpool | Yes | Maximum connections in the pool |
pretable | No | Table name prefix applied to every generated table |
ssl | No | ON / OFF — enable TLS on the connection |
sslverify | No | ON — verify the server certificate chain |
sslhost | No | Certificate domain for SNI and hostname checks; falls back to host |
2. Generate models
The CLI reads each tag from conf/orm.conf, introspects every table in that database, and writes three layers of C++ files.
# one tag = one database section
./bin/paozhu_cli orm default # MySQL [default]
./bin/paozhu_cli orm cms # MySQL [cms]
./bin/paozhu_cli orm pg # PostgreSQL [pg]
./bin/paozhu_cli orm lite # SQLite [lite]
# Regenerate after editing a template in:
# vendor/httpserver/include/mysqlorm.hpp
# vendor/httpserver/include/postgresqlorm.hpp
# vendor/httpserver/include/sqliteorm.hpp2.1 Generated file layout
orm/cms/include/article_base.h # cols enum, meta struct, table name, PK name
orm/cms/include/article_opsql.h # full where/fetch/save/update/remove/page + prepared APIs
orm/cms/article_opsql.cpp # FK accessors: oneFkParent() / manyFkChild()
models/cms/include/Article.h # business shell (created once, never overwritten)
models/cms/Article.cpp # constructor bound to the "cms" tag2.2 Business shell example
#include "orm/cms/include/article_opsql.h"
#include "orm/cms/include/article_base.h"
namespace orm { namespace cms {
class Article : public article_opsql<Article, article_base> {
public:
Article(std::string dbtag_); // use a custom tag
Article(); // default to the "cms" tag
// add your own helpers here — this file is yours
int recent_count(int userid);
bool update_visibility(unsigned int aid, unsigned char open);
};
}}3. Read
3.1 fetch_one() vs exec_one()
Both load exactly one row into data. Use fetch_one() for regular queries; use exec_one() when the query should go through the prepared-statement cache. The current sample login route uses exec_one().
// regular path — parameter binding, no statement cache
auto articles = orm::cms::Article();
articles.select("title", "content")
.where("isopen", 1)
.where("aid", aid)
.fetch_one();
client.val["title"] = articles.getTitle();
client.val["content"] = articles.getContent();
// prepared path — goes through exec_* family, cached on the connection
auto users = orm::cms::Sysuser();
users.where("name", username)
.whereAnd("password", md5string)
.whereAnd("isopen", 1)
.exec_one();
if (users.getAdminid() > 0) { /* logged in */ }3.2 List and pagination
page(page, per_page, list_num) internally runs a COUNT(*), sets the LIMIT / OFFSET, and returns a 4-tuple that describes the pagination bar.
auto articles = orm::cms::Article();
articles.where("isopen", 1);
auto [bar_min, bar_max, current_page, total_page] = articles.page(page, 10, 5);
// bar_min — first page shown in the bar
// bar_max — last page shown in the bar
// current_page — page clamped into [0, total_page)
// total_page — total page count (COUNT / per_page rounded up)
articles.order("aid", "desc").fetch();
client.val["pageinfo"]["min"] = bar_min;
client.val["pageinfo"]["max"] = bar_max;
client.val["pageinfo"]["current"] = current_page;
client.val["pageinfo"]["total"] = total_page;
client.val["list"].set_array();
obj_val item;
for (auto &row : articles) {
item["aid"] = row.aid;
item["title"] = row.title;
item["createtime"] = row.createtime;
client.val["list"].push(std::move(item));
}3.3 Select specific columns
Without a select(...) call the ORM loads every column defined in the field layer. Passing column names to select reduces bandwidth and avoids loading blobs you do not need.
auto artmodel = orm::cms::Article();
artmodel.where("userid", client.session["userid"].to_int())
.desc("aid")
.select("aid,topicid,title,createtime,sortid,isopen,ishome")
.fetch();
for (auto &item : artmodel.record) {
tempa["title"] = item.title;
tempa["aid"] = item.aid;
}4. Condition building DSL
4.1 Basic where()
where(col, value) defaults to equality. Pass the operator explicitly for anything else.
// equality — two args
model.where("userid", 123).fetch();
// equality — three args, explicit wq::eq
model.where("userid", orm::wq::eq, 123).fetch();
// equality — typed cols enum (catches typos at compile time)
model.where(orm::cms::article_info::cols::userid, 123).fetch();4.2 wq operators enum
| Operator | SQL | Example |
|---|---|---|
orm::wq::eq | = | where("id", wq::eq, 1) |
orm::wq::nq | != | where("status", wq::nq, 0) |
orm::wq::bt | > | where("age", wq::bt, 18) |
orm::wq::lt | < | where("price", wq::lt, 100) |
orm::wq::be | >= | where("rating", wq::be, 3) |
orm::wq::le | <= | where("count", wq::le, 10) |
orm::wq::like | LIKE | where("title", wq::like, "%paozhu%") |
orm::wq::nlike | NOT LIKE | where("title", wq::nlike, "beta%") |
orm::wq::in | IN (...) | where("id", wq::in, ids_vector) |
orm::wq::nin | NOT IN (...) | where("id", wq::nin, blocked) |
4.3 Grouped conditions
Use andsub() / orsub() / endsub() to build nested AND (...) and OR (...) groups.
auto world = orm::World();
world.AND("id", orm::wq::be, 1)
.AND("id", orm::wq::le, 200)
.orsub()
.AND("randomnumber", orm::wq::bt, 5000)
.OR("randomnumber", orm::wq::lt, 200)
.endsub();
// WHERE id >= 1 AND id <= 200 AND (randomnumber > 5000 OR randomnumber < 200)4.4 Generated beAid() / ltAid() / eqName()
Every column gets a full set of short operators generated. These are the fastest way to write conditions because the column name is resolved at compile time.
auto world = orm::World();
world.btId(2).ltId(6);
// WHERE id > 2 AND id < 6
world.beIsopen(1)
.btAid(0)
.andsub()
.likeTitle("paozhu")
.orlikeContent("paozhu")
.endsub()
.desc(orm::cms::article_info::cols::aid)
.limit(5)
.fetch();4.5 whereIn / whereLike / whereOrLike
Convenience methods common in search and admin screens. whereIn accepts a vector of values or a comma-separated SQL literal. whereLike wraps the value in % wildcards.
std::vector<unsigned int> topic_ids = {1, 3, 7};
artmodel.whereIn("topicid", topic_ids);
// combine sub-groups in an admin search:
artmodel.andsub()
.whereLike("title", str_addslash(searchword))
.whereOrLike("content", str_addslash(searchword))
.endsub();5. Create, update, delete
5.1 save() vs insert()
save() decides for you: if the primary key is already set it issues an UPDATE, otherwise an INSERT. insert() always issues an INSERT, regardless of the current PK value.
// INSERT path — PK is 0 or unset
auto articles = orm::cms::Article();
articles.setIsopen(1);
articles.setCreatetime(get_date("%Y-%m-%d %X"));
articles.setAddtime(timeid());
articles.setTitle(title);
articles.setContent(content);
auto [effectnum, last_id] = articles.save();
// articles.getAid() == last_id after a successful insert
// UPDATE path — PK already set
articles.setAid(42);
articles.setTitle("updated");
auto [ueffect, uid] = articles.save(); // issues UPDATE WHERE aid = 42
// insert() always inserts
auto [ieffect, newid] = articles.insert();5.2 update("cols") vs update_dirty()
update("title,content") only updates the columns you name. update_dirty() updates every field that has been touched by a setter.
artmodel.data.title = client.post["title"].to_string();
artmodel.data.content = client.post["content"].to_string();
artmodel.where("aid", aid);
// explicit column list — safest
int effectnum = artmodel.update("title,content");
// update all dirty columns
int effectnum2 = artmodel.update_dirty();5.3 remove() variants
Delete by primary key with remove(pk), or delete with conditions by chaining where(...).remove().
auto artmodel = orm::cms::Article();
// by PK directly
unsigned int tempid = artmodel.remove(aid);
// with extra safety conditions — also removes multiple rows
artmodel.where("userid", userid).whereAnd("aid", aid).remove();5.4 Bulk insert — exec_insert_batch()
Fill record with meta structs, then call exec_insert_batch(). The ORM emits a single INSERT INTO ... VALUES (...), (...), (...) statement.
auto batch = orm::cms::Testa();
for (unsigned int i = 0; i < 3; i++) {
orm::cms::testa_info::meta row;
row.parentid = 8;
row.content = "batch row " + std::to_string(i);
batch.record.push_back(std::move(row));
}
auto [batch_effect, first_id] = batch.exec_insert_batch();
// batch_effect — affected row count
// first_id — first auto-generated PK (MySQL/SQLite) or last PK returned (PostgreSQL)5.5 Arithmetic update — exec_update_col()
Use exec_update_col(column, delta, '+') to issue UPDATE ... SET col = col + delta WHERE .... Supports +, -, *, /.
auto one = orm::cms::Testa();
one.where(orm::cms::testa_info::cols::id, newid);
one.exec_update_col("parentid", 3, '+');
// UPDATE testa SET parentid = parentid + 3 WHERE id = ?
one.exec_update_col("readnum", 1, '+');
// UPDATE testa SET readnum = readnum + 1 WHERE id = ?5.6 Conditional replace — exec_replace_col()
exec_replace_col(col, old_value, new_value) is a lightweight wrapper around REPLACE(col, old, new). Useful for string cleanups and mass replacements.
auto one = orm::cms::Testa();
one.where(orm::cms::testa_info::cols::id, newid);
one.exec_replace_col("content", "prepared", "replaced");
// UPDATE testa SET content = REPLACE(content, 'prepared', 'replaced') WHERE id = ?| Method | Behavior |
|---|---|
save() | UPDATE when PK is set, otherwise INSERT |
insert() | Always INSERT; supports row, meta and vector<meta> |
insert(rows) | Insert a vector of meta rows in one call |
update("a,b") | Update only listed columns |
update_dirty() | Update fields marked dirty by setters |
remove(pk) | Delete by PK, or call remove() after where() |
exec_insert_batch() | Insert all record rows with a single prepared INSERT |
exec_update_col("col", n, '+') | Issue col = col + n arithmetic update |
exec_replace_col("col", "old", "new") | Issue REPLACE(col, old, new) update |
6. Joins
Paozhu ORM supports leftJoin and innerJoin with a fluent chain of joinOn, joinSelect, joinWhere, joinGroup, joinDesc, joinLimit.
6.1 LEFT JOIN
auto world = orm::World();
world.btId(2).ltId(6);
world.select("id,randomnumber");
world.leftJoin<orm::Fortune>()
.joinOn("id", "id") // left.col, right.col
.joinSelect("message"); // extra columns from the joined table
world.fetch();
// SELECT world.id, world.randomnumber, fortune.message
// FROM world LEFT JOIN fortune ON world.id = fortune.id
// WHERE world.id > 2 AND world.id < 66.2 INNER JOIN with where / group / limit
All join modifiers are optional; chain only what you need.
auto topic = orm::cms::Topic();
topic.eqUserid(1);
topic.select("topicid,title AS topictitle");
topic.innerJoin<orm::cms::Article>()
.joinOn("topicid", orm::cms::topic_info::cols::topicid)
.joinSelect("aid, title AS arttitle")
.joinWhere("userid", orm::wq::eq, 1)
.joinGroup("topicid")
.joinDesc("aid")
.joinLimit(2);
topic.fetch();6.3 Join chain reference
| Method | Meaning |
|---|---|
leftJoin<T>() | Start a LEFT JOIN with model type T |
innerJoin<T>() | Start an INNER JOIN with model type T |
joinOn("lcol", "rcol") | ON left.lcol = right.rcol |
joinSelect("a,b") | Columns to read from the joined table |
joinWhere("col", wq::eq, v) | Extra conditions on the joined table |
joinGroup("col") | GROUP BY (applies to the outer query) |
joinAsc / joinDesc("col") | Extra ORDER BY |
joinLimit(n) | Extra LIMIT |
7. Foreign-key navigation
Models generated after FK introspection get two free accessors: oneFkParent() (outgoing FK — child → parent) and manyFkChild() (incoming FK — parent → children).
7.1 oneFkParent() — outgoing FK
Given a child row, oneFkParent() builds a model of the parent table pre-scoped to the child's FK value.
auto child = orm::FkChild();
child.where(orm::fk_child_info::cols::id, 1).fetch_one();
// child.data.parent_id = 123
// 1) default overload — uses child.data.parent_id
auto parent = child.oneFkParent();
parent.fetch_one();
// SELECT * FROM fk_parent WHERE id = 123
// 2) explicit id overload
auto parent2 = child.oneFkParent(2);
parent2.fetch_one();
// SELECT * FROM fk_parent WHERE id = 2
// 3) decorate an existing model so you can chain extra conditions
auto decorated = orm::FkParent();
child.oneFkParent(decorated);
decorated.select("id,name").fetch_one();7.2 manyFkChild() — incoming FK
Given a list of parent rows (after a fetch()), manyFkChild() loads every matching child in a single query — avoiding the classic N+1 problem.
auto parents = orm::FkParent();
parents.fetch(); // e.g. 5 parents, ids = [1,2,3,4,5]
auto children = parents.manyFkChild(); // WHERE parent_id IN (1,2,3,4,5)
children.fetch();
// group in memory — no extra round trips
std::vector<int> child_count;
for (auto &p : parents.record) {
int n = 0;
for (auto &c : children.record) {
if (c.parent_id == p.id) n++;
}
child_count.emplace_back(n);
}7.3 FK navigation with coroutines
FK accessors are compatible with both sync and async APIs.
asio::awaitable<std::string> test_ormfk_co(std::shared_ptr<httppeer> peer) {
auto parents = orm::FkParent();
co_await parents.async_fetch();
auto children = parents.manyFkChild();
co_await children.async_fetch();
client << "parents:" << parents.record.size()
<< " children:" << children.record.size();
co_return "";
}8. Counting and aggregation
8.1 exec_count()
exec_count() runs SELECT COUNT(*) FROM ... WHERE ... using the prepared-statement path and returns the count as an unsigned int. It does not populate the model's record.
auto world = orm::World();
world.AND("id", orm::wq::be, 1)
.AND("id", orm::wq::le, 200);
unsigned int total = world.exec_count();8.2 Aggregates via select()
You can write COUNT, SUM, MAX, MIN, AVG into select(). Use an alias and read the result through a custom struct that has an ORM_NAMES(...) entry for each alias.
namespace orm::cust {
struct WorldRowStruct : orm::Base<WorldRowStruct> {
unsigned int id;
int randomnumber;
ORM_NAMES(id, randomnumber);
};
}
auto world = orm::World();
world.select("COUNT(*) AS cnt, SUM(randomnumber) AS total");
std::vector<orm::cust::WorldRowStruct> rows;
world.exec_fetch_to(rows);
// rows[0].cnt — total row count
// rows[0].total — sum of randomnumber9. Coroutine ORM — async operations
Every major ORM method has an async_* coroutine counterpart that can be awaited with co_await. They return the same values but run on the asio I/O thread instead of blocking the worker thread.
9.1 Reading with async_fetch / async_fetch_one
asio::awaitable<std::string> my_view(std::shared_ptr<httppeer> peer) {
auto articles = orm::cms::Article();
articles.where("isopen", 1);
unsigned int rows = co_await articles.async_fetch();
auto one = orm::cms::Article();
one.where("aid", aid);
co_await one.async_fetch_one();
client.val["title"] = one.getTitle();
co_return "";
}9.2 Prepared async_* APIs
Use the async_exec_* family when you want the benefit of prepared-statement caching on the coroutine path.
asio::awaitable<std::string> test_ormprepared_co(std::shared_ptr<httppeer> peer) {
auto world = orm::World();
// explicit connection ownership
world.lock_conn();
world.where(orm::world_info::cols::id, orm::wq::bt, 0);
unsigned int total = co_await world.async_exec_count();
world.clearWhere();
world.AND("id", orm::wq::be, 1).AND("id", orm::wq::le, 50);
world.select("id,randomnumber");
std::vector<orm::cust::WorldRowStruct> rows;
co_await world.async_exec_fetch_to(rows);
auto one = orm::World();
one.where(orm::world_info::cols::id, 1);
co_await one.async_exec_one();
world.unlock_conn();
client << "count:" << total << " rows:" << rows.size();
co_return "";
}9.3 async_exec_fetch_append — accumulate rows
async_exec_fetch_append() appends to record instead of clearing it on repeated calls. The underlying prepared statement is cached, so the second call of the same query runs from a warm path.
auto world = orm::World();
world.AND("id", orm::wq::be, 1).AND("id", orm::wq::le, 500);
world.select("id,randomnumber");
world.limit(0, 10);
unsigned int cold = co_await world.async_exec_fetch_append();
unsigned int warm = co_await world.async_exec_fetch_append();
// cold — first call, compiles and caches the prepared statement
// warm — second call, reuses the cached statement
// world.record now contains 20 rows total9.4 Async API reference
| Method | Returns |
|---|---|
co_await async_fetch() | affected row count (unsigned int) |
co_await async_fetch_one() | affected row count (unsigned int) |
co_await async_exec_count() | unsigned int total count |
co_await async_exec_one() | affected row count (unsigned int) |
co_await async_exec_fetch_to(vector<T>) | affected row count |
co_await async_exec_fetch_append() | newly appended row count |
co_await async_exec_update(...) / async_exec_update_col(...) / async_exec_replace_col(...) / async_exec_remove() | affected row count |
co_await async_exec_insert() / async_exec_insert_batch() | {affected_rows, last_id} |
10. Transactions
10.1 db_conn + begin_commit() / commit() / rollback()
Start a transaction with orm::db_conn, which locks one write connection exclusively until it is released.
auto tx = std::make_unique<orm::db_conn>("cms");
if (tx->begin_commit()) {
try {
std::string sql =
"UPDATE sysuser SET nickname = 'nicename_a', postid = postid + 1 "
"WHERE adminid = 10000";
tx->edit_query(sql);
if (tx->iserror) tx->rollback(); else tx->commit();
} catch (...) {
tx->rollback();
}
}10.2 Bind an ORM model to the transaction
ORM models grab their own connections from the pool by default. To make a model join your transaction, call lock_conn(tx_conn) so that all of its reads and writes go through the transaction's locked connection. unlock_conn() only unbinds — the transaction still owns the connection.
auto tx = std::make_unique<orm::db_conn>("cms");
if (tx->begin_commit()) {
auto user = orm::cms::Sysuser();
user.lock_conn(tx->mysql_edit_conn); // borrow the transaction connection
user.data.nickname = "nicename_txn";
user.where("adminid", 10000);
user.update("nickname");
user.unlock_conn(); // unbind only; tx still owns it
tx->commit(); // or rollback() on error
}10.3 Async transactions
Use async_begin_commit(), async_edit_query(), async_insert_query(), async_commit() and async_rollback() on the coroutine path.
asio::awaitable<std::string> test_co_sql_commit(std::shared_ptr<httppeer> peer) {
auto ulink = std::make_unique<orm::db_conn>("cms");
if (co_await ulink->async_begin_commit()) {
std::string sql =
"UPDATE sysuser SET nickname = 'nicename_a', "
"postid = postid + 1 WHERE adminid = 10000";
co_await ulink->async_edit_query(sql);
if (ulink->iserror) {
co_await ulink->async_rollback();
} else {
auto [eff, pid] = co_await ulink->async_insert_query(newsql);
co_await ulink->async_commit();
}
}
co_return "";
}10.4 Generate SQL strings with commit_insert / commit_update / commit_remove
For maximum control inside a transaction, build the SQL with ORM helpers and execute it via db_conn::edit_query. This is how the generator handles PostgreSQL's RETURNING clause automatically.
auto ulink = std::make_unique<orm::db_conn>("cms");
co_await ulink->async_begin_commit();
auto user_m = orm::cms::Sysuser();
user_m.data.name = "userroot";
user_m.data.password = "e10adc3949ba59abbe56e057f20f883e";
user_m.data.isopen = 1;
user_m.data.nickname = "goodname";
// 1) INSERT — PG gets RETURNING adminid automatically
std::string newsql = user_m.commit_insert();
auto [eff, pid] = co_await ulink->async_insert_query(newsql);
// 2) UPDATE — reuse the model's where()
user_m.data.nickname = "nicename_b";
user_m.where("adminid", orm::wq::eq, pid);
newsql = user_m.commit_update("nickname");
unsigned int ueff = co_await ulink->async_edit_query(newsql);
// 3) DELETE
newsql = user_m.commit_remove();
co_await ulink->async_edit_query(newsql);
co_await ulink->async_commit();11. Custom result structs
For ad-hoc queries or to avoid pulling full models, define your own structs that inherit from orm::Base<Self> and list their fields in an ORM_NAMES(...) macro. They work with both db_conn::query and exec_fetch_to.
11.1 Define a custom struct
namespace orm::cust {
// single-row carrier (used in test_sql_commit.cpp)
struct LocalusersqlStruct : orm::Base<LocalusersqlStruct> {
unsigned int adminid;
std::string name;
std::string nickname;
unsigned int postid;
ORM_NAMES(adminid, name, nickname, postid);
};
// custom ORM result struct for prepared queries
struct WorldRowStruct : orm::Base<WorldRowStruct> {
unsigned int id;
int randomnumber;
ORM_NAMES(id, randomnumber);
};
}// namespace orm::cust11.2 Read into the struct
Pass a custom struct to db_conn::query for a single row, or to db_conn::exec_query for parameterised prepared queries. Pass a std::vector of the struct to exec_fetch_to to load many rows at once.
// Single row via db_conn — synchronous
orm::cust::LocalusersqlStruct loaduser;
auto ulink = std::make_unique<orm::db_conn>("cms");
ulink->query("SELECT adminid,name,nickname,postid FROM sysuser LIMIT 1",
loaduser);
// loaduser.adminid, loaduser.name, ... are populated
// Prepared query with parameter binding
std::string sql = "SELECT aid,title,content FROM article "
"WHERE userid = ? AND aid = ? LIMIT 1";
std::vector<http::obj_val> params = {
http::obj_val(static_cast<long long>(userid)),
http::obj_val(static_cast<long long>(aid)),
};
orm::cust::ArticleRow row;
ulink->exec_query(sql, params, row);
// row.aid, row.title, row.content populated from prepared result
// Bulk fetch into a vector with exec_fetch_to
auto world = orm::World();
world.select("id,randomnumber");
std::vector<orm::cust::WorldRowStruct> rows;
world.exec_fetch_to(rows);
// rows[i].id and rows[i].randomnumber populated for every row12. Prepared statements
12.1 exec_* vs fetch_*
Paozhu ORM exposes two parallel API families. The fetch_* family issues parameterised queries. The exec_* family issues prepared queries — the compiled SQL template is cached on the connection, which cuts parsing time on repeated calls of the same query shape.
| Purpose | Regular | Prepared |
|---|---|---|
| Fetch list | fetch() | exec_fetch() |
| Fetch one row | fetch_one() | exec_one() / exec_fetch_one() |
| Count | count() | exec_count() |
| Update | update("cols") | exec_update("cols") |
| Insert | save() / insert() | exec_insert() / exec_insert_batch() |
| Delete | remove() | exec_remove() |
| Custom struct read | — | exec_fetch_to(vector<T>) |
// Regular path — every call compiles SQL fresh
auto articles = orm::cms::Article();
articles.where("isopen", 1);
articles.fetch();
// Prepared path — same shape queries share the cached statement
auto world = orm::World();
world.clearWhere();
world.AND("id", orm::wq::be, 1).AND("id", orm::wq::le, 50);
world.select("id,randomnumber");
std::vector<orm::cust::WorldRowStruct> rows;
world.exec_fetch_to(rows);12.2 Alias columns (AS) handling
When you use SELECT id AS myid, randomnumber, the physical column name is still id — the alias only affects the result set key name. The exec_* prepared path looks up physical column names via the connection metadata, so aliased queries still fill data.id correctly. The plain fetch_one() path uses the alias name instead, so data.id will be 0 in that case.
auto aliasone = orm::World();
aliasone.where(orm::world_info::cols::id, 1);
aliasone.select("id AS myid,randomnumber");
co_await aliasone.async_exec_one();
// aliasone.data.id != 0 — exec path reads physical column name via metadata
auto oneark = orm::World();
oneark.where(orm::world_info::cols::id, 1);
oneark.select("id AS myid,randomnumber");
co_await oneark.async_fetch_one();
// oneark.data.id == 0 — fetch path sees the alias "myid", not "id"13. Database dialect differences
13.1 SQLite
SQLite is the simplest driver because it runs inside the process. The host value is the absolute filesystem path of the .db file; port, user and password are left empty.
[lite]
type = main
host = /Users/hzq/paozhu/docs/sqlite_lite.db
port =
dbname = lite
user =
password =
minpool = 1
maxpool = 5
dbtype = sqlite
charset = utf8mb413.2 PostgreSQL — RETURNING clause
PostgreSQL does not expose an implicit last_insert_id() like MySQL. The ORM generator handles this by appending RETURNING <pk_col> to INSERT SQL on PostgreSQL, so commit_insert() produces different SQL depending on the database type — you do not need to branch manually.
auto user_m = orm::cms::Sysuser();
user_m.data.name = "userroot";
user_m.data.nickname = "goodname";
// commit_insert() outputs:
// MySQL: INSERT INTO sysuser (name, nickname, ...) VALUES ('userroot', 'goodname', ...)
// PG: INSERT INTO sysuser (name, nickname, ...) VALUES ('userroot', 'goodname', ...) RETURNING adminid
std::string newsql = user_m.commit_insert();
auto [eff, pid] = co_await ulink->async_insert_query(newsql);
// pid == auto-generated PK on both drivers — unified return value13.3 Driver feature summary
| Feature | MySQL | PostgreSQL | SQLite |
|---|---|---|---|
host meaning | hostname / IP | hostname / IP | .db file path |
port | 3306 | 5432 | empty |
user / password | required | required | empty |
Implicit last_insert_id | yes | no — via RETURNING | yes |
Generated commit_insert appends RETURNING | no | yes (auto) | no |
| Prepared statements | yes | yes | yes |
| FK introspection / navigation | yes | yes | yes (if schema has FKs) |