| 1 | #if __has_include(<mysql.h>) |
| 2 | #include <mysql.h> |
| 3 | #else |
| 4 | #include <mysql/mysql.h> |
| 5 | #endif |
| 6 | |
| 7 | #include <mysqlxx/Connection.h> |
| 8 | #include <mysqlxx/Query.h> |
| 9 | |
| 10 | |
| 11 | namespace mysqlxx |
| 12 | { |
| 13 | |
| 14 | Query::Query(Connection * conn_, const std::string & query_string) : std::ostream(0), conn(conn_) |
| 15 | { |
| 16 | /// Важно в случае, если Query используется не из того же потока, что Connection. |
| 17 | mysql_thread_init(); |
| 18 | |
| 19 | init(&query_buf); |
| 20 | |
| 21 | if (!query_string.empty()) |
| 22 | { |
| 23 | query_buf.str(query_string); |
| 24 | seekp(0, std::ios::end); |
| 25 | } |
| 26 | |
| 27 | imbue(std::locale::classic()); |
| 28 | } |
| 29 | |
| 30 | Query::Query(const Query & other) : std::ostream(0), conn(other.conn) |
| 31 | { |
| 32 | /// Важно в случае, если Query используется не из того же потока, что Connection. |
| 33 | mysql_thread_init(); |
| 34 | |
| 35 | init(&query_buf); |
| 36 | imbue(std::locale::classic()); |
| 37 | |
| 38 | *this << other.str(); |
| 39 | } |
| 40 | |
| 41 | Query & Query::operator= (const Query & other) |
| 42 | { |
| 43 | if (this == &other) |
| 44 | return *this; |
| 45 | |
| 46 | conn = other.conn; |
| 47 | |
| 48 | seekp(0); |
| 49 | clear(); |
| 50 | *this << other.str(); |
| 51 | |
| 52 | return *this; |
| 53 | } |
| 54 | |
| 55 | Query::~Query() |
| 56 | { |
| 57 | mysql_thread_end(); |
| 58 | } |
| 59 | |
| 60 | void Query::reset() |
| 61 | { |
| 62 | seekp(0); |
| 63 | clear(); |
| 64 | query_buf.str("" ); |
| 65 | } |
| 66 | |
| 67 | void Query::executeImpl() |
| 68 | { |
| 69 | std::string query_string = query_buf.str(); |
| 70 | if (mysql_real_query(conn->getDriver(), query_string.data(), query_string.size())) |
| 71 | throw BadQuery(errorMessage(conn->getDriver()), mysql_errno(conn->getDriver())); |
| 72 | } |
| 73 | |
| 74 | UseQueryResult Query::use() |
| 75 | { |
| 76 | executeImpl(); |
| 77 | MYSQL_RES * res = mysql_use_result(conn->getDriver()); |
| 78 | if (!res) |
| 79 | onError(conn->getDriver()); |
| 80 | |
| 81 | return UseQueryResult(res, conn, this); |
| 82 | } |
| 83 | |
| 84 | StoreQueryResult Query::store() |
| 85 | { |
| 86 | executeImpl(); |
| 87 | MYSQL_RES * res = mysql_store_result(conn->getDriver()); |
| 88 | if (!res) |
| 89 | checkError(conn->getDriver()); |
| 90 | |
| 91 | return StoreQueryResult(res, conn, this); |
| 92 | } |
| 93 | |
| 94 | void Query::execute() |
| 95 | { |
| 96 | executeImpl(); |
| 97 | } |
| 98 | |
| 99 | UInt64 Query::insertID() |
| 100 | { |
| 101 | return mysql_insert_id(conn->getDriver()); |
| 102 | } |
| 103 | |
| 104 | } |
| 105 | |