### Quick Build and Install Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Build and install libpqxx using default configurations. This is a quick way to get the library set up on your system. ```shell ./configure --disable-shared make sudo make install ``` -------------------------------- ### Complete CMakeLists.txt with Installed libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md A minimal CMakeLists.txt example for using an installed libpqxx by finding the package and linking against it. ```cmake cmake_minimum_required(VERSION 3.12) project(ausom) set(CMAKE_CXX_STANDARD 20) add_executable(ausom src/ausom.cxx) find_package(libpqxx REQUIRED) target_link_libraries(ausom PRIVATE pqxx) ``` -------------------------------- ### Install libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Run this command to install libpqxx after configuration. Ensure you have the necessary write permissions for the installation location. ```shell make install ``` -------------------------------- ### Setup Library Target Source: https://github.com/jtv/libpqxx/blob/master/src/CMakeLists.txt Configures include directories, link libraries, and installation for a library target. ```cmake macro(LIBRARY_TARGET_SETUP tgt) target_include_directories(${tgt} PUBLIC $ $ $ PRIVATE ${PostgreSQL_INCLUDE_DIRS} ) target_link_libraries(${tgt} PRIVATE PostgreSQL::PostgreSQL) if(WIN32) target_link_libraries(${tgt} PUBLIC wsock32 ws2_32) endif() install(TARGETS ${tgt} EXPORT libpqxx-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) get_target_property(name ${tgt} NAME) get_target_property(output_name ${tgt} OUTPUT_NAME) if(NOT CMAKE_HOST_WIN32) # Create library symlink get_target_property(target_type ${tgt} TYPE) if(target_type STREQUAL "SHARED_LIBRARY") set(library_prefix ${CMAKE_SHARED_LIBRARY_PREFIX}) set(library_suffix ${CMAKE_SHARED_LIBRARY_SUFFIX}) elseif(target_type STREQUAL "STATIC_LIBRARY") set(library_prefix ${CMAKE_STATIC_LIBRARY_PREFIX}) set(library_suffix ${CMAKE_STATIC_LIBRARY_SUFFIX}) endif() list(APPEND noop_command "${CMAKE_COMMAND}" "-E" "true") list( APPEND create_symlink_command "${CMAKE_COMMAND}" "-E" "create_symlink" "${library_prefix}${output_name}${library_suffix}" "${library_prefix}${name}${library_suffix}") # `add_custom_command()` does nothing if the `OUTPUT_NAME` and `NAME` # properties are equal, otherwise it creates library symlink. add_custom_command(TARGET ${tgt} POST_BUILD COMMAND "$,${noop_command},${create_symlink_command}>" VERBATIM COMMAND_EXPAND_LISTS COMMENT "Ensure library symlink" ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${library_prefix}${name}${library_suffix} DESTINATION ${CMAKE_INSTALL_LIBDIR} ) endif() endmacro() ``` -------------------------------- ### Install libpqxx to a custom prefix Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Specify a custom installation directory using the --prefix option when installing. ```shell cmake --install $BUILD --prefix $DEST ``` -------------------------------- ### Install libpqxx Benchmark Tool Source: https://github.com/jtv/libpqxx/blob/master/tools/CMakeLists.txt Installs the benchmark executable as a system binary if the INSTALL_TOOLS option is enabled. This is useful for deploying the benchmark tool alongside the library. ```cmake if(INSTALL_TOOLS) install( PROGRAMS benchmark TYPE BIN RENAME libpqxx-benchmark ) endif() ``` -------------------------------- ### Install libpqxx to default location Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Use this command to install the library and headers to the system's default location after building. ```shell cmake --install $BUILD ``` -------------------------------- ### Install libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Execute this command after compilation to install libpqxx in the default location. ```shell cmake --install . ``` -------------------------------- ### Install pkg-config File Source: https://github.com/jtv/libpqxx/blob/master/src/CMakeLists.txt Configures and installs the pkg-config file for the library. ```cmake set(prefix ${CMAKE_INSTALL_PREFIX}) # cmake-lint: disable=C0103 set(exec_prefix $ prefix) # cmake-lint: disable=C0103 set(libdir "$ {prefix}/${CMAKE_INSTALL_LIBDIR}") # cmake-lint: disable=C0103 set(includedir "$ {prefix}/${CMAKE_INSTALL_INCLUDEDIR}") set(VERSION ${PROJECT_VERSION}) configure_file( ${PROJECT_SOURCE_DIR}/libpqxx.pc.in ${PROJECT_BINARY_DIR}/libpqxx.pc) install( FILES ${PROJECT_BINARY_DIR}/libpqxx.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) ``` -------------------------------- ### Install libpqxx using HomeBrew on macOS Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Command to install libpqxx on macOS using the HomeBrew package manager. ```shell brew install libpqxx ``` -------------------------------- ### Install libpqxx Development Package on Debian/Ubuntu Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Command to install the libpqxx development package, which includes headers and libraries, on Debian-based systems. ```shell sudo apt-get install libpqxx-dev ``` -------------------------------- ### Install libpqxx Development Package on RedHat/Fedora Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Illustrative command for installing the libpqxx development package on RedHat-flavored systems, using the '-devel' suffix convention. ```shell sudo yum install libpqxx-devel ``` -------------------------------- ### Complete CMakeLists.txt with Embedded libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md A minimal CMakeLists.txt example demonstrating how to embed libpqxx by adding its subdirectory and linking against it. ```cmake cmake_minimum_required(VERSION 3.12) project(ausom) set(CMAKE_CXX_STANDARD 20) add_executable(ausom src/ausom.cxx) add_subdirectory(deps/libpqxx build-pqxx) target_link_libraries(ausom PRIVATE pqxx) ``` -------------------------------- ### Install Test Runner Source: https://github.com/jtv/libpqxx/blob/master/test/CMakeLists.txt This snippet conditionally installs the 'runner' executable as 'libpqxx-test-runner' to the BIN directory if the INSTALL_TEST option is enabled. ```cmake if(INSTALL_TEST) install( PROGRAMS runner TYPE BIN RENAME libpqxx-test-runner ) endif() ``` -------------------------------- ### Find Installed libpqxx Package with CMake Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Use CMake's find_package command to locate an installed libpqxx. This requires libpqxx to be installed and discoverable by CMake. ```cmake find_package(libpqxx REQUIRED) ``` -------------------------------- ### Configure with Custom libpq Paths Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Configure the build to explicitly specify the directories for libpq headers and library binaries, useful when libpq is not installed in a standard location. ```shell --with-postgres-lib=$DIR --with-postgres-include=$DIR ``` -------------------------------- ### Streaming Query Example Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/streams.md Use tx.stream() to read large amounts of data directly from the database. This method is faster than exec() and query() for larger data sets and allows processing data as it arrives. It internally uses PostgreSQL's COPY command, so limitations apply. The example uses structured bindings to unpack tuple fields into variables. ```c++ for (auto [name, score] : tx.stream("SELECT name, points FROM score") ) process(name, score); ``` -------------------------------- ### Basic Database Connection and Query Source: https://github.com/jtv/libpqxx/blob/master/README.md Demonstrates connecting to a PostgreSQL database, starting a transaction, and executing a query to retrieve employee names and salaries. Ensure your PostgreSQL connection string is correctly configured. ```c++ #include #include int main() { try { // Connect to the database. You can have multiple connections open // at the same time, even to the same database. pqxx::connection cx; std::cout << "Connected to " << cx.dbname() << '\n'; // Start a transaction. A connection can only have one transaction // open at the same time, but after you finish a transaction, you // can start a new one on the same connection. pqxx::work tx{cx}; // Query data of two columns, converting them to std::string and // int respectively. Iterate the rows. for (auto [name, salary] : tx.query( "SELECT name, salary FROM employee ORDER BY name")) ``` -------------------------------- ### Basic Database Connection and Query Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/getting-started.md Connects to the default database, executes a simple query to get the number 1, commits the transaction, and prints the result as an integer. Includes basic error handling for database operations. ```c++ #include #include int main() { try { // Connect to the database. In practice we may have to pass some // arguments to say where the database server is, and so on. // The constructor parses options exactly like libpq's // PQconnectdb/PQconnect, see: // https://www.postgresql.org/docs/10/static/libpq-connect.html pqxx::connection cx; // Start a transaction. In libpqxx, you always work in one. pqxx::work tx(cx); // We'll just ask the database to return the number 1 to us. // The one_row() call checks that the result contains exactly one row // of data, and throws an exception if it does not. It returns the // row. pqxx::row r = tx.exec("SELECT 1").one_row(); // Commit your transaction. If an exception occurred before this // point, execution will have left the block, and the transaction will // have been destroyed along the way. In that case, the failed // transaction would implicitly abort instead of getting to this point. tx.commit(); // Look at the first and only field in the row, parse it as an integer, // and print it. // // "r[0]" returns the first field, which has an "as<...>()" member // function template to convert its contents from their string format // to a type of your choice. std::cout << r[0].as() << std::endl; } catch (std::exception const &e) { std::cerr << e.what() << std::endl; return 1; } } ``` -------------------------------- ### Find and Link PostgreSQL with libpqxx Source: https://github.com/jtv/libpqxx/blob/master/tools/CMakeLists.txt Configures CMake to find the PostgreSQL development package and links the libpqxx library and PostgreSQL to the executable. Ensure PostgreSQL is installed and discoverable by CMake. ```cmake if(NOT PostgreSQL_FOUND) find_package(PostgreSQL REQUIRED) endif() add_executable(benchmark benchmark.cxx) target_link_libraries(benchmark PUBLIC pqxx PostgreSQL::PostgreSQL) target_include_directories(benchmark PRIVATE ${PostgreSQL_INCLUDE_DIRS}) ``` -------------------------------- ### Full string_traits Specialization Example Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/datatypes.md This is a template for specializing the pqxx::string_traits for a custom type T. It includes methods for converting to an SQL string (to_buf, size_buffer) and from an SQL string (from_string). ```c++ namespace pqxx { // T is your type. template<> struct string_traits { // If you support conversion _to_ an SQL string: // Represent `value` as a string, using `buf` for storage if needed. // (But the result may live somewhere outside the buffer, or lie inside // it but not start exactly at the beginning of the buffer. It may even // be a reference back to `value` itself.) // // We'll explain the context `c` further down. static [[nodiscard]] std::string_view to_buf( std::span buf, T const &value, ctx c = {}); // Converting value to string may require at most this much buffer space. static [[nodiscard]] std::size_t size_buffer(T const &value) noexcept; // If you support conversion _from_ an SQL string: // Parse `text` as a T value. static [[nodiscard]] T from_string(std::string_view text, ctx c = {}); }; } ``` -------------------------------- ### Execute Plain Statement Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/parameters.md Example of executing a plain SQL statement without parameters. This method is generally discouraged due to security risks and awkwardness in handling values. ```c++ pqxx::result r = tx.exec("SELECT name FROM employee where id=101"); ``` -------------------------------- ### Basic Configuration Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Configure the libpqxx build in a specified directory. This command sets up Makefiles based on system parameters and compiler support. ```shell cd $BUILD $SRC/configure ``` -------------------------------- ### Configure libpqxx Build and Testing Source: https://github.com/jtv/libpqxx/blob/master/test/CMakeLists.txt This snippet sets up testing, finds the PostgreSQL library, and compiles the test runner executable. It links the necessary libraries and includes directories for the test runner. ```cmake enable_testing() if(NOT PostgreSQL_FOUND) find_package(PostgreSQL REQUIRED) endif() file(GLOB TEST_SOURCES *.cxx) add_executable(runner ${TEST_SOURCES}) target_link_libraries(runner PUBLIC pqxx) target_include_directories(runner PRIVATE ${PostgreSQL_INCLUDE_DIRS}) ``` -------------------------------- ### Include All libpqxx Headers Source: https://github.com/jtv/libpqxx/blob/master/README.md Include all necessary libpqxx headers for your program. This is a convenient way to ensure all functionalities are available. ```c++ #include ``` -------------------------------- ### Run libpqxx Test Suite Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Execute the test suite for libpqxx. Ensure a database is accessible for the tests to run. ```shell test/runner ``` -------------------------------- ### Checkout Development Version Source: https://github.com/jtv/libpqxx/blob/master/README.md How to checkout the development version of libpqxx from Git. ```sh git checkout 7.1.1 ``` -------------------------------- ### Build Executables and Link libpqxx with CMake Source: https://github.com/jtv/libpqxx/blob/master/examples/CMakeLists.txt This snippet iterates through all .cxx files, creates an executable for each, links it with the 'pqxx' library, and adds a test for it. Use this to build multiple executables from source files in a directory. ```cmake file(GLOB SOURCE_FILES "*.cxx") foreach(source_file ${SOURCE_FILES}) get_filename_component(name ${source_file} NAME_WLE) add_executable(${name} ${source_file}) target_link_libraries(${name} PRIVATE pqxx) add_test(NAME ${name} COMMAND ${name}) endforeach() ``` -------------------------------- ### Prepare a Statement with Parameters in pqxx Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/prepared-statement.md Prepare a statement that accepts parameters, using placeholders like $1, $2. The statement is identified by the name 'find'. ```c++ void prepare_find(pqxx::connection &cx) { // Prepare a statement called "find" that looks for employees with a // given name (parameter 1) whose salary exceeds a given number // (parameter 2). cx.prepare( "find", "SELECT * FROM Employee WHERE name = $1 AND salary > $2"); } ``` -------------------------------- ### Configure libpqxx build Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Use this command to configure your libpqxx build. Specify the source directory and any necessary CMake options. ```shell cd $BUILD cmake $SRC ``` -------------------------------- ### Execute a Prepared Statement with Parameters in pqxx Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/prepared-statement.md Execute a prepared statement named 'find' with provided parameters for name and minimum salary. Uses pqxx::params for parameter binding. ```c++ pqxx::result execute_find( pqxx::transaction_base &tx, std::string name, int min_salary) { return tx.exec(pqxx::prepped{"find"}, pqxx::params{name, min_salary}); } ``` -------------------------------- ### Compile libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Run this command from the root of the libpqxx source tree after configuration to compile the library. ```shell cmake --build . ``` -------------------------------- ### Run Test Suite with make check Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Execute the test suite to verify the library's functionality. Ensure a database is available for the tests to use, as they will create and drop tables. ```shell make check ``` ```shell make check -j$(nproc) ``` -------------------------------- ### Prepare a Simple Statement in pqxx Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/prepared-statement.md Prepare a SQL statement with a given name on a connection. This statement can later be invoked by its name. ```c++ void prepare_my_statement(pqxx::connection &cx) { cx.prepare( "my_statement", "SELECT * FROM Employee WHERE name = 'Xavier'"); } ``` -------------------------------- ### Uninstall libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Run this command to uninstall libpqxx. It is recommended to keep your build tree to facilitate uninstallation. ```shell make uninstall ``` -------------------------------- ### Specify libpq Include and Library Paths Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Manually set the directories for libpq headers and library binaries if CMake's find_package fails or needs overriding. ```shell cmake -DPostgreSQL_TYPE_INCLUDE_DIR=$DIR ``` ```shell cmake -DPostgreSQL_INCLUDE_DIR=$DIR ``` ```shell cmake -DPostgreSQL_LIBRARY_DIR=$DIR ``` -------------------------------- ### Execute a Prepared Statement in pqxx Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/prepared-statement.md Execute a previously prepared statement by its name using pqxx::prepped. This is useful for statements that do not require parameters. ```c++ pqxx::result execute_my_statement(pqxx::transaction_base &t) { return t.exec(pqxx::prepped{"my_statement"}); } ``` -------------------------------- ### Configure with Disabled Documentation and No Optimization Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Configure the build to skip documentation generation and disable compiler optimizations for a faster build, though the resulting code will be less efficient. ```shell ./configure --disable-documentation CXXFLAGS=-O0 ``` -------------------------------- ### Generate Placeholders for Complex Queries Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/parameters.md Illustrates using the `pqxx::placeholders` class to generate SQL placeholders ($1, $2, etc.) and manage corresponding parameter values in complex query construction. This helps track which value corresponds to which placeholder. ```c++ pqxx::params values; pqxx::placeholders name; ``` ```c++ if (extra_clause) { // Extend the query text, using the current placeholder. query += " AND x = " + name.get(); // Add the parameter value. values.append(my_x); // Move on to the next placeholder value. name.next(); } ``` -------------------------------- ### Compile libpqxx Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Invoke the build tool configured by CMake to compile the libpqxx library. Consider using parallel jobs with '-j' for faster builds, but do not use with Ninja. ```shell cmake --build $BUILD ``` -------------------------------- ### Parallel Compilation with make Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Use the `-j` option with `make` to run multiple compiler processes concurrently for faster builds. It's often fastest to use one process per CPU core. ```shell make -j8 ``` ```shell make -j$(nproc) ``` -------------------------------- ### Construct pqxx::params Object Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/parameters.md Shows different ways to construct a pqxx::params object, which holds the values for statement parameters. Values can be passed during construction or appended individually. ```c++ pqxx::params{23, "acceptance", 3.14159} ``` ```c++ pqxx::params p; p.append(23); p.append("acceptance"); p.append(3.14159); ``` ```c++ pqxx::params p{23}; p.append(params{"acceptance", 3.14159}); ``` -------------------------------- ### Execute Query and Check Row Count Source: https://github.com/jtv/libpqxx/blob/master/README.md Executes an UPDATE statement and asserts that it returns zero rows. Throws pqxx::unexpected_rows if the query returns any data. ```cpp // Execute a statement, and check that it returns 0 rows of data. // This will throw pqxx::unexpected_rows if the query returns rows. std::cout << "Doubling all employees' salaries...\n"; tx.exec("UPDATE employee SET salary = salary*2").no_rows(); ``` -------------------------------- ### Include libpqxx in a CMakeLists.txt file Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Fragment for a CMakeLists.txt file to include libpqxx in another project. It sets the libpqxx directory, skips tests, and configures shared library building based on the platform. ```cmake # (First set LIBVERSION to the libpqxx version you have.) set(libpqxxdir "libpqxx-${LIBVERSION}") # You can usually skip building the tests. set(SKIP_BUILD_TEST ON) # On Windows we generally recommend building libpqxx as a shared # library. On other platforms, we recommend a static library. IF (WIN32) set(BUILD_SHARED_LIBS ON) ELSE() set(BUILD_SHARED_LIBS OFF) ENDIF() add_subdirectory(${libpqxxdir}) ``` -------------------------------- ### Execute Statement with Parameter Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/parameters.md Demonstrates executing an SQL statement using a parameter for the WHERE clause. This is the recommended approach for security and clarity, preventing SQL injection. ```c++ pqxx::result r = tx.exec("SELECT name FROM employee WHERE id=$1", {101}); ``` -------------------------------- ### Streaming Data into a Table with libpqxx Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/streams.md Use `stream_to` to efficiently write data directly to a database table, avoiding individual INSERT statements. Ensure `complete()` is called to properly finalize the stream and make any potential errors visible. ```c++ pqxx::stream_to stream{ tx, "score", std::vector{"name", "points"}}; for (auto const &entry: scores) stream << entry; stream.complete(); ``` -------------------------------- ### Add libpqxx Subdirectory to CMakeLists.txt Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Include the libpqxx source tree as a subdirectory in your CMake project. This method builds libpqxx along with your project. ```cmake add_subdirectory(deps/libpqxx build-pqxx) ``` -------------------------------- ### Define pqxx Library Source: https://github.com/jtv/libpqxx/blob/master/src/CMakeLists.txt Defines the main pqxx library target and an alias. Sets output name and compile definitions based on library type. ```cmake file(GLOB CXX_SOURCES *.cxx) add_library(pqxx ${CXX_SOURCES}) add_library(libpqxx::pqxx ALIAS pqxx) get_target_property(pqxx_target_type pqxx TYPE) if(pqxx_target_type STREQUAL "SHARED_LIBRARY") target_compile_definitions(pqxx PUBLIC PQXX_SHARED) endif() # cmake-lint: disable=C0301 set_target_properties( pqxx PROPERTIES OUTPUT_NAME $,pqxx,pqxx-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}> ) LIBRARY_TARGET_SETUP(pqxx) ``` -------------------------------- ### Configure for Debugging with Maximum Optimization Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-configure.md Configure the build with maintainer mode and audit enabled for extensive debugging checks, along with maximum compiler optimization for performance analysis. ```shell ./configure --enable-maintainer-mode --enable-audit CXXFLAGS=-O3 ``` -------------------------------- ### SQL Query with Statement Parameters Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/escaping.md This code demonstrates the preferred method of passing variable data to SQL queries using statement parameters. This is generally safer and more efficient than manual string escaping. ```cxx tx.exec( " SELECT number, amount " "FROM account " "WHERE allowed_to_see($1, $2)", pqxx::params{tx, userid, password}); ``` -------------------------------- ### Specify PostgreSQL Root Directory Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Provide the root path to a full PostgreSQL build tree for CMake to find libpq, requires CMake 3.12 or newer. ```shell cmake -DPostgreSQL_ROOT=$DIR ``` -------------------------------- ### Access Result Metadata Source: https://github.com/jtv/libpqxx/blob/master/README.md Executes a query and retrieves a pqxx::result object to access metadata like column names. ```cpp // If you need to access the result metadata, not just the actual // field values, use `exec()`. It returns a pqxx::result object. pqxx::result res = tx.exec("SELECT * FROM employee"); std::cout << "Columns:\n"; for (pqxx::row_size_type col = 0; col < res.columns(); ++col) std::cout << res.column_name(col) << '\n'; ``` -------------------------------- ### Convert C-style string to bytes_view for writing Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/binary-data.md Use the pointer and length overload of `pqxx::binary_cast` to convert a C-style string (char array) into a `pqxx::bytes_view` for writing to a blob. This is useful when dealing with raw character arrays. ```c++ char const greeting[] = "Hello binary world"; char const *hi = greeting; my_blob.write(pqxx::binary_cast(hi, sizeof(greeting))); ``` -------------------------------- ### Safe Embedding of User Input in SQL Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/getting-started.md Retrieves a string from command-line arguments and safely embeds it into an SQL query using `pqxx::params`. This prevents SQL injection vulnerabilities. It also shows how to read the result field as a C-style string. ```c++ #include #include #include int main(int, char *argv[]) { try { if (!argv[1]) throw std::runtime_error("Give me a string!"); pqxx::connection cx; pqxx::work tx(cx); // work::exec() returns a full result set, which can consist of any // number of rows. pqxx::result r = tx.exec("SELECT $1", pqxx::params{argv[1]}); ``` -------------------------------- ### Link libpqxx to Target in CMakeLists.txt Source: https://github.com/jtv/libpqxx/blob/master/BUILDING-cmake.md Specify libpqxx as a private dependency for your target executable or library. This ensures your code links against the libpqxx library. ```cmake target_link_libraries(ausom PRIVATE pqxx) ``` -------------------------------- ### Convert std::string to bytes_view for writing Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/binary-data.md Use `pqxx::binary_cast` to convert a `std::string` into a `pqxx::bytes_view` for writing to a blob. Ensure the target is a `pqxx::blob` object. ```c++ std::string hi{"Hello binary world"}; my_blob.write(pqxx::binary_cast(hi)); ``` -------------------------------- ### Execute Query and Stream Results Source: https://github.com/jtv/libpqxx/blob/master/README.md Executes a query and streams results efficiently for large datasets. Fields can be read as std::string_view for single-iteration use. ```cpp { std::cout << name << " earns " << salary << ".\n"; } // For large amounts of data, "streaming" the results is more // efficient. It does not work for all types of queries though. // // You can read fields as std::string_view here, which is not // something you can do in most places. A string_view becomes // meaningless when the underlying string ceases to exist. In this // particular situation, you can convert a field to string_view and // it will be valid for just that one iteration of the loop. The // next iteration may overwrite or deallocate its buffer space. for (auto [name, salary] : tx.stream( "SELECT name, salary FROM employee")) { std::cout << name << " earns " << salary << ".\n"; } ``` -------------------------------- ### Convert Integer to String Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/datatypes.md Use `to_string` to convert an integer value to its string representation for database queries. ```c++ auto x = to_string(99); ``` -------------------------------- ### Find PostgreSQL Package Source: https://github.com/jtv/libpqxx/blob/master/src/CMakeLists.txt Finds the PostgreSQL development package. It handles policy changes for PostgreSQL_ROOT. ```cmake if(NOT PostgreSQL_FOUND) if(POLICY CMP0074) cmake_policy(PUSH) # CMP0074 is `OLD` by `cmake_minimum_required(VERSION 3.7)`, # sets `NEW` to enable support CMake variable `PostgreSQL_ROOT`. cmake_policy(SET CMP0074 NEW) endif() find_package(PostgreSQL REQUIRED) if(POLICY CMP0074) cmake_policy(POP) endif() endif() ``` -------------------------------- ### Converting Row to Multiple C++ Types Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/getting-started.md Demonstrates converting an entire row of data into multiple C++ variables of specified types using structured binding. This is useful for retrieving multiple columns at once. ```c++ pqxx::connection cx; pqxx::work tx(cx); pqxx::row r = tx.exec("SELECT 1, 2, 'Hello'").one_row(); auto [one, two, hello] = r.as(); std::cout << (one + two) << ' ' << std::size(hello) << std::endl; ``` -------------------------------- ### Streaming Query Results Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/accessing-results.md Stream query results for potentially faster processing, especially with large datasets. This method uses PostgreSQL's COPY command and supports specific query types. Be aware that views to data are only valid within the loop iteration. ```c++ for (auto [id, name, x, y] : tx.stream( "SELECT id, name, x, y FROM point")) process(id + 1, "point-" + name, x * 10.0, y * 10.0); ``` -------------------------------- ### Error Handling Source: https://github.com/jtv/libpqxx/blob/master/README.md Basic exception handling for database operations, catching std::exception and printing error messages. ```cpp } catch (std::exception const &e) { std::cerr << "ERROR: " << e.what() << '\n'; return 1; } return 0; } ``` -------------------------------- ### Convert String to Integer Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/datatypes.md Use `from_string` with explicit template instantiation to convert a string value to an integer type. ```c++ auto y = from_string("99"); ``` -------------------------------- ### Two-Dimensional Array Access for Fields Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/accessing-results.md Access fields directly using a two-dimensional index (row, column) for potentially faster access compared to classic indexing. Requires C++23 or later. ```c++ for (std::size_t rownum=0u; rownum < num_rows; ++rownum) { for (std::size_t colnum=0u; colnum < num_cols; ++colnum) std::cout result[rownum, colnum].c_str() << '\t'; std::cout << '\n'; } ``` -------------------------------- ### Vulnerable SQL Query Construction Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/escaping.md This code demonstrates a common SQL injection vulnerability where user-provided strings are directly concatenated into an SQL query. Avoid this pattern. ```cxx tx.exec( "SELECT number, amount " "FROM account " "WHERE allowed_to_see('" + userid + "','" + password + "')"); ``` -------------------------------- ### Iterating Rows and Fields as Raw Text Source: https://github.com/jtv/libpqxx/blob/master/include/pqxx/doc/accessing-results.md Iterate through each row and field of a result set, printing field values as raw C-style strings. This is useful for simple display or when type conversion is not immediately needed. ```c++ pqxx::result r = tx.exec("SELECT * FROM mytable"); for (auto const &row_ref: r) { for (auto const &field_ref: row) std::cout << field.c_str() << '\t'; std::cout << '\n'; } ```