### CMake Project Setup and Executable Creation Source: https://github.com/qicosmos/ormpp/blob/master/example/CMakeLists.txt Configures the CMake project named 'ormpp_example' and defines the source files for the main executable. It sets up the project structure and identifies the primary build artifact. ```cmake project(ormpp_example) set(ORMPP_EXAMPLE main.cpp ) add_executable(${PROJECT_NAME} ${ORMPP_EXAMPLE}) ``` -------------------------------- ### CMake Installation Rule for Executable Source: https://github.com/qicosmos/ormpp/blob/master/example/CMakeLists.txt Installs the built executable target to the CMAKE_INSTALL_INCLUDEDIR destination. This defines where the compiled program will be placed after installation. ```cmake install(TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) ``` -------------------------------- ### Connect to Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Demonstrates how to establish a connection to different database systems (MySQL, PostgreSQL, SQLite) using the `connect` method. It shows examples with different argument sets for host, user, password, database name, timeout, and port. Returns true on success, false on failure. ```C++ // mysql.connect(host, dbuser, pwd, dbname); mysql.connect("127.0.0.1", "root", "12345", "testdb"); // mysql.connect(host, dbuser, pwd, dbname, timeout, port); mysql.connect("127.0.0.1", "root", "12345", "testdb", 5, 3306); postgres.connect("127.0.0.1", "root", "12345", "testdb"); sqlite.connect("127.0.0.1", "testdb");//或直接sqlite.connect("testdb"); //开启sqlcipher后 sqlite.connect("127.0.0.1", "root", "12345", "testdb");//或者直接sqlite.connect("testdb", "123456"); ``` -------------------------------- ### Query Data from Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Provides examples for querying data from database tables using `query_s` for MySQL, PostgreSQL, and SQLite. Demonstrates fetching all records and fetching records based on a condition with parameter binding. Returns a `std::vector` of the queried type. ```C++ auto result = mysql.query_s(); TEST_CHECK(result.size()==3); auto result1 = postgres.query_s(); TEST_CHECK(result1.size()==3); auto result2 = sqlite.query_s(); TEST_CHECK(result2.size()==3); //可以根据条件查询 auto result3 = mysql.query_s("id=?", 1); TEST_CHECK(result3.size()==1); ``` -------------------------------- ### ORM++ C++ API - Transaction Management Source: https://github.com/qicosmos/ormpp/blob/master/README.md This C++ code snippet illustrates ORM++ API functions for managing database transactions. It includes functions to start a transaction, commit pending changes, and roll back the transaction in case of errors. ```cpp //开始事务 bool begin(); //提交事务 bool commit(); //回滚 bool rollback(); ``` -------------------------------- ### Conditional Database Library Linking in CMake Source: https://github.com/qicosmos/ormpp/blob/master/example/CMakeLists.txt Conditionally links the executable against database libraries (PostgreSQL, MySQL, MariaDB, or SQLite3) based on build flags. It also includes a specific compiler flag for MSVC Debug builds when using MySQL. ```cmake if(ENABLE_PG) target_link_libraries(${PROJECT_NAME} ${PGSQL_LIBRARY}) elseif(ENABLE_MYSQL) target_link_libraries(${PROJECT_NAME} ${MYSQL_LIBRARY}) if (MSVC AND CMAKE_BUILD_TYPE STREQUAL "Debug") set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/MD") endif() elseif(ENABLE_MARIADB) target_link_libraries(${PROJECT_NAME} ${MARIADB_LIBRARY}) elseif(ENABLE_SQLITE3) target_link_libraries(${PROJECT_NAME} sqlite3) endif() ``` -------------------------------- ### CMake Build Configuration for ormpp Source: https://github.com/qicosmos/ormpp/blob/master/CMakeLists.txt This CMakeLists.txt file sets up the build system for the ormpp project. It defines the project name, minimum required CMake version, and includes various CMake modules for dependency management, platform specifics, and build customization. It also conditionally includes subdirectories for tests and examples based on build flags. ```cmake cmake_minimum_required(VERSION 3.15) project(ormpp) if(ENABLE_SQLITE3_CODEC) include(cmake/openssl.cmake) endif() include(cmake/build.cmake) include(cmake/develop.cmake) include(cmake/platform.cmake) include(cmake/dependency.cmake) if (ENABLE_PG) include_directories(${PGSQL_INCLUDE_DIR} ormpp) elseif(ENABLE_MYSQL) include_directories(${MYSQL_INCLUDE_DIR} ormpp) elseif(ENABLE_MARIADB) include_directories(${MARIADB_INCLUDE_DIR} ormpp) else() include_directories(ormpp) endif() include_directories(./) if (BUILD_UNIT_TESTS) add_subdirectory(${ormpp_SOURCE_DIR}/tests) endif () if (BUILD_EXAMPLES) add_subdirectory(${ormpp_SOURCE_DIR}/example) endif () ``` -------------------------------- ### Delete Records from Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Demonstrates deleting records from database tables using `delete_records_s` for MySQL, PostgreSQL, and SQLite. Examples include deleting all records and deleting records based on a condition with parameter binding. ```C++ //删除所有数据 TEST_REQUIRE(mysql.delete_records_s()); TEST_REQUIRE(postgres.delete_records_s()); TEST_REQUIRE(sqlite.delete_records_s()); //根据条件删除数据 TEST_REQUIRE(mysql.delete_records_s("id=?", 1)); TEST_REQUIRE(postgres.delete_records_s("id=$1", 1)); TEST_REQUIRE(sqlite.delete_records_s("id=?", 1)); ``` -------------------------------- ### Insert Single Record into Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Provides examples for inserting a single data record into tables for MySQL, PostgreSQL, and SQLite. It shows inserting a standard `person` object and a `person` object where the 'age' field is intentionally left null. ```C++ person p = {1, "test1", 2}; TEST_CHECK(mysql.insert(p)==1); TEST_CHECK(postgres.insert(p)==1); TEST_CHECK(sqlite.insert(p)==1); // age为null person p = {1, "test1", {}}; TEST_CHECK(mysql.insert(p)==1); TEST_CHECK(postgres.insert(p)==1); TEST_CHECK(sqlite.insert(p)==1); ``` -------------------------------- ### Database Transactions (MySQL) Source: https://github.com/qicosmos/ormpp/blob/master/README.md Demonstrates the use of transactions for performing multiple database operations atomically. It includes starting a transaction, inserting records within the transaction, and either committing the changes upon success or rolling back if any insertion fails. Returns a boolean indicating success or failure. ```C++ //transaction mysql.begin(); for (int i = 0; i < 10; ++i) { person s = {i, "tom", 19}; if(!mysql.insert(s)){ mysql.rollback(); return -1; } } mysql.commit(); ``` -------------------------------- ### Transaction Management (MySQL) Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md ORM++ provides basic transaction management capabilities, including begin, commit, and rollback operations. This example demonstrates inserting multiple records within a transaction, with rollback occurring if any insert operation fails. The success or failure of the transaction is indicated by a boolean return value. ```C++ mysql.begin(); for (int i = 0; i < 10; ++i) { person s = {i, "tom", 19}; if(!mysql.insert(s)){ mysql.rollback(); return -1; } } mysql.commit(); ``` -------------------------------- ### C++ ORM Operations with ormpp Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Demonstrates basic CRUD operations (insert, update, query, delete) and transaction management using the ormpp library with a MySQL database. It requires the 'dbng.hpp' header and the REFECTION macro for entity mapping. This example assumes a 'person' struct and a configured MySQL connection. ```cpp #include "dbng.hpp" using namespace ormpp; struct person { int id; std::string name; int age; }; REFLECTION(person, id, name, age) int main() { person p = {1, "test1", 2}; person p1 = {2, "test2", 3}; person p2 = {3, "test3", 4}; std::vector v{p1, p2}; dbng mysql; mysql.connect("127.0.0.1", "dbuser", "yourpwd", "testdb"); mysql.create_datatable(); mysql.insert(p); mysql.insert(v); mysql.update(p); mysql.update(v); auto result = mysql.query(); //vector for(auto& person : result){ std::cout<(); //transaction mysql.begin(); for (int i = 0; i < 10; ++i) { person s = {i, "tom" 19}; if(!mysql.insert(s)){ mysql.rollback(); return -1; } } mysql.commit(); } ``` -------------------------------- ### Aspect-Oriented Programming (AOP) with Custom Aspects (MySQL) Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md This feature allows developers to integrate custom logic (aspects) to run before or after business functions. The example shows how to define 'log' and 'validate' aspects, which print messages to the console. These aspects are then applied to a database connection using the `warper_connect` method. The `before` method in an aspect can modify arguments, and the `after` method can potentially alter the return value. ```C++ struct log{ template bool before(Args... args){ std::cout<<"log before"< bool after(T result, Args... args){ std::cout<<"log after"< bool before(Args... args){ std::cout<<"validate before"< bool after(T result, Args... args){ std::cout<<"validate after"< mysql; auto r = mysql.warper_connect("127.0.0.1", "root", "12345", "testdb"); TEST_REQUIRE(r); ``` -------------------------------- ### Aspect-Oriented Programming (AOP) Aspects Source: https://github.com/qicosmos/ormpp/blob/master/README.md Defines custom aspects for Aspect-Oriented Programming (AOP). The 'log' and 'validate' structs are examples of aspects that can be applied to database operations. They feature 'before' and 'after' methods that execute code, respectively, before and after the core business logic. These methods can accept arguments and return booleans to control execution flow. ```C++ struct log{ //args...是业务逻辑函数的入参 template bool before(Args... args){ std::cout<<"log before"< bool after(T t, Args... args){ std::cout<<"log after"< bool before(Args... args){ std::cout<<"validate before"< bool after(T t, Args... args){ std::cout<<"validate after"< bool connect(Args&&... args); // Disconnect from the database bool disconnect(); // Create a data table template bool create_datatable(Args&&... args); // Insert a single record template int insert(const T& t, Args&&... args); // Insert multiple records template int insert(const std::vector& t, Args&&... args); // Replace a single record template int replace(const T &t, Args &&...args); // Replace multiple records template int replace(const std::vector &v, Args &&...args); // Update a single record template int update(const T& t, Args&&... args); // Update multiple records template int update(const std::vector& t, Args&&... args); // Update specific fields of a single record template int update_some(const T &t, Args &&...args); // Update specific fields of multiple records template int update_some(const std::vector &v, Args &&...args); // Get the auto-increment ID after insertion template uint64_t get_insert_id_after_insert(const T &t, Args &&...args); // Delete records (with prepared statements) template int delete_records_s(const std::string &str = "", Args &&...args); // Query records, including single and multi-table queries (with prepared statements) template std::vector query_s(const std::string &str = "", Args &&...args); // Delete records (without prepared statements - deprecated) template [[deprecated]] bool delete_records(Args &&...where_condition) // Query records, including single and multi-table queries (without prepared statements - deprecated) template [[deprecated]] std::vector query(Args &&...args); // Execute raw SQL statements int execute(const std::string& sql); // Start a transaction bool begin(); // Commit a transaction bool commit(); // Rollback a transaction bool rollback(); ``` ``` -------------------------------- ### CMake: Configure ORM++ Project and Executable Source: https://github.com/qicosmos/ormpp/blob/master/tests/CMakeLists.txt This CMake script sets up the build environment for the ORM++ project. It defines the runtime output directory for executables and adds a new executable target named 'test_ormpp' compiled from 'test_ormpp.cpp' and 'main.cpp'. It also registers this executable as a test case. ```cmake set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests) project(test_ormpp) add_executable(${PROJECT_NAME} test_ormpp.cpp main.cpp ) add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME}) ``` -------------------------------- ### Compiler and Database Requirements Source: https://github.com/qicosmos/ormpp/blob/master/README.md Details on compiler and database prerequisites for ORM++. ```APIDOC ## Compiler and Database Requirements ### Compiler Support Requires a C++17 compatible compiler: - Linux: GCC 7.2 or higher - Windows: Visual Studio 2017 Update 5 or higher ### Database Installation ORM++ supports MySQL and PostgreSQL. Ensure these databases and their respective client libraries (e.g., libpq for PostgreSQL) are installed. If not installed in default locations, configure the CMakeLists.txt file with the correct directory and library paths. ``` -------------------------------- ### Integrate MySQL Support with CMake Source: https://github.com/qicosmos/ormpp/blob/master/README.md This snippet shows how to enable MySQL support in ORM++ using CMake. It involves setting build flags and including the ORM++ library. Alternatively, it demonstrates a more explicit way to link against MySQL libraries and headers. ```cmake set(ENABLE_MYSQL ON) add_definitions(-DORMPP_ENABLE_MYSQL) add_subdirectory(ormpp) ``` ```cmake set(ENABLE_MYSQL ON) add_definitions(-DORMPP_ENABLE_MYSQL) add_library(ormpp INTERFACE) include(ormpp/cmake/mysql.cmake) target_link_libraries(ormpp INTERFACE ${MYSQL_LIBRARY}) target_include_directories(ormpp INTERFACE ormpp ormpp/ormpp ${MYSQL_INCLUDE_DIR}) ``` -------------------------------- ### Database Connection Source: https://github.com/qicosmos/ormpp/blob/master/README.md Establishes a connection to the database. Supports various connection parameters depending on the database type. ```APIDOC ## Database Connection ### Description Establishes a connection to the database. Supports various connection parameters depending on the database type. ### Method `template bool connect(Args&&... args);` ### Parameters #### Query Parameters (Varies by database type. See examples for details.) ### Request Example ```cpp // For MySQL mysql.connect("127.0.0.1", "root", "12345", "testdb"); mysql.connect("127.0.0.1", "root", "12345", "testdb", 5, 3306); // For PostgreSQL postgres.connect("127.0.0.1", "root", "12345", "testdb"); // For SQLite sqlite.connect("127.0.0.1", "testdb"); // or sqlite.connect("testdb"); // For SQLite with SQLCipher sqlite.connect("127.0.0.1", "root", "12345", "testdb"); // or sqlite.connect("testdb", "123456"); ``` ### Response #### Success Response (true) Returns `true` if the connection is successful. #### Failure Response (false) Returns `false` if the connection fails. #### Response Example ``` true ``` ``` -------------------------------- ### Database Connection Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Establishes a connection to the specified database. Supports MySQL, PostgreSQL, and SQLite. ```APIDOC ## Database Connection ### Description Connects to a database using provided credentials and connection details. ### Method `template bool connect(Args&&... args)` ### Parameters * **MySQL/PostgreSQL**: `connect(host, user, password, dbname)` * **SQLite**: `connect(dbfile)` ### Request Example ```cpp // MySQL dbng mysql; mysql.connect("127.0.0.1", "root", "12345", "testdb"); // PostgreSQL dbng postgres; postgres.connect("127.0.0.1", "root", "12345", "testdb"); // SQLite dbng sqlite; sqlite.connect("dbfile"); ``` ### Response #### Success Response (true) Returns `true` if the connection is successful. #### Failure Response (false) Returns `false` if the connection fails. ``` -------------------------------- ### Add doctest Library Source: https://github.com/qicosmos/ormpp/blob/master/thirdparty/CMakeLists.txt Configures the doctest testing framework as an interface library. It includes specifying the include directories for doctest, making it available for use in other targets within the project. ```cmake add_library(doctest INTERFACE) target_include_directories(doctest INTERFACE doctest) ``` -------------------------------- ### Create Database Table with C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Demonstrates creating database tables based on C++ structs using `create_datatable`. Supports specifying primary keys, NOT NULL constraints, and UNIQUE constraints. Handles potential data type issues with unique string columns by defaulting to VARCHAR(512). ```C++ //创建不含主键的表 mysql.create_datatable(); postgres.create_datatable(); sqlite.create_datatable(); //创建含主键和not null属性的表 ormpp_key key1{"id"}; ormpp_not_null not_null{{"id", "age"}}; person p = {1, "test1", 2}; person p1 = {2, "test2", 3}; person p2 = {3, "test3", 4}; mysql.create_datatable(key1, not_null); postgres.create_datatable(key1, not_null); sqlite.create_datatable(key1); //... (unique constraint example) mysql.create_datatable(ormpp_unique{{"name"}}); ``` -------------------------------- ### Integrate PostgreSQL Support with CMake Source: https://github.com/qicosmos/ormpp/blob/master/README.md This CMake snippet shows how to enable PostgreSQL support in ORM++. It sets the necessary build flags and includes the ORM++ library. An alternative configuration demonstrates explicit linking with PostgreSQL libraries and headers. ```cmake set(ENABLE_PG ON) add_definitions(-DORMPP_ENABLE_PG) add_subdirectory(ormpp) ``` ```cmake set(ENABLE_PG ON) add_definitions(-DORMPP_ENABLE_PG) add_library(ormpp INTERFACE) include(ormpp/cmake/pgsql.cmake) target_link_libraries(ormpp INTERFACE ${PGSQL_LIBRARY}) target_include_directories(ormpp INTERFACE ormpp ormpp/ormpp ${PGSQL_INCLUDE_DIR}) ``` -------------------------------- ### Configure SQLite3 Build Source: https://github.com/qicosmos/ormpp/blob/master/thirdparty/CMakeLists.txt Conditional compilation for SQLite3 support. When ENABLE_SQLITE3 is defined, this block configures the build, including adding the SQLite3 static library and specifying include directories. ```cmake if (ENABLE_SQLITE3) add_library(sqlite3 STATIC sqlite3/sqlite3.c) target_include_directories(sqlite3 INTERFACE sqlite3) endif() ``` -------------------------------- ### C++ Compile-Time Options for ormpp Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Illustrates how to enable specific database support (SQLite3, MySQL, PostgreSQL) for the ormpp library during the build process using CMake. This involves setting specific CMake definitions to include the desired database backends. ```bash cmake -B build -DENABLE_SQLITE3=ON -DCMAKE_BUILD_TYPE=Debug cmake --build build --config Debug ``` -------------------------------- ### ORM++ C++ API - Data Querying and Execution Source: https://github.com/qicosmos/ormpp/blob/master/README.md This C++ code snippet presents ORM++ API functions for querying data and executing raw SQL statements. It includes functions for querying single or multiple tables, both with and without pre-processing. An `execute` function allows for running arbitrary SQL commands. ```cpp //查询数据,包括单表查询和多表查询(带预处理) template std::vector query_s(const std::string &str = "", Args &&...args); //查询数据,包括单表查询和多表查询(不带预处理) template [[deprecated]] std::vector query(Args &&...args); //执行原生的sql语句 int execute(const std::string& sql); ``` -------------------------------- ### Integrate SQLite Support with CMake Source: https://github.com/qicosmos/ormpp/blob/master/README.md This CMake snippet enables SQLite3 support for ORM++. It sets the necessary build flags and includes the ORM++ library. An alternative method shows explicit linking with the sqlite3 library and headers. ```cmake set(ENABLE_SQLITE3 ON) add_definitions(-DORMPP_ENABLE_SQLITE3) add_subdirectory(ormpp) ``` ```cmake set(ENABLE_SQLITE3 ON) add_definitions(-DORMPP_ENABLE_SQLITE3) add_subdirectory(ormpp/thirdparty) add_library(ormpp INTERFACE) target_link_libraries(ormpp INTERFACE sqlite3) target_include_directories(ormpp INTERFACE ormpp ormpp/ormpp ormpp/thirdparty/sqlite3) ``` -------------------------------- ### Create Data Table Source: https://github.com/qicosmos/ormpp/blob/master/README.md Creates a new table in the database based on the provided entity structure. Supports defining primary keys, unique constraints, and not null constraints. ```APIDOC ## Create Data Table ### Description Creates a new table in the database based on the provided entity structure. Supports defining primary keys, unique constraints, and not null constraints. ### Method `template bool create_datatable(Args&&... args);` ### Endpoint N/A (Instance method) ### Parameters * `T`: The entity type (struct) representing the table structure. * `Args`: Optional arguments for defining constraints like `ormpp_key`, `ormpp_not_null`, `ormpp_unique`. ### Request Example ```cpp // Create a table without a primary key mysql.create_datatable(); // Create a table with primary key and not null constraints ormpp_key key1{"id"}; ormpp_not_null not_null{{"id", "age"}}; mysql.create_datatable(key1, not_null); // Create a table with a unique constraint on 'name' mysql.create_datatable(ormpp_unique{{"name"}}); ``` ### Response #### Success Response (true) Returns `true` if the table creation is successful. #### Failure Response (false) Returns `false` if the table creation fails. #### Response Example ``` true ``` ``` -------------------------------- ### Insert Multiple Records into Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Demonstrates inserting multiple records into database tables using a `std::vector` of `person` objects for MySQL, PostgreSQL, and SQLite. Returns the number of inserted rows or INT_MIN on failure. ```C++ person p = {1, "test1", 2}; person p1 = {2, "test2", 3}; person p2 = {3, "test3", 4}; std::vector v1{p, p1, p2}; TEST_CHECK(mysql.insert(v1)==3); TEST_CHECK(postgres.insert(v1)==3); TEST_CHECK(sqlite.insert(v1)==3); ``` -------------------------------- ### Create Datatable Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Creates a new database table based on a C++ struct or class. Supports defining primary keys and NOT NULL constraints. ```APIDOC ## Create Datatable ### Description Creates a database table corresponding to a C++ type `T`. Constraints like primary keys and NOT NULL can be specified. ### Method `template bool create_datatable(Args&&... args)` ### Parameters * **`T`**: The C++ type (struct/class) to map to a table. * **`Args`**: Optional constraints such as `ormpp_key` and `ormpp_not_null`. * `ormpp_key`: Defines primary key(s). * `ormpp_not_null`: Defines columns that cannot contain NULL values. ### Request Example ```cpp // Create a table without specific constraints mysql.create_datatable(); postgres.create_datatable(); sqlite.create_datatable(); // Create a table with primary key and NOT NULL constraints ormpp_key key1{"id"}; ormpp_not_null not_null{{"id", "age"}}; // Assuming 'person' struct is defined and reflected mysql.create_datatable(key1, not_null); postgres.create_datatable(key1, not_null); sqlite.create_datatable(key1); ``` ### Response #### Success Response (true) Returns `true` if the table creation is successful. #### Failure Response (false) Returns `false` if the table creation fails. ### Note Currently supports single and multiple primary keys, and NOT NULL constraints. Support for multiple primary keys is planned for future versions. ``` -------------------------------- ### ormpp Database Operations Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md This section outlines the core interfaces provided by ormpp for interacting with databases, including connection management, table creation, data manipulation, querying, and transaction handling. ```APIDOC ## ormpp Database Interfaces ### Description ormpp provides a set of unified and easy-to-use interfaces for common database operations, abstracting away the underlying database specifics. ### Interfaces #### Connection Management * **connect**: Establishes a connection to the database. ```cpp template bool connect(Args&&... args); ``` * **disconnect**: Closes the database connection. ```cpp bool disconnect(); ``` #### Table Management * **create_datatable**: Creates a database table based on a C++ struct/class. ```cpp template bool create_datatable(Args&&... args); ``` #### Data Manipulation * **insert (single record)**: Inserts a single record into the database. ```cpp template int insert(const T& t, Args&&... args); ``` * **insert (multiple records)**: Inserts multiple records from a vector. ```cpp template int insert(const std::vector& t, Args&&... args); ``` * **update (single record)**: Updates a single record in the database. ```cpp template int update(const T& t, Args&&... args); ``` * **update (multiple records)**: Updates multiple records from a vector. ```cpp template int update(const std::vector& t, Args&&... args); ``` * **delete_records**: Deletes records from the database based on specified conditions. ```cpp template bool delete_records(Args&&... where_conditon); ``` #### Querying * **query**: Executes a query to retrieve data. Supports single-table and multi-table queries. ```cpp template auto query(Args&&... args); ``` #### Raw SQL Execution * **execute**: Executes a native SQL statement. ```cpp int execute(const std::string& sql); ``` #### Transaction Management * **begin**: Starts a new database transaction. ```cpp bool begin(); ``` * **commit**: Commits the current transaction. ```cpp bool commit(); ``` * **rollback**: Rolls back the current transaction. ```cpp bool rollback(); ``` ### Example Usage (from provided text) ```cpp #include "dbng.hpp" using namespace ormpp; struct person { int id; std::string name; int age; }; REFLECTION(person, id, name, age) int main() { person p = {1, "test1", 2}; person p1 = {2, "test2", 3}; person p2 = {3, "test3", 4}; std::vector v{p1, p2}; dbng mysql; mysql.connect("127.0.0.1", "dbuser", "yourpwd", "testdb"); mysql.create_datatable(); mysql.insert(p); mysql.insert(v); mysql.update(p); mysql.update(v); auto result = mysql.query(); //vector for(auto& person : result){ std::cout<(); //transaction mysql.begin(); for (int i = 0; i < 10; ++i) { person s = {i, "tom", 19}; if(!mysql.insert(s)){ mysql.rollback(); return -1; } } mysql.commit(); } ``` ``` -------------------------------- ### ORM++ C++ API - Database Connection and Table Operations Source: https://github.com/qicosmos/ormpp/blob/master/README.md This C++ code snippet outlines essential ORM++ API functions for database management. It includes functions for connecting to and disconnecting from a database, creating data tables, and performing basic CRUD operations like insert, replace, update, and delete. ```cpp //连接数据库 template bool connect(Args&&... args); //断开数据库连接 bool disconnect(); //创建数据表 template bool create_datatable(Args&&... args); ``` -------------------------------- ### Query Table Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Queries records from a database table. Supports fetching all records or records matching specific conditions. Returns results as a vector of the specified type. ```APIDOC ## Query Table ### Description Retrieves records from a database table. Results can be filtered using a WHERE clause. If `T` is a reflection object, the result is returned as `std::vector`. ### Method `template auto query(Args&&... args)` ### Parameters * **`T`**: The C++ type to map the query results to. * **`args`**: Optional. A string representing the WHERE clause for the query. If omitted, all records are fetched. ### Request Example ```cpp // Query all records from the 'person' table std::vector result_all_mysql = mysql.query(); std::vector result_all_postgres = postgres.query(); std::vector result_all_sqlite = sqlite.query(); // Query records matching a condition std::vector result_cond_mysql = mysql.query("id=1"); std::vector result_cond_postgres = postgres.query("id=2"); // Assuming sqlite supports the same query condition syntax // std::vector result_cond_sqlite = sqlite.query("id=3"); ``` ### Response #### Success Response (`std::vector`) Returns a `std::vector` of type `T` containing the queried records. The vector will be empty if no records match the criteria or if the query fails in a way that yields no results. #### Error Handling Specific error return values or exceptions for query failures are not detailed in the provided text, but the examples imply successful retrieval or an empty vector. ``` -------------------------------- ### Insert Single Record (MySQL, PostgreSQL, SQLite) Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Demonstrates inserting a single record into a database table. The 'insert' method takes a C++ object and returns 1 on success or INT_MIN on failure. ```cpp // person p = {1, "test1", 2}; // TEST_CHECK(mysql.insert(p)==1); // TEST_CHECK(postgres.insert(p)==1); // TEST_CHECK(sqlite.insert(p)==1); ``` -------------------------------- ### Disconnect from Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Shows how to explicitly disconnect from a database using the `disconnect` method for MySQL, PostgreSQL, and SQLite. It also notes that the disconnection is automatically handled when the database object is destructed. ```C++ mysql.disconnect(); postgres.disconnect(); sqlite.disconnect(); ``` -------------------------------- ### CMake: Conditional Database Library Linking for ORM++ Source: https://github.com/qicosmos/ormpp/blob/master/tests/CMakeLists.txt This CMake snippet demonstrates conditional linking of database libraries for the ORM++ project's test executable. It checks flags like ENABLE_PG, ENABLE_MYSQL, ENABLE_MARIADB, and ENABLE_SQLITE3 to link the appropriate database library and 'doctest'. For MSVC Debug builds with MySQL, it sets a specific compiler flag. ```cmake if(ENABLE_PG) target_link_libraries(${PROJECT_NAME} ${PGSQL_LIBRARY} doctest) elseif(ENABLE_MYSQL) target_link_libraries(${PROJECT_NAME} ${MYSQL_LIBRARY} doctest) if (MSVC AND CMAKE_BUILD_TYPE STREQUAL "Debug") set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/MD") endif() elseif(ENABLE_MARIADB) target_link_libraries(${PROJECT_NAME} ${MARIADB_LIBRARY} doctest) elseif(ENABLE_SQLITE3) target_link_libraries(${PROJECT_NAME} sqlite3 doctest) endif() ``` -------------------------------- ### Insert Multiple Records (MySQL, PostgreSQL, SQLite) Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Shows how to insert multiple records efficiently by passing a std::vector of C++ objects to the 'insert' method. Returns the number of inserted records on success or INT_MIN on failure. ```cpp // person p = {1, "test1", 2}; // person p1 = {2, "test2", 3}; // person p2 = {3, "test3", 4}; // std::vector v1{p, p1, p2}; // TEST_CHECK(mysql.insert(v1)==3); // TEST_CHECK(postgres.insert(v1)==3); // TEST_CHECK(sqlite.insert(v1)==3); ``` -------------------------------- ### Integrate SQLCipher Support with CMake Source: https://github.com/qicosmos/ormpp/blob/master/README.md This CMake configuration enables SQLCipher support within ORM++, requiring both ENABLE_SQLITE3 and ENABLE_SQLITE3_CODEC flags. It also defines preprocessor macros for codec support. The second option demonstrates explicit linking with OpenSSL and SQLite3. ```cmake set(ENABLE_SQLITE3 ON) set(ENABLE_SQLITE3_CODEC)#开启sqlcipher需要同时开启ENABLE_SQLITE3和ENABLE_SQLITE3_CODEC add_definitions( -DORMPP_ENABLE_SQLITE3 -DSQLITE_HAS_CODEC ) add_subdirectory(ormpp) ``` ```cmake set(ENABLE_SQLITE3 ON) set(ENABLE_SQLITE3_CODEC)#开启sqlcipher需要同时开启ENABLE_SQLITE3和ENABLE_SQLITE3_CODEC add_definitions( -DORMPP_ENABLE_SQLITE3 -DSQLITE_HAS_CODEC ) add_subdirectory(ormpp/thirdparty) add_library(ormpp INTERFACE) target_link_libraries(ormpp INTERFACE sqlite3) target_include_directories(ormpp INTERFACE ormpp ormpp/ormpp ormpp/thirdparty/sqlite3) ``` -------------------------------- ### Query Data with Primary Key (PostgreSQL, SQLite) Source: https://github.com/qicosmos/ormpp/blob/master/README.md Executes a query to retrieve records based on a primary key for PostgreSQL and SQLite databases. It returns a vector of 'person' objects. The query string uses placeholders for parameter binding. It expects a single result if the ID exists. ```C++ auto result4 = postgres.query_s("id=$1", 2); TEST_CHECK(result4.size()==1); auto result5 = sqlite.query_s("id=?", 3); TEST_CHECK(result5.size()==1); ``` -------------------------------- ### Enable SQLCipher Definitions for SQLite3 Source: https://github.com/qicosmos/ormpp/blob/master/thirdparty/CMakeLists.txt Defines specific preprocessor macros required for SQLCipher integration with SQLite3. These definitions enable encryption capabilities and thread safety configurations for SQLite. ```cmake if(ENABLE_SQLITE3_CODEC) add_definitions( -DSQLITE_EXTRA_INIT=sqlcipher_extra_init -DSQLITE_EXTRA_SHUTDOWN=sqlcipher_extra_shutdown -DSQLITE_THREADSAFE=2 -DSQLITE_TEMP_STORE=2 -DHAVE_STDINT_H ) endif() ``` -------------------------------- ### Insert Single Record Source: https://github.com/qicosmos/ormpp/blob/master/lang/english/README.md Inserts a single record into a database table. ```APIDOC ## Insert Single Record ### Description Inserts a single object `t` into its corresponding database table. ### Method `template int insert(const T& t, Args&&... args)` ### Parameters * **`t`**: The object to insert. * **`Args`**: Optional arguments (currently not specified for single insert). ### Request Example ```cpp // Assuming 'person' struct is defined and reflected person p = {1, "test1", 2}; // For MySQL int rows_inserted_mysql = mysql.insert(p); // For PostgreSQL int rows_inserted_postgres = postgres.insert(p); // For SQLite int rows_inserted_sqlite = sqlite.insert(p); ``` ### Response #### Success Response (1) Returns `1` indicating one row was successfully inserted. #### Failure Response (INT_MIN) Returns `INT_MIN` if the insertion fails. ``` -------------------------------- ### Update Single Record in Database using C++ Source: https://github.com/qicosmos/ormpp/blob/master/README.md Shows how to update a single record in the database for MySQL, PostgreSQL, and SQLite. Updates are based on the table's key field. If no key field exists, an update column can be specified. ```C++ person p = {1, "test1", 2}; TEST_CHECK(mysql.update(p)==1); TEST_CHECK(postgres.update(p)==1); TEST_CHECK(sqlite.update(p)==1); // ... (update with specified column example) TEST_CHECK(mysql.update(p, "age")==1); TEST_CHECK(postgres.update(p, "age")==1); TEST_CHECK(sqlite.update(p, "age")==1); ```