mysql/example/2_simple/multi_function.cpp
2025-02-11 20:42:41 +01:00

152 lines
4.6 KiB
C++

//
// Copyright (c) 2019-2025 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio/awaitable.hpp>
#ifdef BOOST_ASIO_HAS_CO_AWAIT
//[example_multi_function
/**
* This example demonstrates how to run multi-function operations
* to dump an entire table to stdout, reading rows in batches.
*
* It uses C++20 coroutines. If you need, you can backport
* it to C++11 by using callbacks, asio::yield_context
* or sync functions instead of coroutines.
*/
#include <boost/mysql/any_connection.hpp>
#include <boost/mysql/error_with_diagnostics.hpp>
#include <boost/mysql/execution_state.hpp>
#include <boost/mysql/row_view.hpp>
#include <boost/mysql/rows_view.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/this_coro.hpp>
#include <iostream>
namespace mysql = boost::mysql;
namespace asio = boost::asio;
void print_employee(mysql::row_view employee)
{
std::cout << "Employee '" << employee.at(0) << " " // first_name (string)
<< employee.at(1) << "' earns " // last_name (string)
<< employee.at(2) << " dollars yearly\n"; // salary (double)
}
// The main coroutine
asio::awaitable<void> coro_main(
std::string_view server_hostname,
std::string_view username,
std::string_view password
)
{
// Create a connection. It will use the same executor as our coroutine
mysql::any_connection conn(co_await asio::this_coro::executor);
// The hostname, username, password and database to use
mysql::connect_params params;
params.server_address.emplace_host_and_port(std::string(server_hostname));
params.username = username;
params.password = password;
params.database = "boost_mysql_examples";
// Connect to the server
co_await conn.async_connect(params);
// Start our query as a multi-function operation.
// This will send the query for execution but won't read the rows.
// An execution_state keep tracks of the operation.
mysql::execution_state st;
co_await conn.async_start_execution("SELECT first_name, last_name, salary FROM employee", st);
// st.should_read_rows() returns true while there are more rows to read.
// Use async_read_some_rows to read a batch of rows.
// This function tries to minimize copies. employees is a view
// object pointing into the connection's internal buffers,
// and is valid until you start the next async operation.
while (st.should_read_rows())
{
mysql::rows_view employees = co_await conn.async_read_some_rows(st);
for (auto employee : employees)
print_employee(employee);
}
// Notify the MySQL server we want to quit, then close the underlying connection.
co_await conn.async_close();
}
void main_impl(int argc, char** argv)
{
if (argc != 4)
{
std::cerr << "Usage: " << argv[0] << " <username> <password> <server-hostname>\n";
exit(1);
}
// Create an I/O context, required by all I/O objects
asio::io_context ctx;
// Launch our coroutine
asio::co_spawn(
ctx,
[=] { return coro_main(argv[3], argv[1], argv[2]); },
// If any exception is thrown in the coroutine body, rethrow it.
[](std::exception_ptr ptr) {
if (ptr)
{
std::rethrow_exception(ptr);
}
}
);
// Calling run will actually execute the coroutine until completion
ctx.run();
std::cout << "Done\n";
}
int main(int argc, char** argv)
{
try
{
main_impl(argc, argv);
}
catch (const boost::mysql::error_with_diagnostics& err)
{
// Some errors include additional diagnostics, like server-provided error messages.
// Security note: diagnostics::server_message may contain user-supplied values (e.g. the
// field value that caused the error) and is encoded using to the connection's character set
// (UTF-8 by default). Treat is as untrusted input.
std::cerr << "Error: " << err.what() << ", error code: " << err.code() << '\n'
<< "Server diagnostics: " << err.get_diagnostics().server_message() << std::endl;
return 1;
}
catch (const std::exception& err)
{
std::cerr << "Error: " << err.what() << std::endl;
return 1;
}
}
//]
#else
#include <iostream>
int main()
{
std::cout << "Sorry, your compiler doesn't have the required capabilities to run this example"
<< std::endl;
}
#endif