AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH SQL library documentation

Introduction

AnCH SQL library aims to provide facilities to manage SQL database interactions.

Prerequisites

anch-utils (connection pool), anch-conf (connection factory configuration) and the client library of each driver: libmariadb (or libmysqlclient), libpq and libsqlite3.

Installation

CMake target anch::sql, option ANCH_BUILD_SQL ; drivers anch::mysql , anch::postgresql and anch::sqlite are loaded at runtime:

find_package(Anch REQUIRED)
target_link_libraries(my-app PRIVATE anch::sql)

See installation.

Conception

AnCH SQL library is a layer to manage SQL client. Managed SQL clients are SQLite3, PostgreSQL and MySQL/MariaDB.

SQl interfaces are inspired by Java JDBC. You will find Connection, ResultSet,, PreparedStatement and SqlException. ResultSet can be handle with row mapper and complete extract std::function "std::function" trough queryMapRow and queryExtract methods. These methods will release ResultSet.

AnCH SQL provides connection factory.

Prepared statements

Prepared statements use named parameters ( :name , see NamedQuery): a name used several times is bound once. Parameters in string literals, quoted identifiers and comments are ignored, as PostgreSQL casts ( x::int ), array slices ( arr[1:n] ) and jsonb ? operators, and MySQL assignments ( := ). Positional parameters ( ? , PostgreSQL $1 , SQLite ?1 , @name , $name ) are refused. Values are given with PreparedStatement::set(name, value) or with Parameters:

dbCon.update("UPDATE T_Test SET email = :email WHERE first_name = :first", {{"email", "john@anch.org"}, {"first", "John"}});
dbCon.update("UPDATE T_Test SET email = :email WHERE first_name = :first",
anch::sql::Parameters().add("first", "Jane").addNull("email"));

Every parameter has to be bound before execution (missing parameters are reported with their names, unknown names are refused) ; NULL is bound with setNull , std::nullopt , a NULL pointer or an empty std::optional .
Values are sent as text: integers, floating point numbers, booleans ( 1 / 0 ), strings, anch::date::Date , anch::date::Time , anch::date::DateTime and, with ANCH_UUID , anch::UUID (canonical form: PostgreSQL uuid , MariaDB UUID , CHAR(36) , ... columns ; BINARY(16) columns need UUID_TO_BIN(:id) in the query). Result fields are read with ResultSet::get<T> as the same types (booleans: 1 / 0 , PostgreSQL t / f , true / false ; ResultSet::columns and columnIndex give the columns names):

dbCon.queryMapRow("SELECT CAST(:id AS uuid)", [](ResultSet& res) {
std::cout << "UUID: " << res.get<anch::UUID>(0).value_or(anch::UUID()) << std::endl;
}, {{"id", id}});

Points in time of std::chrono::system_clock ( std::chrono::sys_time<Duration> : sys_seconds , sys_days , ...) are bound and read as anch::date::DateTime (milliseconds, local time), rounded down to their precision when they are read ; sys_days is a point in time at midnight UTC (a calendar day is an anch::date::Date ) and points in time of other clocks are refused at compile time ( std::chrono::clock_cast them):

const std::chrono::sys_seconds yesterday = std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now()) - std::chrono::days(1);
dbCon.queryMapRow("SELECT CAST(:since AS timestamp)", [](ResultSet& res) {
std::optional<std::chrono::sys_seconds> since = res.get<std::chrono::sys_seconds>(0);
std::cout << "Since: " << (since ? std::format("{}", *since) : std::string("NULL")) << std::endl;
}, {{"since", yesterday}});

A list of values ( std::vector , std::list , std::set , ... ; strings are not lists) bound to the only item of an IN list ( IN (:ids) , NOT IN (:ids) ) is a PostgreSQL array: the query is rewritten in = ANY($1) ( <> ALL($1) ), one prepared statement whatever the list size ; other databases expand the list ( IN (?, ?, ?) : the statement is prepared again when the list size changes ; an empty list is an empty subquery: IN is false and NOT IN true). In PostgreSQL, a list can also be used as an array anywhere ( = ANY(:ids) , :ids::int[] ).
The fields of an object described by its common description ( anch::Mapping<T> , anch-utils, shared with JSON, CSV and validation) are bound to the parameters of the same names with fieldsOf (the other fields are ignored ; fields which are only written are not parameters), and Connection::batchUpdate takes a range of described objects:

// Common description of Person (JSON, CSV, validation, SQL parameters, ...): fields are SQL parameters of the same
// names with anch::sql::fieldsOf, and are read from the columns of the same names (queryList, queryOne, ...)
template<>
struct anch::Mapping<Person> {
static void
registerObject(anch::ObjectMapper<Person> auto& mapper) {
mapper
.registerField("id", &Person::_id)
.registerField("first_name", &Person::_firstName)
.registerField("last_name", &Person::_lastName)
.registerField("birth_date", &Person::_birthDate)
.registerField("email", &Person::_email)
;
}
};
Person joe;
joe.setFirstName("Joe");
joe.setLastName("Doe");
joe.setBirthDate("1973-01-01");
joe.setEmail("joe@anch.org");
dbCon.update("INSERT INTO T_Test (first_name,last_name,birth_date,email) VALUES (:first_name,:last_name,:birth_date,:email)",

Result rows are read as described objects or values with Connection::queryList (all the rows), queryOne (the only row, std::nullopt without row, error with several rows) and queryEach (one row at a time), with the same parameters as query ; readRow and rowAs read the current row of a result set. Each column fills the field of the same name (ASCII case is ignored: PostgreSQL gives unquoted aliases in lowercase ; RowMapper), other columns are ignored and fields without column keep their value ; a NULL column needs a std::optional field. A row which is not described (integer, string, date, ...) is read from the first column:

const std::string select = "SELECT id,first_name,last_name,birth_date,COALESCE(email, '') AS email FROM T_Test";
std::vector<Person> all = dbCon.queryList<Person>(select);
std::optional<Person> george = dbCon.queryOne<Person>(select + " WHERE id = :id", {{"id", 2}});
dbCon.queryEach<Person>(select, [](Person&& person) { std::cout << "Read " << person._firstName << std::endl; });
std::vector<int64_t> ids = dbCon.queryList<int64_t>("SELECT id FROM T_Test ORDER BY id");

Queries built by the SELECT builder ( anch::sql::select , anch::sql::clauses ) have named parameters generated from their columns ( t.id gives :t_id , _min and _max for BETWEEN , _2 , ... when a name is already used, also by merged clauses and subqueries): SQLQuery::getParameters gives them to Connection::query . A clause whose value is absent (empty std::optional or string) is skipped.
PostgreSQL infers the type of a parameter from its first use: a parameter whose first use does not give its type ( :name IS NULL ) is written with a cast ( :name::text ) or after a comparison with a column.

Errors

Errors raise SqlException and are reported to the connection, from its prepared statements and result sets too. A fatal error (SqlException::isOK is false : connection lost or killed, server shutdown, out of memory, protocol error) invalidates the connection. Other errors keep it valid.

Transactions

Without Connection::startTransaction (or begin ), each query is committed by the database (auto-commit mode). A transaction is committed only by Connection::commit : a transaction which is not ended when the connection is released (returned to its pool or destroyed) is rolled back, with or without error, so that an application exception between two queries does not commit partial work.

SQL connection pool

SQL connection pools are configured in configuration file dbCon.conf
When a connection is returned to its pool, Connection::release rolls back its unfinished transaction, then invalid connections are destroyed instead of being reused.

Prepared statements cache

Each connection keeps its prepared statements in a bounded cache (statement-cache-size key of the connection section, 256 by default, Connection::setStatementCacheSize ). The least recently used statement is evicted and deallocated on the server side when the cache is full ; a statement is not evicted while one of its result sets is alive. Queries built with literal values (IN lists of the builder for example) are distinct cache entries: bind values with named parameters whenever possible.

Example

SQL connection example:

#include "sql/postgresqlConnection.hpp"
#include <chrono>
#include <iostream>
#include <format>
#include <functional>
#include <list>
#include <optional>
#include <string>
#include <vector>
class Person {
public:
uint32_t _id;
std::string _firstName;
std::string _lastName;
std::string _birthDate;
std::string _email;
public:
Person(): _id(), _firstName(), _lastName(), _birthDate(), _email() {}
virtual ~Person() {}
inline uint32_t getId() const {return _id;}
inline void setId(uint32_t id) {_id = id;}
inline const std::string& getFirstName() const {return _firstName;}
inline void setFirstName(const std::string& firstName) {_firstName = firstName;}
inline const std::string& getLastName() const {return _lastName;}
inline void setLastName(const std::string& lastName) {_lastName = lastName;}
inline const std::string& getBirthDate() const {return _birthDate;}
inline void setBirthDate(const std::string& birthDate) {_birthDate = birthDate;}
inline const std::string& getEmail() const {return _email;}
inline void setEmail(const std::string& email) {_email = email;}
};
// Common description of Person (JSON, CSV, validation, SQL parameters, ...): fields are SQL parameters of the same
// names with anch::sql::fieldsOf, and are read from the columns of the same names (queryList, queryOne, ...)
template<>
struct anch::Mapping<Person> {
static void
registerObject(anch::ObjectMapper<Person> auto& mapper) {
mapper
.registerField("id", &Person::_id)
.registerField("first_name", &Person::_firstName)
.registerField("last_name", &Person::_lastName)
.registerField("birth_date", &Person::_birthDate)
.registerField("email", &Person::_email)
;
}
};
int
main(void) {
std::cout << "Enter in PostgreSQL unit tests" << std::endl << std::endl;
try {
config.driver = "PostgreSQL";
config.database = "anch_test";
config.hostname = "localhost";
config.port = 5432;
config.user = "anch";
config.password = "anch";
PostgreSQLConnection dbCon(config);
std::cout << "Connected to database" << std::endl;
// Without transaction, each query is committed by the database (auto-commit mode). Parameters are named
// (':name'): each one has to be given, a name used several times is bound once
dbCon.update("UPDATE T_Test SET email = :email WHERE first_name = :first", {{"email", "john@anch.org"}, {"first", "John"}});
dbCon.update("UPDATE T_Test SET email = :email WHERE first_name = :first",
anch::sql::Parameters().add("first", "Jane").addNull("email"));
// A transaction is committed only by commit(): an unfinished transaction is rolled back when the connection is
// released (returned to its pool or destroyed), even without SQL error
dbCon.begin();
try {
const std::string insert = "INSERT INTO T_Test (first_name,last_name,birth_date) VALUES (:first,:last,:birth)";
dbCon.update(insert, {{"first", "Jane"}, {"last", "Doe"}, {"birth", "1971-01-01"}});
dbCon.update(insert, {{"first", "Jack"}, {"last", "Doe"}, {"birth", "1972-01-01"}});
dbCon.commit();
} catch(...) {
dbCon.rollback();
throw;
}
// Parameters from the fields of a described object (the other fields are ignored)
Person joe;
joe.setFirstName("Joe");
joe.setLastName("Doe");
joe.setBirthDate("1973-01-01");
joe.setEmail("joe@anch.org");
dbCon.update("INSERT INTO T_Test (first_name,last_name,birth_date,email) VALUES (:first_name,:last_name,:birth_date,:email)",
#ifdef ANCH_UUID
// UUID (with ANCH_UUID): canonical form, read back as anch::UUID
dbCon.queryMapRow("SELECT CAST(:id AS uuid)", [](ResultSet& res) {
std::cout << "UUID: " << res.get<anch::UUID>(0).value_or(anch::UUID()) << std::endl;
}, {{"id", id}});
#endif
// system_clock points in time: bound and read as anch::date::DateTime (milliseconds, local time)
const std::chrono::sys_seconds yesterday = std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now()) - std::chrono::days(1);
dbCon.queryMapRow("SELECT CAST(:since AS timestamp)", [](ResultSet& res) {
std::optional<std::chrono::sys_seconds> since = res.get<std::chrono::sys_seconds>(0);
std::cout << "Since: " << (since ? std::format("{}", *since) : std::string("NULL")) << std::endl;
}, {{"since", yesterday}});
std::cout << std::endl;
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' with manual result handling" << std::endl;
ResultSet* res = dbCon.query("SELECT id,first_name,last_name,birth_date,email FROM T_Test");
int row = 0;
std::string nullStr("NULL");
while(res->next()) {
std::cout << "Row " << row << std::endl;
std::optional<uint32_t> id = res->get<uint32_t>(0);
std::cout << "id=" << (id ? std::to_string(*id) : nullStr) << std::endl;
std::optional<std::string> fName = res->get<std::string>(1);
std::cout << "first name=" << fName.value_or(nullStr) << std::endl;
std::optional<std::string> lName = res->get<std::string>(2);
std::cout << "last name=" << lName.value_or(nullStr) << std::endl;
std::optional<std::string> bDate = res->get<std::string>("birth_date");
std::cout << "birth date=" << bDate.value_or(nullStr) << std::endl;
std::optional<std::string> email = res->get<std::string>(4);
std::cout << "email=" << email.value_or(nullStr) << std::endl;
row++;
}
delete res;
std::cout << std::endl;
// Rows as described objects (columns associated with fields by name, case ignored ; a NULL column needs a
// std::optional field) or as values (first column)
const std::string select = "SELECT id,first_name,last_name,birth_date,COALESCE(email, '') AS email FROM T_Test";
std::vector<Person> all = dbCon.queryList<Person>(select);
std::optional<Person> george = dbCon.queryOne<Person>(select + " WHERE id = :id", {{"id", 2}});
dbCon.queryEach<Person>(select, [](Person&& person) { std::cout << "Read " << person._firstName << std::endl; });
std::vector<int64_t> ids = dbCon.queryList<int64_t>("SELECT id FROM T_Test ORDER BY id");
std::cout << all.size() << " persons, " << ids.size() << " identifiers, George " << (george ? "found" : "not found") << std::endl;
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' with per row result handling" << std::endl;
std::list<Person> persons;
dbCon.queryMapRow("SELECT id,first_name,last_name,birth_date,email FROM T_Test", [&persons](ResultSet& resSet) {
Person person;
resSet.get<uint32_t>(0,person._id);
resSet.get<std::string>(1, person._firstName);
resSet.get<std::string>(2, person._lastName);
resSet.get<std::string>(3, person._birthDate);
resSet.get<std::string>(4, person._email);
persons.push_back(person);
});
std::cout << "Found " << persons.size() << " persons." << std::endl;
for(const Person& pers : persons) {
std::cout << "Person " << pers._id << ":" << std::endl;
std::cout << "first name: " << pers._firstName << std::endl;
std::cout << "last name: " << pers._lastName << std::endl;
std::cout << "birth data: " << pers._birthDate << std::endl;
std::cout << "email: " << pers._email << std::endl;
}
std::cout << std::endl;
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' with result set extracting" << std::endl;
dbCon.queryExtract("SELECT id,first_name,last_name,birth_date,email FROM T_Test", [](ResultSet& resSet) {
while(resSet.next()) {
Person pers;
resSet.get<uint32_t>(0,pers._id);
resSet.get<std::string>(1, pers._firstName);
resSet.get<std::string>(2, pers._lastName);
resSet.get<std::string>(3, pers._birthDate);
resSet.get<std::string>(4, pers._email);
std::cout << "Person " << pers._id << ":" << std::endl;
std::cout << "first name: " << pers._firstName << std::endl;
std::cout << "last name: " << pers._lastName << std::endl;
std::cout << "birth data: " << pers._birthDate << std::endl;
std::cout << "email: " << pers._email << std::endl;
}
});
std::cout << std::endl;
} catch(const SqlException& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
std::cout << "Exit PostgreSQL unit tests" << std::endl;
return 0;
}

Pool configuration example:

[anch::sql.anch_mysql]
driver=MySQL
host=localhost
port=3306
user=anch
password=anch
database=anch_test
[anch::sql.anch_mysql.pool]
max-size=20
init-size=2
[anch::sql.anch_pgsql]
driver=PostgreSQL
host=localhost
port=5432
user=anch
password=anch
database=anch_test
statement-cache-size=512
[anch::sql.anch_pgsql.pool]
max-size=20
init-size=2
timeout=200
[anch::sql.anch_sqlite]
driver=SQLite3
database=anch.db
SQL namespace.
Definition clauses.hpp:28
AnCH framework base namespace.
Definition app.hpp:30

Pool example:

#include "sql/sqlConnectionFactory.hpp"
#include <iostream>
#include <list>
#include <functional>
class Person {
public:
uint32_t _id;
std::string _firstName;
std::string _lastName;
std::string _birthDate;
std::string _email;
public:
Person(): _id(), _firstName(), _lastName(), _birthDate(), _email() {}
virtual ~Person() {}
inline uint32_t getId() const {return _id;}
inline void setId(uint32_t id) {_id = id;}
inline const std::string& getFirstName() const {return _firstName;}
inline void setFirstName(const std::string& firstName) {_firstName = firstName;}
inline const std::string& getLastName() const {return _lastName;}
inline void setLastName(const std::string& lastName) {_lastName = lastName;}
inline const std::string& getBirthDate() const {return _birthDate;}
inline void setBirthDate(const std::string& birthDate) {_birthDate = birthDate;}
inline const std::string& getEmail() const {return _email;}
inline void setEmail(const std::string& email) {_email = email;}
};
int
main(void) {
std::cout << "Enter in SQL connection factory unit test" << std::endl;
try {
SqlConnectionFactory& fact = SqlConnectionFactory::getInstance();
std::cout << "Factory has been correctly initialized" << std::endl;
SqlConnectionPool& myPool = fact.getPool("anch_mysql");
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' on MySQL database" << std::endl;
std::list<Person> persons;
myPool.borrowResource().get().queryMapRow("SELECT id,first_name,last_name,birth_date,email FROM T_Test", [&persons](ResultSet& resSet) {
Person person;
resSet.get<uint32_t>(0,person._id);
resSet.get<std::string>(1,person._firstName);
resSet.get<std::string>(2,person._lastName);
resSet.get<std::string>(3,person._birthDate);
resSet.get<std::string>(4,person._email);
persons.push_back(person);
});
std::cout << "Found " << persons.size() << " persons." << std::endl;
for(const Person& pers : persons) {
std::cout << "Person " << pers._id << ":" << std::endl;
std::cout << "first name: " << pers._firstName << std::endl;
std::cout << "last name: " << pers._lastName << std::endl;
std::cout << "birth data: " << pers._birthDate << std::endl;
std::cout << "email: " << pers._email << std::endl;
}
std::cout << std::endl;
SqlConnectionPool& pgPool = fact.getPool("anch_pgsql");
persons.clear();
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' on PostgreSQL database" << std::endl;
auto res = pgPool.borrowResource();
res.get().queryMapRow("SELECT id,first_name,last_name,birth_date,email FROM T_Test", [&persons](ResultSet& resSet) {
Person person;
resSet.get<uint32_t>(0,person._id);
resSet.get<std::string>(1,person._firstName);
resSet.get<std::string>(2,person._lastName);
resSet.get<std::string>(3,person._birthDate);
resSet.get<std::string>(4,person._email);
persons.push_back(person);
});
std::cout << "Found " << persons.size() << " persons." << std::endl;
for(const Person& pers : persons) {
std::cout << "Person " << pers._id << ":" << std::endl;
std::cout << "first name: " << pers._firstName << std::endl;
std::cout << "last name: " << pers._lastName << std::endl;
std::cout << "birth data: " << pers._birthDate << std::endl;
std::cout << "email: " << pers._email << std::endl;
}
std::cout << std::endl;
Connection* sqliteCon = fact.createConnection("anch_sqlite");
persons.clear();
std::cout << "Execute 'SELECT id,first_name,last_name,birth_date,email FROM T_Test' on SQLite3 database" << std::endl;
sqliteCon->queryMapRow("SELECT id,first_name,last_name,birth_date,email FROM T_Test", [&persons](ResultSet& resSet) {
Person person;
resSet.get<uint32_t>(0,person._id);
resSet.get<std::string>(1,person._firstName);
resSet.get<std::string>(2,person._lastName);
resSet.get<std::string>(3,person._birthDate);
resSet.get<std::string>(4,person._email);
persons.push_back(person);
});
std::cout << "Found " << persons.size() << " persons." << std::endl;
for(const Person& pers : persons) {
std::cout << "Person " << pers._id << ":" << std::endl;
std::cout << "first name: " << pers._firstName << std::endl;
std::cout << "last name: " << pers._lastName << std::endl;
std::cout << "birth data: " << pers._birthDate << std::endl;
std::cout << "email: " << pers._email << std::endl;
}
delete sqliteCon;
} catch(const SqlException& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
} catch(const std::bad_alloc& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
std::cout << "Exit SQL connection factory unit test" << std::endl;
return 0;
}