ClickHouse/base/mysqlxx/Query.cpp

106 lines
2.2 KiB
C++
Raw Normal View History

#if __has_include(<mysql.h>)
#include <errmsg.h>
#include <mysql.h>
#else
2021-10-27 23:10:39 +00:00
#include <mysql/errmsg.h>
#include <mysql/mysql.h>
#endif
#include <Poco/Logger.h>
2011-03-03 19:57:34 +00:00
#include <mysqlxx/Connection.h>
#include <mysqlxx/Query.h>
#include <mysqlxx/Types.h>
2011-03-03 19:57:34 +00:00
namespace mysqlxx
{
2020-05-09 23:31:44 +00:00
Query::Query(Connection * conn_, const std::string & query_string) : conn(conn_)
2011-03-03 19:57:34 +00:00
{
/// Важно в случае, если Query используется не из того же потока, что Connection.
mysql_thread_init();
if (!query_string.empty())
2020-05-09 23:31:44 +00:00
query_buf << query_string;
2011-03-10 20:31:02 +00:00
2020-05-09 23:31:44 +00:00
query_buf.imbue(std::locale::classic());
2011-03-03 19:57:34 +00:00
}
2020-05-09 23:31:44 +00:00
Query::Query(const Query & other) : conn(other.conn)
2011-03-03 19:57:34 +00:00
{
/// Важно в случае, если Query используется не из того же потока, что Connection.
mysql_thread_init();
2020-05-09 23:31:44 +00:00
query_buf.imbue(std::locale::classic());
2011-03-16 20:33:39 +00:00
*this << other.str();
2011-03-03 19:57:34 +00:00
}
2011-03-05 20:47:46 +00:00
Query & Query::operator= (const Query & other)
{
2019-04-22 16:07:09 +00:00
if (this == &other)
return *this;
conn = other.conn;
2011-03-10 20:31:02 +00:00
2020-05-09 23:31:44 +00:00
query_buf.str(other.str());
return *this;
2011-03-05 20:47:46 +00:00
}
Query::~Query()
{
mysql_thread_end();
}
2011-03-03 19:57:34 +00:00
void Query::reset()
{
2020-05-09 23:31:44 +00:00
query_buf.str({});
2011-03-03 19:57:34 +00:00
}
2011-03-15 20:56:42 +00:00
void Query::executeImpl()
2011-03-03 19:57:34 +00:00
{
std::string query_string = query_buf.str();
MYSQL* mysql_driver = conn->getDriver();
auto & logger = Poco::Logger::get("mysqlxx::Query");
logger.trace("Running MySQL query using connection %lu", mysql_thread_id(mysql_driver));
if (mysql_real_query(mysql_driver, query_string.data(), query_string.size()))
{
const auto err_no = mysql_errno(mysql_driver);
switch (err_no)
{
case CR_SERVER_GONE_ERROR:
[[fallthrough]];
case CR_SERVER_LOST:
throw ConnectionLost(errorMessage(mysql_driver), err_no);
default:
throw BadQuery(errorMessage(mysql_driver), err_no);
}
}
2011-03-03 19:57:34 +00:00
}
UseQueryResult Query::use()
{
executeImpl();
MYSQL_RES * res = mysql_use_result(conn->getDriver());
if (!res)
onError(conn->getDriver());
2011-03-03 19:57:34 +00:00
return UseQueryResult(res, conn, this);
2011-03-03 19:57:34 +00:00
}
2011-03-15 20:56:42 +00:00
void Query::execute()
{
executeImpl();
2011-03-15 20:56:42 +00:00
}
2011-03-05 16:56:30 +00:00
UInt64 Query::insertID()
{
return mysql_insert_id(conn->getDriver());
2011-03-05 16:56:30 +00:00
}
2011-03-03 19:57:34 +00:00
}