### Build Example Binaries Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/zlib/CMakeLists.txt Conditionally builds example executables ('example', 'minigzip') and their 64-bit variants if HAVE_OFF64_T is defined. These examples are linked against the zlib library. ```cmake if(ZLIB_BUILD_EXAMPLES) add_executable(example test/example.c) target_link_libraries(example zlib) add_test(example example) add_executable(minigzip test/minigzip.c) target_link_libraries(minigzip zlib) if(HAVE_OFF64_T) add_executable(example64 test/example.c) target_link_libraries(example64 zlib) set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") add_test(example64 example64) add_executable(minigzip64 test/minigzip.c) target_link_libraries(minigzip64 zlib) set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") endif() endif() ``` -------------------------------- ### Install Protobuf with nmake Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Install the compiled Protocol Buffers to the specified 'install' folder. This makes the protoc compiler, headers, and libraries available. ```bash C:\Path\to\protobuf\cmake\build\release>nmake install ``` ```bash C:\Path\to\protobuf\cmake\build\debug>nmake install ``` -------------------------------- ### Final Example Configuration Message Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/examples/CMakeLists.txt Prints a status message indicating that the examples configuration is complete. ```cmake MESSAGE(STATUS "Configuring examples") ``` -------------------------------- ### Install Connector Library (Release/RelWithDebInfo) Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/CMakeLists.txt Installs the connector library for Release and RelWithDebInfo configurations. ```cmake install(TARGETS connector CONFIGURATIONS Release RelWithDebInfo ARCHIVE DESTINATION "${INSTALL_LIB_DIR_STATIC}" COMPONENT XDevAPIDev RUNTIME DESTINATION "${INSTALL_LIB_DIR}" COMPONENT XDevAPIDll LIBRARY DESTINATION "${INSTALL_LIB_DIR}" COMPONENT XDevAPIDll ) ``` -------------------------------- ### Install Protobuf with zlib support using vcpkg Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Install Protocol Buffers with optional zlib support using vcpkg. Ensure both the base package and the zlib feature are installed for the target architecture. ```powershell >vcpkg install protobuf[zlib] protobuf[zlib]:x64-windows ``` -------------------------------- ### Build and install Protocol Buffers C++ Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Compiles and installs the Protocol Buffer runtime and compiler. Includes a check step to verify functionality. ```bash ./configure make make check sudo make install sudo ldconfig ``` -------------------------------- ### Configure Protocol Buffers installation prefix Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Specifies the installation directory using the --prefix option during configuration. Useful if /usr/local/lib is not in LD_LIBRARY_PATH. ```bash ./configure --prefix=/usr ``` -------------------------------- ### Windows CMake Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/process_launcher/CMakeLists.txt Example CMake command for building on Windows, specifying Boost and GMock paths. ```bash cmake -DBOOST_INCLUDE_DIR=C:\src\mysql-server\boost\boost_1_56_0 -DBOOST_LIB_DIR=C:\src\mysql-server\boost\boost_1_56_0\stage\lib -DMY_INCLUDE_DIR=C:\src\mysql-server\MyIncludes -DMY_GMOCK_LIB_DIR=C:\src\mysql-server\MyLibs -DGMOCK_LIBRARIES=gmock ..\process_launcher ``` -------------------------------- ### Compile and Install ZLib Library Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Steps to obtain, compile, and install the zlib library from source. This is required for using GzipInputStream and GzipOutputStream in Protocol Buffers. ```bash C:\Path\to>git clone -b v1.2.8 https://github.com/madler/zlib.git C:\Path\to>cd zlib ``` ```bash C:\Path\to\zlib>mkdir build & cd build ``` -------------------------------- ### Complete X DevAPI Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/doc/devapi_ref.txt The full source code for the X DevAPI example, including session creation, document insertion, fetching, and processing. ```cpp #include #include #include #include #include "mysqlx_test_framework.h" using namespace std; using namespace mysqlx; // Test case for the X DevAPI // // This test case is intended to be run against a MySQL Server that has // the X Plugin enabled. The X Plugin is enabled by default in MySQL 8.0. // // The test case is intended to demonstrate the usage of the Connector/C++ // X DevAPI. It covers the following operations: // // - Creating a session // - Creating a collection // - Inserting documents // - Fetching documents // - Accessing document fields // - Processing sub-documents and arrays // - Handling errors // // The test case is organized as follows: // // 1. Setup: Connect to the server and get a session. // 2. Document insertion: Insert several documents into a collection. // 3. Document fetching: Fetch the inserted documents. // 4. Field access: Access and print individual fields of the documents. // 5. Sub-document and array processing: Demonstrate handling of nested structures. // 6. Error handling: Show how to catch and report errors. // 7. Cleanup: Close the session. // // Note: This test case assumes that the MySQL Server is running and accessible // on localhost:13009. It also assumes that the 'test' database and a collection // named 'mycollection' exist or can be created. // // For more information on the X DevAPI, please refer to the official MySQL // Connector/C++ documentation. // // Copyright (c) 2015, 2024, Oracle and/or its affiliates. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License, version 2.0, as // published by the Free Software Foundation. // // This program is also distributed with certain software (including // but not limited to OpenSSL) that is licensed under separate terms, // as designated in a particular file or component or in included license // documentation. The authors of MySQL hereby grant you an // additional permission to link the program and your derivative works // with the separately licensed software that they have included with // MySQL. // // Without limiting anything contained in the foregoing, this file, // which is part of MySQL Connector/C++, is also subject to the // Universal FOSS Exception, version 1.0, a copy of which can be found at // http://oss.oracle.com/licenses/universal-foss-exception. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License, version 2.0, for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // int main(int argc, char **argv) { // Initialize the X DevAPI client Client client("mysqlx://user:password@localhost:13009"); // Create a session cout << "Creating session on localhost, port 13009 ..." << endl; Session session(client.getSession()); cout << "Session accepted, creating collection..." << endl; // Get a collection (create if it doesn't exist) Collection collection = session.getSchema("test").getCollection("mycollection", true); // Insert documents cout << "Inserting documents..." << endl; collection.add( R"({"_id": "AA71B4BF6B72E511BD76001E684A06F0", "age": 3, "date": {"day": 20, "month": "Apr"}, "name": "baz"})") .execute(); collection.add( R"({"_id": "2885B4BF6B72E511BD76001E684A06F0", "age": 2, "name": "bar", "toys": ["car", "ball"]})") .execute(); collection.add( R"({"_id": "3492B4BF6B72E511BD76001E684A06F0", "age": 4, "name": "foo"})") .execute(); collection.add( R"({"_id": "myuuid-1", "name": "test"})") .execute(); // Fetch documents cout << "Fetching documents..." << endl; DocResult res = collection.find("{\"name\": \"baz\"}").execute(); // Process fetched documents int i = 0; for (DbDoc doc : res) { cout << "\ndoc#" << i++ << ": " << doc.toString() << endl; cout << " field `_id`: " << doc.get("_id").toString() << endl; cout << " field `age`: " << doc.get("age").get() << endl; cout << " field `date": " << doc.get("date").toString() << endl; cout << " field `name": " << doc.get("name").toString() << endl; // Accessing fields of a sub-document if (doc.has("date")) { DbDoc date = doc.get("date"); cout << " name: " << doc.get("name") << endl; cout << "- date field" << endl; cout << " date `day`: " << date.get("day").get() << endl; cout << " date `month": " << date.get("month").toString() << endl; } // Accessing elements of an array if (doc.has("toys")) { cout << "- toys:" << endl; for (const auto& toy : doc.get("toys").getArray()) { cout << " " << toy.toString() << endl; } } } // Example of error handling try { collection.remove("{\"_id\": \"non-existent-id\"}").execute(); } catch (const mysqlx::Error& err) { cerr << "Caught expected error: " << err.what() << endl; } cout << "\nDone!" << endl; return 0; } ``` -------------------------------- ### Configure Protobuf with ZLIB Support Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Invokes CMake to configure the Protobuf build, enabling ZLIB support by setting the -Dprotobuf_WITH_ZLIB=ON flag. This example assumes ZLIB has been built and installed. ```bash cmake -Dprotobuf_WITH_ZLIB=ON ``` -------------------------------- ### Include Directories Setup Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/CMakeLists.txt Sets up include directories for the project, including ZLIB and protobuf-specific paths. ```cmake include_directories( ${ZLIB_INCLUDE_DIRECTORIES} ${protobuf_BINARY_DIR} ${protobuf_source_dir}/src) ``` -------------------------------- ### Install zlib Libraries and Headers Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/zlib/CMakeLists.txt Defines installation rules for the zlib library targets (shared and static), public headers, man pages, and pkg-config files. These rules are conditional on not skipping installation. ```cmake if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL ) install(TARGETS zlib zlibstatic RUNTIME DESTINATION "${INSTALL_BIN_DIR}" ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" LIBRARY DESTINATION "${INSTALL_LIB_DIR}" ) endif() if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL ) install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION "${INSTALL_INC_DIR}") endif() if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) install(FILES zlib.3 DESTINATION "${INSTALL_MAN_DIR}/man3") endif() if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) install(FILES ${ZLIB_PC} DESTINATION "${INSTALL_PKGCONFIG_DIR}") endif() ``` -------------------------------- ### Install Protobuf using vcpkg Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Install Protocol Buffers and its dependencies using the vcpkg package manager. Specify the desired architecture, such as x64-windows. ```powershell >vcpkg install protobuf protobuf:x64-windows ``` -------------------------------- ### Install Connector Library (Debug) Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/CMakeLists.txt Installs the connector library for Debug configurations. ```cmake install(TARGETS connector CONFIGURATIONS Debug ARCHIVE DESTINATION "${INSTALL_LIB_DIR_STATIC_DEBUG}" COMPONENT XDevAPIDev RUNTIME DESTINATION "${INSTALL_LIB_DIR_DEBUG}" COMPONENT XDevAPIDll LIBRARY DESTINATION "${INSTALL_LIB_DIR_DEBUG}" COMPONENT XDevAPIDll ) ``` -------------------------------- ### Configure Tests with Default Installation Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/testing/find_package/README.txt Run CMake to configure tests when the connector is installed OS-wide. Point CMake to the test directory. ```bash cmake ${SRC_DIR}/testing/find_package ``` -------------------------------- ### Interactive Program Notice (GPL) Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/LICENSE.txt This notice should be displayed by interactive programs when they start, informing users about the program's free software status, warranty, and redistribution conditions under the GPL. It guides users on how to view the full license details. ```text Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Include Examples Module Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/CMakeLists.txt Conditionally includes the 'examples.cmake' module if the protobuf_BUILD_EXAMPLES option is enabled. ```cmake if (protobuf_BUILD_EXAMPLES) include(examples.cmake) endif (protobuf_BUILD_EXAMPLES) ``` -------------------------------- ### Build and Link JDBC Example Executables Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/examples/CMakeLists.txt Iterates through a list of example names, creating an executable for each. It sets target properties for linking flags, compile flags, and folder organization, then links necessary libraries and adds them as tests. ```cmake foreach(example connect connection_meta_schemaobj debug_output exceptions prepared_statement resultset resultset_binary resultset_meta resultset_types statement dynamic_load ) ADD_EXECUTABLE(${example} ${example}.cpp) SET_TARGET_PROPERTIES(${example} PROPERTIES LINK_FLAGS "${MYSQLCPPCONN_LINK_FLAGS_ENV} ${MYSQL_LINK_FLAGS}" COMPILE_FLAGS "${MYSQLCPPCONN_COMPILE_FLAGS_ENV}" FOLDER "Tests/jdbc" ) TARGET_LINK_LIBRARIES(${example} ${MY_TARGET_LINK_LIBRARIES} ${MY_GCOV_LINK_LIBRARIES} ${MYSQLCPPCONN_BOOST_THREAD_LIBS} ${MYSQLCPPCONN_ICU_LIBRARY} ) ADD_TEST(jdbc_${example} ${example}) install_test(${example} ${example}) endforeach() ``` -------------------------------- ### Install Thread Libraries Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/thread/CMakeLists.txt Defines installation rules for the shared and static thread libraries. The destination directory depends on the operating system. ```cmake IF(WIN32) INSTALL(TARGETS mysqlcppconn_thread mysqlcppconn_thread-static RUNTIME DESTINATION lib ARCHIVE DESTINATION lib COMPONENT JDBCDev ) ELSE(WIN32) INSTALL(TARGETS mysqlcppconn_thread mysqlcppconn_thread-static LIBRARY DESTINATION ${INSTALL_LIBDIR} ARCHIVE DESTINATION ${INSTALL_LIBDIR} COMPONENT JDBCDev ) ENDIF(WIN32) ``` -------------------------------- ### Manual CDK Setup and Linking Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/usage.rst An alternative to ADD_CDK is to manually set up the include path for CDK using CDK_SETUP() and then link the 'cdk' library to your target. ```cmake CDK_SETUP() ADD_LIBRARY(foo ...) TARGET_LINK_LIBRARIES(foo cdk) ``` -------------------------------- ### Establish TCP/IP Connection and Protocol Instance Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/usage.rst Establishes a TCP/IP connection to the server and creates a Protocol instance for communication. This is the initial setup for client-server interaction. ```cpp connection::TCPIP conn("localhost", PORT); cout <<"Connectiog to port " < CONFIGURATIONS RelWithDebInfo DESTINATION "${INSTALL_LIB_DIR}" COMPONENT Debuginfo ) install(FILES $ CONFIGURATIONS Debug DESTINATION "${INSTALL_LIB_DIR_DEBUG}" COMPONENT Debuginfo ) endif() ``` -------------------------------- ### Configure Visual Studio Solution Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Configure the build to generate a Visual Studio solution file. Specify the Visual Studio version and the installation prefix. ```bash C:\Path\to\protobuf\cmake\build>mkdir solution & cd solution C:\Path\to\protobuf\cmake\build\solution>cmake -G "Visual Studio 16 2019" ^ -DCMAKE_INSTALL_PREFIX=../../../../install ^ ../.. ``` -------------------------------- ### Add Install Bin to System PATH Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Appends the 'bin' directory from the ZLIB installation to the system's PATH environment variable. This is necessary for the Protobuf build to find ZLIB executables. ```bash C:\Path\to>set PATH=%PATH%;C:\Path\to\install\bin ``` -------------------------------- ### CMake Minimum Requirements and Project Setup Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/process_launcher/CMakeLists.txt Sets the minimum required CMake version and defines the project name. ```cmake cmake_minimum_required (VERSION 2.8) project (process_launcher) ``` -------------------------------- ### Configure Release Build with NMake Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/README.md Configure the build for a Release configuration using the NMake Makefile generator. Sets the installation prefix and build type. ```bash C:\Path\to\protobuf\cmake\build>mkdir release & cd release C:\Path\to\protobuf\cmake\build\release>cmake -G "NMake Makefiles" ^ -DCMAKE_BUILD_TYPE=Release ^ -DCMAKE_INSTALL_PREFIX=../../../../install ^ ../.. ``` -------------------------------- ### Compile a C++ program with Protocol Buffers Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Example of compiling a C++ program that uses Protocol Buffers, including the necessary flags obtained via pkg-config. ```bash c++ my_program.cc my_proto.pb.cc `pkg-config --cflags --libs protobuf` ``` -------------------------------- ### Authentication Handshake Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/designs/protocol.rst Demonstrates how to perform an authentication handshake using the Protocol API. It involves sending an initial authentication message and handling server replies. ```APIDOC ## Authentication Handshake ### Description This example shows the process of authenticating with the server using the `Protocol` class and an `Auth_handler`. ### Usage ```cpp #include #include #include using namespace cdk; using namespace cdk::protocol::mysqlx; // Assume conn is an initialized foundation::api::Connection object foundation::api::Connection &conn = ...; // Create a Protocol instance Protocol proto(conn, ...); // Create an Auth_handler instance Auth_handler ah(proto, ...); // Perform authentication handshake if (!ah.authenticate()) { // Authentication failed // Handle error } ``` ### `Auth_handler::authenticate()` Method This method initiates and manages the authentication handshake. ```cpp bool Auth_handler::authenticate() try { // ... other setup ... // Send authenticateStart() packet which initiates authentication handshake bytes initial_auth_data(...); bytes first_response(...); m_proto.snd_AuthenticateStart("method", initial_auth_data, first_response).wait(); continue_handshake(); return true; } catch (Error &e) { // Error during handshake return false; } ``` ### `Auth_handler::continue_handshake()` Method This method continues the handshake process until the connection is accepted or an error occurs. ```cpp void Auth_handler::continue_handshake() { while (!m_accepted) { // get server's reply m_proto.rcv_AuthenticateReply(*this).wait(); // if server accepted connection, stop here if (m_accepted) break; // send response computed in authenticateContinue() method m_proto.snd_AuthenticateContinue(bytes(m_reply, m_reply_len)).wait(); } } ``` ### `Auth_handler` Callbacks These methods are called by the `Protocol` class during the handshake. ```cpp // Called when server sends authenticateOK void Auth_handler::auth_ok(bytes data) { m_accepted = true; // ... handle successful authentication ... } // Called when server sends authenticateContinue void Auth_handler::auth_continue(bytes data) { // compute reply and store it in m_reply ... } ``` ``` -------------------------------- ### Install JDBC Test Executable Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/CMakeLists.txt Installs a JDBC test executable and adds a corresponding test definition to a ctest file. This function is automatically called by add_unit_test() but needs explicit calls for examples. ```cmake function(install_test TGT_NAME EXE_NAME) # FIXME: Currently it puts all tests in a single folder which might lead # to name conflicts. install( TARGETS ${TGT_NAME} DESTINATION tests/jdbc COMPONENT JDBCTests EXCLUDE_FROM_ALL ) file(APPEND "${PROJECT_BINARY_DIR}/jdbc_tests.cmake" "add_test(jdbc_${TGT_NAME} ${EXE_NAME})\n" ) endfunction() ``` -------------------------------- ### Protobuf Type Name Resolution Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt Illustrates a change in protobuf's type name resolver to prevent type names from resolving to fields, ensuring correct resolution of message types. This change aligns with the Protocol Buffers style guide. ```Protocol Buffers message Foo {} message Bar { optional int32 Foo = 1; optional Foo baz = 2; } ``` -------------------------------- ### Configure CMake for Local Connector/C++ Installation Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/doc/usage.txt When Connector/C++ is installed locally, set the `mysql-concpp_DIR` variable to the installation path before calling `find_package`. ```cmake set(mysql-concpp_DIR "/path/to/concpp/install") find_package(mysql-concpp) ``` -------------------------------- ### Configure Tests with Custom Installation Path Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/testing/find_package/README.txt Configure tests when the connector is installed from a TGZ or ZIP package to a custom location. Specify the installation directory using the WITH_CONCPP parameter. ```bash cmake -D WITH_CONCPP=${INSTALL_DIR} ... ``` -------------------------------- ### Alternative Session Creation Methods Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/doc/devapi_ref.txt Demonstrates alternative ways to specify session options for creating a `mysqlx::Session` object. ```cpp Session s1("mysqlx://mike:s3cr3t!@localhost:13009"); Session s2("localhost", 13009, "mike", "s3cr3t!"); Session s3(13009, "mike", "s3cr3t!"); // session on localhost Session s4( SessionOption::USER, "mike", SessionOption::PWD, "s3cr3t!", SessionOption::HOST, "localhost", SessionOption::PORT, 13009 ); ``` -------------------------------- ### Create Session with Options Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/cdk.rst Establish a session for the data source using provided user credentials and options. Sets the default schema for operations. ```cpp ds::Options opt(user, password); opt.set_default_schema("test"); Session s(ds, opt); ``` -------------------------------- ### Show Configuration Options Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/CMakeLists.txt Displays the current configuration options for the build. ```cmake show_config_options() ``` -------------------------------- ### Install JDBC Test Definitions Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/CMakeLists.txt Installs the generated jdbc_tests.cmake file, renaming it to CTestTestfile.cmake. This allows tests to be run using the ctest command. ```cmake install( FILES "${PROJECT_BINARY_DIR}/jdbc_tests.cmake" DESTINATION tests/jdbc RENAME CTestTestfile.cmake COMPONENT JDBCTests EXCLUDE_FROM_ALL ) ``` -------------------------------- ### Using Any Type in C++ Protobuf Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt Demonstrates how to use the Any type in C++ for flexible message handling. Import 'google/protobuf/any.proto' and use PackFrom/UnpackTo methods. ```protobuf // foo.proto import "google/protobuf/any.proto"; message Foo { google.protobuf.Any any_field = 1; } message Bar { int32 value = 1; } ``` ```cpp Foo foo; Bar bar = ...; foo.mutable_any_field()->PackFrom(bar); ... if (foo.any_field().IsType()) { foo.any_field().UnpackTo(&bar); ... } ``` -------------------------------- ### Manage Schemas with MySQL Connector/C++ X DevAPI Source: https://context7.com/mysql/mysql-connector-cpp/llms.txt Illustrates how to obtain, create, list, check for existence, and drop schemas using the X DevAPI. It also shows how to enumerate collections and tables within a schema. ```cpp #include using namespace mysqlx; Session sess("mysqlx://root:secret@127.0.0.1"); // Get (or lazily reference) a schema Schema db = sess.getSchema("myapp"); // Create if not exists Schema db2 = sess.createSchema("myapp", /*reuse=*/true); // List all schemas for (Schema s : sess.getSchemas()) cout << s.getName() << endl; // Check existence (round-trips to server) if (db.existsInDatabase()) cout << "Schema exists" << endl; // Enumerate collections and tables for (const string &name : db.getCollectionNames()) cout << " collection: " << name << endl; for (const string &name : db.getTableNames()) cout << " table: " << name << endl; sess.dropSchema("myapp"); ``` -------------------------------- ### Create Collection Directly Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/doc/devapi_ref.txt Shows how to create a `mysqlx::Collection` object directly without explicitly creating a `mysqlx::Schema` instance. ```cpp Collection coll = sess.getSchema("test").createCollection("c1",true); ``` -------------------------------- ### Install build dependencies on Ubuntu/Debian Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/src/README.md Installs necessary tools like autoconf, automake, libtool, make, g++, and unzip on Ubuntu/Debian systems. ```bash sudo apt-get install autoconf automake libtool curl make g++ unzip ``` -------------------------------- ### Connect and Interact with MySQL using C++ Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/README.md This C++ code demonstrates how to connect to a MySQL server using X DevAPI, create a collection, insert documents, and fetch documents based on a query. It includes error handling for connection and operation failures. Ensure you have the MySQL Connector/C++ library installed and configured. ```cpp #include #include using ::std::cout; using ::std::endl; using namespace ::mysqlx; int main(int argc, const char* argv[]) try { const char *url = (argc > 1 ? argv[1] : "mysqlx://root@127.0.0.1"); cout << "Creating session on " << url << " ..." << endl; Session sess(url); cout <<"Session accepted, creating collection..." < ids = add.getGeneratedIds(); for (string id : ids) cout <<"- added doc with id: " << id < 1 and name like 'ba%'" ).execute(); int i = 0; for (DbDoc doc : docs) { cout <<"doc#" < using namespace mysqlx; // --- URI form (preferred) --- Session s1("mysqlx://root:secret@127.0.0.1:33060/mydb?ssl-mode=required"); // --- Positional form --- Session s2("127.0.0.1", 33060, "root", "secret", "mydb"); // --- Named-option form --- Session s3( SessionOption::HOST, "127.0.0.1", SessionOption::PORT, 33060, SessionOption::USER, "root", SessionOption::PWD, "secret", SessionOption::DB, "mydb", SessionOption::SSL_MODE, SSLMode::REQUIRED ); // --- Multi-host failover with priorities --- Session s4( SessionOption::HOST, "primary.example.com", SessionOption::PORT, 33060, SessionOption::PRIORITY, 100, SessionOption::HOST, "replica.example.com", SessionOption::PORT, 33060, SessionOption::PRIORITY, 50, SessionOption::USER, "root", SessionOption::PWD, "secret" ); // Proper error handling try { Session s("mysqlx://root@localhost:33060"); cout << "Default schema: " << s.getDefaultSchemaName() << endl; s.close(); } catch (const mysqlx::Error &e) { cerr << "Connection error: " << e.what() << endl; } ``` ``` -------------------------------- ### Configure Pkg-config for API Installation Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/extra/otel/opentelemetry-cpp-1.12.0/api/CMakeLists.txt Includes a CMake script to configure pkg-config files for the OpenTelemetry API. This is used when the API is being installed and needs to be discoverable by other projects. ```cmake include(${PROJECT_SOURCE_DIR}/cmake/pkgconfig.cmake) if(OPENTELEMETRY_INSTALL) opentelemetry_add_pkgconfig( api "OpenTelemetry API" "A header-only library to support instrumentation with OpenTelemetry." "${TARGET_DEPS}") endif() ``` -------------------------------- ### CDK Client Main Function Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/usage.rst Illustrates the main function of a CDK client application, including connection, authentication, query preparation, and session closing. It also shows error handling for CDK-specific and standard exceptions. ```cpp int main() try { connection::TCPIP conn("localhost", PORT); cout <<"Connectiog to port " < using namespace mysqlx; // Build a pool of up to 10 connections Client cli( "mysqlx://root:secret@127.0.0.1", ClientOption::POOLING, true, ClientOption::POOL_MAX_SIZE, 10, ClientOption::POOL_QUEUE_TIMEOUT, 5000, // ms – max wait for a free slot ClientOption::POOL_MAX_IDLE_TIME, 30000 // ms – evict idle connections ); // Or with a JSON options string alongside the URI Client cli2( "mysqlx://root:secret@127.0.0.1", R"({ \"pooling\": { \"enabled\": true, \"maxSize\": 25, \"queueTimeout\": 1000, \"maxIdleTime\": 5000 } })" ); // Acquire a session from the pool (blocks up to queueTimeout if pool is full) { Session sess = cli.getSession(); auto res = sess.sql("SELECT @@version").execute(); cout << res.fetchOne()[0] << endl; } // session automatically returned to pool when it goes out of scope ``` -------------------------------- ### Conditional Build for Tests and Examples Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/CMakeLists.txt Enables the inclusion of test and example subdirectories only when the WITH_TESTS CMake variable is set to true. It also sets a compile definition if shared libraries are not being built. ```cmake if(WITH_TESTS) if(NOT BUILD_SHARED_LIBS) set_property( DIRECTORY . APPEND PROPERTY COMPILE_DEFINITIONS CPPCONN_LIB_BUILD ) endif() add_subdirectory(test) add_subdirectory(examples) endif() ``` -------------------------------- ### Bundle a single library with platform-specific installation Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/CMakeLists.txt Installs a library to the appropriate destination based on the operating system (Windows, macOS, or Linux). On macOS, it also creates symlinks for plugin dependencies. ```cmake function(bundle_lib lib) get_filename_component(lib_name ${lib} NAME) if(bundled_${lib_name}) return() endif() set(bundled_${lib_name} true PARENT_SCOPE) message("Bundling library: ${lib}") if(WIN32) install(FILES ${lib} DESTINATION "bin" COMPONENT JDBCDll ) else() if(APPLE) # On Apple, its on the lib dir install(FILES ${lib} DESTINATION "${INSTALL_LIB_DIR}" COMPONENT JDBCDll ) # Symlinks need to be created to allow authenticating # plugins to load dependencies in MacOS # # NOTE: in Linux the dependencies are adressed in # a different way install(CODE " execute_process( COMMAND ${CMAKE_COMMAND} -E create_symlink ../${lib_name} ${lib_name} WORKING_DIRECTORY \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/${INSTALL_LIB_DIR}/plugin\" ) ") else() install(FILES ${lib} DESTINATION "${INSTALL_LIB_DIR}/private" COMPONENT JDBCDll ) endif() endif() endfunction(bundle_lib) ``` -------------------------------- ### Session Establishment Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/doc/devapi_ref.txt Demonstrates how to establish a session with the MySQL Server using various connection string formats and session options. ```APIDOC ## Session Establishment ### Description Establishes a connection to the MySQL Server using the X DevAPI. The constructor can accept a URI string or individual host, port, user, and password parameters. Error handling for connection failures is also described. ### Method `mysqlx::Session` constructor ### Endpoint N/A (Client-side API) ### Parameters #### Constructor Arguments (Examples) - `"mysqlx://mike:s3cr3t!@localhost:13009"` (string) - Connection URI including host, port, and credentials. - `"localhost", 13009, "mike", "s3cr3t!"` (string, int, string, string) - Host, port, user, and password. - `13009, "mike", "s3cr3t!"` (int, string, string) - Port, user, and password (assumes localhost). - `SessionOption::USER, "mike", SessionOption::PWD, "s3cr3t!", SessionOption::HOST, "localhost", SessionOption::PORT, 13009` (Enumerated options) - Key-value pairs for session settings. ### Request Example ```cpp #include using namespace mysqlx; // Example using URI string Session s1("mysqlx://mike:s3cr3t!@localhost:13009"); // Example using individual parameters Session s2("localhost", 13009, "mike", "s3cr3t!"); // Example using SessionOption enum Session s4( SessionOption::USER, "mike", SessionOption::PWD, "s3cr3t!", SessionOption::HOST, "localhost", SessionOption::PORT, 13009 ); ``` ### Response #### Success Response A `mysqlx::Session` object is successfully created and ready for use. #### Error Response Throws an error derived from `mysqlx::Error` if the session could not be established. ``` -------------------------------- ### Configure Parser Include Directories Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/parser/tests/CMakeLists.txt Sets up include directories for the parser module, including the parent directory, protocol definitions, and protobuf include paths. ```cmake INCLUDE_DIRECTORIES(..) INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/protocol/mysqlx ${PROJECT_BINARY_DIR}/protocol/mysqlx ${PROTOBUF_INCLUDE_DIR} ) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/mysqlx) ``` -------------------------------- ### Protobuf Enum Name and Parse Functions (C++) Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt For each enum type Foo, protoc generates Foo_Name() to get the string name from a value and Foo_Parse() to get the value from a string name. ```cpp const string& Foo_Name(Foo value); bool Foo_Parse(const string& name, Foo* result); ``` -------------------------------- ### Instantiate Protocol Class Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/designs/protocol.rst Instantiate the Protocol class with a connection object and optional arguments. ```cpp foundation::api::Connection &conn= ...; Protocol proto(conn, ...); ``` -------------------------------- ### Install JDBC Test Tokens with CMake Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/jdbc/test/unit/classes/CMakeLists.txt This snippet iterates through a list of OpenID authentication token files, copies them to the build directory, and installs them to the 'tests/jdbc' destination for the 'JDBCTests' component. This is used to prepare test resources for JDBC authentication. ```cmake foreach (token openid_token_correct.txt openid_token_empty.txt openid_token_expired.txt openid_token_invalid.txt openid_token_issuer2.txt openid_token_key2.txt openid_token_user2.txt ) # Copy tokens to build dir file(COPY tokens/${token} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) # Install tokens install( FILES tokens/${token} DESTINATION tests/jdbc COMPONENT JDBCTests EXCLUDE_FROM_ALL ) endforeach() ``` -------------------------------- ### Fix cmake install on iOS (C++) Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt Corrects issues with the CMake installation process specifically for iOS builds, ensuring that the connector can be properly integrated into iOS projects. ```c++ # CMakeLists.txt snippet for iOS installation # ... (specific CMake code) ... ``` -------------------------------- ### Version Parsing from Configure Script Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/cmake/CMakeLists.txt Parses the project version, description, and contact information from the AC_INIT macro in the configure.ac script using regular expressions. ```cmake set(protobuf_CONFIGURE_SCRIPT "../configure.ac") set(protobuf_AC_INIT_REGEX "^AC_INIT\\(\[([^\]]+)\\],\[([^\]]+)\\],\[([^\]]+)\\],\[([^\]]+)\]\)$" ) file(STRINGS "${protobuf_CONFIGURE_SCRIPT}" protobuf_AC_INIT_LINE LIMIT_COUNT 1 REGEX "^AC_INIT") string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\1" protobuf_DESCRIPTION "${protobuf_AC_INIT_LINE}") string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\2" protobuf_VERSION_STRING "${protobuf_AC_INIT_LINE}") string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\3" protobuf_CONTACT "${protobuf_AC_INIT_LINE}") ``` -------------------------------- ### Protobuf Reserved Keyword Example Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt Demonstrates the usage of the 'reserved' keyword in Protobuf syntax (both proto2 and proto3) to declare reserved field numbers and names, preventing their reuse. This example shows how to reserve specific field numbers within a message. ```protobuf message TestMessage { reserved 2, 15, 9 to 11, 3; } ``` -------------------------------- ### C++: Parser, Style Guide Warnings, and Float Handling Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/extra/protobuf/protobuf-3.19.6/CHANGES.txt This C++ snippet includes general parser improvements, the addition of warnings for style guide non-compliance in field names, and a fix for `TextFormat` round-trip issues with maximum float values. ```C++ Improve the parser. Add a warning if a field name doesn't match the style guide. Fix TextFormat not round-trip correctly when float value is max float. ``` -------------------------------- ### Create TCP/IP Data Source Instance Source: https://github.com/mysql/mysql-connector-cpp/blob/trunk/cdk/doc/cdk.rst Instantiate a data source object for a MySQL server accessed via TCP/IP using the MySQL X protocol. Constructor parameters specify the address and port. ```cpp ds::TCPIP ds(...); ```