mysql_backend.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. ///////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright (C) 2010-2011 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>
  4. //
  5. // Distributed under:
  6. //
  7. // the Boost Software License, Version 1.0.
  8. // (See accompanying file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // or (at your opinion) under:
  12. //
  13. // The MIT License
  14. // (See accompanying file MIT.txt or a copy at
  15. // http://www.opensource.org/licenses/mit-license.php)
  16. //
  17. ///////////////////////////////////////////////////////////////////////////////
  18. #define CPPDB_DRIVER_SOURCE
  19. #ifdef CPPDB_WITH_MYSQL
  20. # define CPPDB_SOURCE
  21. #endif
  22. #ifdef WINDOWS_BUILD
  23. #include <mysql.h>
  24. #elif LINUX_BUILD
  25. #include <mysql/mysql.h>
  26. #endif
  27. #include <cppdb/backend.h>
  28. #include <cppdb/errors.h>
  29. #include <cppdb/utils.h>
  30. #include <cppdb/numeric_util.h>
  31. #include <sstream>
  32. #include <vector>
  33. #include <limits>
  34. #include <iomanip>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <iostream>
  38. namespace cppdb {
  39. namespace mysql_backend {
  40. class cppdb_myerror : public cppdb_error
  41. {
  42. public:
  43. cppdb_myerror(std::string const& str) :
  44. cppdb_error("cppdb::mysql::" + str)
  45. {
  46. }
  47. };
  48. namespace unprep {
  49. class result : public backend::result {
  50. public:
  51. ///
  52. /// Check if the next row in the result exists. If the DB engine can't perform
  53. /// this check without loosing data for current row, it should return next_row_unknown.
  54. ///
  55. virtual next_row has_next()
  56. {
  57. if (!res_)
  58. return last_row_reached;
  59. if (current_row_ >= mysql_num_rows(res_))
  60. return last_row_reached;
  61. else
  62. return next_row_exists;
  63. }
  64. ///
  65. /// Move to next row. Should be called before first access to any of members. If no rows remain
  66. /// return false, otherwise return true
  67. ///
  68. virtual bool next()
  69. {
  70. if (!res_)
  71. return false;
  72. current_row_++;
  73. row_ = mysql_fetch_row(res_);
  74. if (!row_)
  75. return false;
  76. return true;
  77. }
  78. ///
  79. /// Fetch an integer value for column \a col starting from 0.
  80. ///
  81. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  82. /// can't be converted to integer or its range is not supported by the integer type.
  83. ///
  84. char const* at(int col)
  85. {
  86. if (!res_)
  87. throw empty_row_access();
  88. if (col < 0 || col >= cols_)
  89. throw invalid_column();
  90. return row_[col];
  91. }
  92. char const* at(int col, size_t& len)
  93. {
  94. if (!res_)
  95. throw empty_row_access();
  96. if (col < 0 || col >= cols_)
  97. throw invalid_column();
  98. unsigned long* lengths = mysql_fetch_lengths(res_);
  99. if (lengths == 0)
  100. throw cppdb_myerror("Can't get length of column");
  101. len = lengths[col];
  102. return row_[col];
  103. }
  104. template<typename T>
  105. bool do_fetch(int col, T& v)
  106. {
  107. size_t len;
  108. char const* s = at(col, len);
  109. if (!s)
  110. return false;
  111. v = parse_number<T>(std::string(s, len), fmt_);
  112. return true;
  113. }
  114. virtual bool fetch(int col, short& v)
  115. {
  116. return do_fetch(col, v);;
  117. }
  118. virtual bool fetch(int col, unsigned short& v)
  119. {
  120. return do_fetch(col, v);
  121. }
  122. virtual bool fetch(int col, int& v)
  123. {
  124. return do_fetch(col, v);
  125. }
  126. virtual bool fetch(int col, unsigned& v)
  127. {
  128. return do_fetch(col, v);
  129. }
  130. virtual bool fetch(int col, long& v)
  131. {
  132. return do_fetch(col, v);
  133. }
  134. virtual bool fetch(int col, unsigned long& v)
  135. {
  136. return do_fetch(col, v);
  137. }
  138. virtual bool fetch(int col, long long& v)
  139. {
  140. return do_fetch(col, v);
  141. }
  142. ///
  143. virtual bool fetch(int col, unsigned long long& v)
  144. {
  145. return do_fetch(col, v);
  146. }
  147. virtual bool fetch(int col, float& v)
  148. {
  149. return do_fetch(col, v);
  150. }
  151. virtual bool fetch(int col, double& v)
  152. {
  153. return do_fetch(col, v);
  154. }
  155. virtual bool fetch(int col, long double& v)
  156. {
  157. return do_fetch(col, v);
  158. }
  159. ///
  160. virtual bool fetch(int col, std::string& v)
  161. {
  162. size_t len;
  163. char const* s = at(col, len);
  164. if (!s)
  165. return false;
  166. v.assign(s, len);
  167. return true;
  168. }
  169. virtual bool fetch(int col, std::ostream& v)
  170. {
  171. size_t len;
  172. char const* s = at(col, len);
  173. if (!s)
  174. return false;
  175. v.write(s, len);
  176. return true;
  177. }
  178. ///
  179. /// Fetch a date-time value for column \a col starting from 0.
  180. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  181. ///
  182. /// Should throw invalid_column() \a col value is invalid. If the data can't be converted
  183. /// to date-time it should throw bad_value_cast()
  184. ///
  185. virtual bool fetch(int col, std::tm& v)
  186. {
  187. size_t len;
  188. char const* s = at(col, len);
  189. if (!s)
  190. return false;
  191. std::string tmp(s, len);
  192. v = parse_time(tmp);
  193. return true;
  194. }
  195. ///
  196. /// Check if the column \a col is NULL starting from 0, should throw invalid_column() if the index out of range
  197. ///
  198. virtual bool is_null(int col)
  199. {
  200. return at(col) == 0;
  201. }
  202. ///
  203. /// Return the number of columns in the result. Should be valid even without calling next() first time.
  204. ///
  205. virtual int cols()
  206. {
  207. return cols_;
  208. }
  209. virtual std::string column_to_name(int col)
  210. {
  211. if (col < 0 || col >= cols_)
  212. throw invalid_column();
  213. if (!res_)
  214. throw empty_row_access();
  215. MYSQL_FIELD* flds = mysql_fetch_fields(res_);
  216. if (!flds) {
  217. throw cppdb_myerror("Internal error empty fileds");
  218. }
  219. return flds[col].name;
  220. }
  221. virtual int name_to_column(std::string const& name)
  222. {
  223. if (!res_)
  224. throw empty_row_access();
  225. MYSQL_FIELD* flds = mysql_fetch_fields(res_);
  226. if (!flds) {
  227. throw cppdb_myerror("Internal error empty fileds");
  228. }
  229. for (int i = 0; i < cols_; i++)
  230. if (name == flds[i].name)
  231. return i;
  232. return -1;
  233. }
  234. // End of API
  235. result(MYSQL* conn) :
  236. res_(0),
  237. cols_(0),
  238. current_row_(0),
  239. row_(0)
  240. {
  241. fmt_.imbue(std::locale::classic());
  242. res_ = mysql_store_result(conn);
  243. if (!res_) {
  244. cols_ = mysql_field_count(conn);
  245. if (cols_ == 0)
  246. throw cppdb_myerror("Seems that the query does not produce any result");
  247. }
  248. else {
  249. cols_ = mysql_num_fields(res_);
  250. }
  251. }
  252. ~result()
  253. {
  254. if (res_)
  255. mysql_free_result(res_);
  256. }
  257. private:
  258. std::istringstream fmt_;
  259. MYSQL_RES* res_;
  260. int cols_;
  261. unsigned current_row_;
  262. MYSQL_ROW row_;
  263. };
  264. class statement : public backend::statement {
  265. public:
  266. virtual std::string const& sql_query()
  267. {
  268. return query_;
  269. }
  270. virtual void bind(int col, std::string const& s)
  271. {
  272. bind(col, s.c_str(), s.c_str() + s.size());
  273. }
  274. virtual void bind(int col, char const* s)
  275. {
  276. bind(col, s, s + strlen(s));
  277. }
  278. virtual void bind(int col, char const* b, char const* e)
  279. {
  280. std::vector<char> buf(2 * (e - b) + 1);
  281. size_t len = mysql_real_escape_string(conn_, &buf.front(), b, e - b);
  282. std::string& s = at(col);
  283. s.clear();
  284. s.reserve(e - b + 2);
  285. s += '\'';
  286. s.append(&buf.front(), len);
  287. s += '\'';
  288. }
  289. virtual void bind(int col, std::tm const& v)
  290. {
  291. std::string& s = at(col);
  292. s.clear();
  293. s.reserve(30);
  294. s += '\'';
  295. s += cppdb::format_time(v);
  296. s += '\'';
  297. }
  298. virtual void bind(int col, std::istream& v)
  299. {
  300. std::ostringstream ss;
  301. ss << v.rdbuf();
  302. std::string tmp = ss.str();
  303. bind(col, tmp);
  304. }
  305. template<typename T>
  306. void do_bind(int col, T v)
  307. {
  308. fmt_.str(std::string());
  309. if (!std::numeric_limits<T>::is_integer)
  310. fmt_ << std::setprecision(std::numeric_limits<T>::digits10 + 1);
  311. fmt_ << v;
  312. std::string tmp = fmt_.str();
  313. at(col).swap(tmp);
  314. }
  315. virtual void bind(int col, int v)
  316. {
  317. do_bind(col, v);
  318. }
  319. virtual void bind(int col, unsigned v)
  320. {
  321. do_bind(col, v);
  322. }
  323. virtual void bind(int col, long v)
  324. {
  325. do_bind(col, v);
  326. }
  327. virtual void bind(int col, unsigned long v)
  328. {
  329. do_bind(col, v);
  330. }
  331. virtual void bind(int col, long long v)
  332. {
  333. do_bind(col, v);
  334. }
  335. virtual void bind(int col, unsigned long long v)
  336. {
  337. do_bind(col, v);
  338. }
  339. virtual void bind(int col, double v)
  340. {
  341. do_bind(col, v);
  342. }
  343. virtual void bind(int col, long double v)
  344. {
  345. do_bind(col, v);
  346. }
  347. virtual void bind_null(int col)
  348. {
  349. at(col) = "NULL";
  350. }
  351. virtual long long sequence_last(std::string const&/*sequence*/)
  352. {
  353. return mysql_insert_id(conn_);
  354. }
  355. virtual unsigned long long affected()
  356. {
  357. return mysql_affected_rows(conn_);
  358. }
  359. void bind_all(std::string& real_query)
  360. {
  361. size_t total = query_.size();
  362. for (unsigned i = 0; i < params_.size(); i++) {
  363. total += params_[i].size();
  364. }
  365. real_query.clear();
  366. real_query.reserve(total);
  367. size_t pos_ = 0;
  368. for (unsigned i = 0; i < params_.size(); i++) {
  369. size_t marker = binders_[i];
  370. real_query.append(query_, pos_, marker - pos_);
  371. pos_ = marker + 1;
  372. real_query.append(params_[i]);
  373. }
  374. real_query.append(query_, pos_, std::string::npos);
  375. }
  376. virtual result* query()
  377. {
  378. std::string real_query;
  379. bind_all(real_query);
  380. reset_params();
  381. if (mysql_real_query(conn_, real_query.c_str(), real_query.size())) {
  382. throw cppdb_myerror(mysql_error(conn_));
  383. }
  384. return new result(conn_);
  385. }
  386. virtual void exec()
  387. {
  388. std::string real_query;
  389. bind_all(real_query);
  390. reset_params();
  391. if (mysql_real_query(conn_, real_query.c_str(), real_query.size())) {
  392. throw cppdb_myerror(mysql_error(conn_));
  393. }
  394. MYSQL_RES* r = mysql_store_result(conn_);
  395. if (r) {
  396. mysql_free_result(r);
  397. throw cppdb_myerror("Calling exec() on query!");
  398. }
  399. }
  400. std::string& at(int col)
  401. {
  402. if (col < 1 || col > params_no_) {
  403. throw invalid_placeholder();
  404. }
  405. return params_[col - 1];
  406. }
  407. void reset_params()
  408. {
  409. params_.clear();
  410. params_.resize(params_no_, "NULL");
  411. }
  412. statement(std::string const& q, MYSQL* conn) :
  413. query_(q),
  414. conn_(conn),
  415. params_no_(0)
  416. {
  417. fmt_.imbue(std::locale::classic());
  418. bool inside_text = false;
  419. for (size_t i = 0; i < query_.size(); i++) {
  420. if (query_[i] == '\'') {
  421. inside_text = !inside_text;
  422. }
  423. if (query_[i] == '?' && !inside_text) {
  424. params_no_++;
  425. binders_.push_back(i);
  426. }
  427. }
  428. if (inside_text) {
  429. throw cppdb_myerror("Unterminated string found in query");
  430. }
  431. reset_params();
  432. }
  433. virtual ~statement()
  434. {
  435. }
  436. virtual void reset()
  437. {
  438. }
  439. private:
  440. std::ostringstream fmt_;
  441. std::vector<std::string> params_;
  442. std::vector<size_t> binders_;
  443. std::string query_;
  444. MYSQL* conn_;
  445. int params_no_;
  446. };
  447. } // uprep
  448. namespace prep {
  449. class result : public backend::result {
  450. struct bind_data {
  451. bind_data() :
  452. ptr(0),
  453. length(0),
  454. is_null(0),
  455. error(0)
  456. {
  457. memset(&buf, 0, sizeof(buf));
  458. }
  459. char buf[128];
  460. std::vector<char> vbuf;
  461. char* ptr;
  462. unsigned long length;
  463. bool is_null;
  464. bool error;
  465. };
  466. public:
  467. ///
  468. /// Check if the next row in the result exists. If the DB engine can't perform
  469. /// this check without loosing data for current row, it should return next_row_unknown.
  470. ///
  471. virtual next_row has_next()
  472. {
  473. if (current_row_ >= mysql_stmt_num_rows(stmt_))
  474. return last_row_reached;
  475. else
  476. return next_row_exists;
  477. }
  478. ///
  479. /// Move to next row. Should be called before first access to any of members. If no rows remain
  480. /// return false, otherwise return true
  481. ///
  482. virtual bool next()
  483. {
  484. current_row_++;
  485. reset();
  486. if (cols_ > 0) {
  487. if (mysql_stmt_bind_result(stmt_, &bind_[0])) {
  488. throw cppdb_myerror(mysql_stmt_error(stmt_));
  489. }
  490. }
  491. int r = mysql_stmt_fetch(stmt_);
  492. if (r == MYSQL_NO_DATA) {
  493. return false;
  494. }
  495. if (r == MYSQL_DATA_TRUNCATED) {
  496. for (int i = 0; i < cols_; i++) {
  497. if (bind_data_[i].error && !bind_data_[i].is_null && bind_data_[i].length >= sizeof(bind_data_[i].buf)) {
  498. bind_data_[i].vbuf.resize(bind_data_[i].length);
  499. bind_[i].buffer = &bind_data_[i].vbuf.front();
  500. bind_[i].buffer_length = bind_data_[i].length;
  501. if (mysql_stmt_fetch_column(stmt_, &bind_[i], i, 0)) {
  502. throw cppdb_myerror(mysql_stmt_error(stmt_));
  503. }
  504. bind_data_[i].ptr = &bind_data_[i].vbuf.front();
  505. }
  506. }
  507. }
  508. return true;
  509. }
  510. ///
  511. /// Fetch an integer value for column \a col starting from 0.
  512. ///
  513. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  514. /// can't be converted to integer or its range is not supported by the integer type.
  515. ///
  516. bind_data& at(int col)
  517. {
  518. if (col < 0 || col >= cols_)
  519. throw invalid_column();
  520. if (bind_data_.empty())
  521. throw cppdb_myerror("Attempt to access data without fetching it first");
  522. return bind_data_.at(col);
  523. }
  524. template<typename T>
  525. bool do_fetch(int col, T& v)
  526. {
  527. bind_data& d = at(col);
  528. if (d.is_null)
  529. return false;
  530. v = parse_number<T>(std::string(d.ptr, d.length), fmt_);
  531. return true;
  532. }
  533. virtual bool fetch(int col, short& v)
  534. {
  535. return do_fetch(col, v);;
  536. }
  537. ///
  538. /// Fetch an integer value for column \a col starting from 0.
  539. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  540. ///
  541. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  542. /// can't be converted to integer or its range is not supported by the integer type.
  543. ///
  544. virtual bool fetch(int col, unsigned short& v)
  545. {
  546. return do_fetch(col, v);
  547. }
  548. ///
  549. /// Fetch an integer value for column \a col starting from 0.
  550. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  551. ///
  552. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  553. /// can't be converted to integer or its range is not supported by the integer type.
  554. ///
  555. virtual bool fetch(int col, int& v)
  556. {
  557. return do_fetch(col, v);
  558. }
  559. ///
  560. /// Fetch an integer value for column \a col starting from 0.
  561. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  562. ///
  563. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  564. /// can't be converted to integer or its range is not supported by the integer type.
  565. ///
  566. virtual bool fetch(int col, unsigned& v)
  567. {
  568. return do_fetch(col, v);
  569. }
  570. ///
  571. /// Fetch an integer value for column \a col starting from 0.
  572. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  573. ///
  574. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  575. /// can't be converted to integer or its range is not supported by the integer type.
  576. ///
  577. virtual bool fetch(int col, long& v)
  578. {
  579. return do_fetch(col, v);
  580. }
  581. ///
  582. /// Fetch an integer value for column \a col starting from 0.
  583. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  584. ///
  585. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  586. /// can't be converted to integer or its range is not supported by the integer type.
  587. ///
  588. virtual bool fetch(int col, unsigned long& v)
  589. {
  590. return do_fetch(col, v);
  591. }
  592. ///
  593. /// Fetch an integer value for column \a col starting from 0.
  594. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  595. ///
  596. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  597. /// can't be converted to integer or its range is not supported by the integer type.
  598. ///
  599. virtual bool fetch(int col, long long& v)
  600. {
  601. return do_fetch(col, v);
  602. }
  603. ///
  604. /// Fetch an integer value for column \a col starting from 0.
  605. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  606. ///
  607. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  608. /// can't be converted to integer or its range is not supported by the integer type.
  609. ///
  610. virtual bool fetch(int col, unsigned long long& v)
  611. {
  612. return do_fetch(col, v);
  613. }
  614. ///
  615. /// Fetch a floating point value for column \a col starting from 0.
  616. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  617. ///
  618. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  619. /// can't be converted to floating point value.
  620. ///
  621. virtual bool fetch(int col, float& v)
  622. {
  623. return do_fetch(col, v);
  624. }
  625. ///
  626. /// Fetch a floating point value for column \a col starting from 0.
  627. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  628. ///
  629. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  630. /// can't be converted to floating point value.
  631. ///
  632. virtual bool fetch(int col, double& v)
  633. {
  634. return do_fetch(col, v);
  635. }
  636. ///
  637. /// Fetch a floating point value for column \a col starting from 0.
  638. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  639. ///
  640. /// Should throw invalid_column() \a col value is invalid, should throw bad_value_cast() if the underlying data
  641. /// can't be converted to floating point value.
  642. ///
  643. virtual bool fetch(int col, long double& v)
  644. {
  645. return do_fetch(col, v);
  646. }
  647. ///
  648. /// Fetch a string value for column \a col starting from 0.
  649. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  650. ///
  651. /// Should throw invalid_column() \a col value is invalid, any data should be convertible to
  652. /// text value (as formatting integer, floating point value or date-time as string).
  653. ///
  654. virtual bool fetch(int col, std::string& v)
  655. {
  656. bind_data& d = at(col);
  657. if (d.is_null)
  658. return false;
  659. v.assign(d.ptr, d.length);
  660. return true;
  661. }
  662. ///
  663. /// Fetch a BLOB value for column \a col starting from 0.
  664. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  665. ///
  666. /// Should throw invalid_column() \a col value is invalid, any data should be convertible to
  667. /// BLOB value as text (as formatting integer, floating point value or date-time as string).
  668. ///
  669. virtual bool fetch(int col, std::ostream& v)
  670. {
  671. bind_data& d = at(col);
  672. if (d.is_null)
  673. return false;
  674. v.write(d.ptr, d.length);
  675. return true;
  676. }
  677. ///
  678. /// Fetch a date-time value for column \a col starting from 0.
  679. /// Returns true if ok, returns false if the column value is NULL and the referenced object should remain unchanged
  680. ///
  681. /// Should throw invalid_column() \a col value is invalid. If the data can't be converted
  682. /// to date-time it should throw bad_value_cast()
  683. ///
  684. virtual bool fetch(int col, std::tm& v)
  685. {
  686. std::string tmp;
  687. if (!fetch(col, tmp))
  688. return false;
  689. v = parse_time(tmp);
  690. return true;
  691. }
  692. ///
  693. /// Check if the column \a col is NULL starting from 0, should throw invalid_column() if the index out of range
  694. ///
  695. virtual bool is_null(int col)
  696. {
  697. return at(col).is_null;
  698. }
  699. ///
  700. /// Return the number of columns in the result. Should be valid even without calling next() first time.
  701. ///
  702. virtual int cols()
  703. {
  704. return cols_;
  705. }
  706. virtual std::string column_to_name(int col)
  707. {
  708. if (col < 0 || col >= cols_)
  709. throw invalid_column();
  710. MYSQL_FIELD* flds = mysql_fetch_fields(meta_);
  711. if (!flds) {
  712. throw cppdb_myerror("Internal error empty fileds");
  713. }
  714. return flds[col].name;
  715. }
  716. virtual int name_to_column(std::string const& name)
  717. {
  718. MYSQL_FIELD* flds = mysql_fetch_fields(meta_);
  719. if (!flds) {
  720. throw cppdb_myerror("Internal error empty fileds");
  721. }
  722. for (int i = 0; i < cols_; i++)
  723. if (name == flds[i].name)
  724. return i;
  725. return -1;
  726. }
  727. // End of API
  728. result(MYSQL_STMT* stmt) :
  729. stmt_(stmt), current_row_(0), meta_(0)
  730. {
  731. fmt_.imbue(std::locale::classic());
  732. cols_ = mysql_stmt_field_count(stmt_);
  733. if (mysql_stmt_store_result(stmt_)) {
  734. throw cppdb_myerror(mysql_stmt_error(stmt_));
  735. }
  736. meta_ = mysql_stmt_result_metadata(stmt_);
  737. if (!meta_) {
  738. throw cppdb_myerror("Seems that the query does not produce any result");
  739. }
  740. }
  741. ~result()
  742. {
  743. mysql_free_result(meta_);
  744. }
  745. void reset()
  746. {
  747. bind_.resize(0);
  748. bind_data_.resize(0);
  749. bind_.resize(cols_, MYSQL_BIND());
  750. bind_data_.resize(cols_, bind_data());
  751. for (int i = 0; i < cols_; i++) {
  752. bind_[i].buffer_type = MYSQL_TYPE_STRING;
  753. bind_[i].buffer = bind_data_[i].buf;
  754. bind_[i].buffer_length = sizeof(bind_data_[i].buf);
  755. bind_[i].length = &bind_data_[i].length;
  756. bind_[i].is_null = &bind_data_[i].is_null;
  757. bind_[i].error = &bind_data_[i].error;
  758. bind_data_[i].ptr = bind_data_[i].buf;
  759. }
  760. }
  761. private:
  762. std::istringstream fmt_;
  763. int cols_;
  764. MYSQL_STMT* stmt_;
  765. unsigned current_row_;
  766. MYSQL_RES* meta_;
  767. std::vector<MYSQL_BIND> bind_;
  768. std::vector<bind_data> bind_data_;
  769. };
  770. class statement : public backend::statement {
  771. struct param {
  772. bool is_null;
  773. bool is_blob;
  774. unsigned long length;
  775. std::string value;
  776. void* buffer;
  777. param() :
  778. is_null(1),
  779. is_blob(false),
  780. length(0),
  781. buffer(0)
  782. {
  783. }
  784. void set(char const* b, char const* e, bool blob = false)
  785. {
  786. length = e - b;
  787. buffer = const_cast<char*>(b);
  788. is_blob = blob;
  789. is_null = 0;
  790. }
  791. void set_str(std::string const& s)
  792. {
  793. value = s;
  794. buffer = const_cast<char*>(value.c_str());
  795. length = value.size();
  796. is_null = 0;
  797. }
  798. void set(std::tm const& t)
  799. {
  800. set_str(cppdb::format_time(t));
  801. }
  802. void bind_it(MYSQL_BIND* b)
  803. {
  804. b->is_null = &is_null;
  805. if (!is_null) {
  806. b->buffer_type = is_blob ? MYSQL_TYPE_BLOB : MYSQL_TYPE_STRING;
  807. b->buffer = buffer;
  808. b->buffer_length = length;
  809. b->length = &length;
  810. }
  811. else {
  812. b->buffer_type = MYSQL_TYPE_NULL;
  813. }
  814. }
  815. };
  816. public:
  817. // Begin of API
  818. ///
  819. /// Get the query the statement works with. Return it as is, used as key for statement
  820. /// caching
  821. ///
  822. virtual std::string const& sql_query()
  823. {
  824. return query_;
  825. }
  826. ///
  827. /// Bind a text value to column \a col (starting from 1). You may assume
  828. /// that the reference remains valid until real call of query() or exec()
  829. ///
  830. /// Should throw invalid_placeholder() if the value of col is out of range. May
  831. /// ignore if it is impossible to know whether the placeholder exists without special
  832. /// support from back-end.
  833. ///
  834. virtual void bind(int col, std::string const& s)
  835. {
  836. at(col).set(s.c_str(), s.c_str() + s.size());
  837. }
  838. ///
  839. /// Bind a text value to column \a col (starting from 1). You may assume
  840. /// that the reference remains valid until real call of query() or exec()
  841. ///
  842. /// Should throw invalid_placeholder() if the value of col is out of range. May
  843. /// ignore if it is impossible to know whether the placeholder exists without special
  844. /// support from back-end.
  845. ///
  846. virtual void bind(int col, char const* s)
  847. {
  848. at(col).set(s, s + strlen(s));
  849. }
  850. ///
  851. /// Bind a text value to column \a col (starting from 1). You may assume
  852. /// that the reference remains valid until real call of query() or exec()
  853. ///
  854. /// Should throw invalid_placeholder() if the value of col is out of range. May
  855. /// ignore if it is impossible to know whether the placeholder exists without special
  856. /// support from back-end.
  857. ///
  858. virtual void bind(int col, char const* b, char const* e)
  859. {
  860. at(col).set(b, e);
  861. }
  862. ///
  863. /// Bind a date-time value to column \a col (starting from 1).
  864. ///
  865. /// Should throw invalid_placeholder() if the value of col is out of range. May
  866. /// ignore if it is impossible to know whether the placeholder exists without special
  867. /// support from back-end.
  868. ///
  869. virtual void bind(int col, std::tm const& v)
  870. {
  871. at(col).set(v);
  872. }
  873. ///
  874. /// Bind a BLOB value to column \a col (starting from 1).
  875. ///
  876. /// Should throw invalid_placeholder() if the value of col is out of range. May
  877. /// ignore if it is impossible to know whether the placeholder exists without special
  878. /// support from back-end.
  879. ///
  880. virtual void bind(int col, std::istream& v)
  881. {
  882. std::ostringstream ss;
  883. ss << v.rdbuf();
  884. at(col).set_str(ss.str());
  885. at(col).is_blob = true;
  886. }
  887. template<typename T>
  888. void do_bind(int col, T v)
  889. {
  890. fmt_.str(std::string());
  891. if (!std::numeric_limits<T>::is_integer)
  892. fmt_ << std::setprecision(std::numeric_limits<T>::digits10 + 1);
  893. fmt_ << v;
  894. at(col).set_str(fmt_.str());
  895. }
  896. ///
  897. /// Bind an integer value to column \a col (starting from 1).
  898. ///
  899. /// Should throw invalid_placeholder() if the value of col is out of range. May
  900. /// ignore if it is impossible to know whether the placeholder exists without special
  901. /// support from back-end.
  902. ///
  903. virtual void bind(int col, int v)
  904. {
  905. do_bind(col, v);
  906. }
  907. ///
  908. /// Bind an integer value to column \a col (starting from 1).
  909. ///
  910. /// Should throw invalid_placeholder() if the value of col is out of range. May
  911. /// ignore if it is impossible to know whether the placeholder exists without special
  912. /// support from back-end.
  913. ///
  914. /// May throw bad_value_cast() if the value out of supported range by the DB.
  915. ///
  916. virtual void bind(int col, unsigned v)
  917. {
  918. do_bind(col, v);
  919. }
  920. ///
  921. /// Bind an integer value to column \a col (starting from 1).
  922. ///
  923. /// Should throw invalid_placeholder() if the value of col is out of range. May
  924. /// ignore if it is impossible to know whether the placeholder exists without special
  925. /// support from back-end.
  926. ///
  927. /// May throw bad_value_cast() if the value out of supported range by the DB.
  928. ///
  929. virtual void bind(int col, long v)
  930. {
  931. do_bind(col, v);
  932. }
  933. ///
  934. /// Bind an integer value to column \a col (starting from 1).
  935. ///
  936. /// Should throw invalid_placeholder() if the value of col is out of range. May
  937. /// ignore if it is impossible to know whether the placeholder exists without special
  938. /// support from back-end.
  939. ///
  940. /// May throw bad_value_cast() if the value out of supported range by the DB.
  941. ///
  942. virtual void bind(int col, unsigned long v)
  943. {
  944. do_bind(col, v);
  945. }
  946. ///
  947. /// Bind an integer value to column \a col (starting from 1).
  948. ///
  949. /// Should throw invalid_placeholder() if the value of col is out of range. May
  950. /// ignore if it is impossible to know whether the placeholder exists without special
  951. /// support from back-end.
  952. ///
  953. /// May throw bad_value_cast() if the value out of supported range by the DB.
  954. ///
  955. virtual void bind(int col, long long v)
  956. {
  957. do_bind(col, v);
  958. }
  959. ///
  960. /// Bind an integer value to column \a col (starting from 1).
  961. ///
  962. /// Should throw invalid_placeholder() if the value of col is out of range. May
  963. /// ignore if it is impossible to know whether the placeholder exists without special
  964. /// support from back-end.
  965. ///
  966. /// May throw bad_value_cast() if the value out of supported range by the DB.
  967. ///
  968. virtual void bind(int col, unsigned long long v)
  969. {
  970. do_bind(col, v);
  971. }
  972. ///
  973. /// Bind a floating point value to column \a col (starting from 1).
  974. ///
  975. /// Should throw invalid_placeholder() if the value of col is out of range. May
  976. /// ignore if it is impossible to know whether the placeholder exists without special
  977. /// support from back-end.
  978. ///
  979. virtual void bind(int col, double v)
  980. {
  981. do_bind(col, v);
  982. }
  983. ///
  984. /// Bind a floating point value to column \a col (starting from 1).
  985. ///
  986. /// Should throw invalid_placeholder() if the value of col is out of range. May
  987. /// ignore if it is impossible to know whether the placeholder exists without special
  988. /// support from back-end.
  989. ///
  990. virtual void bind(int col, long double v)
  991. {
  992. do_bind(col, v);
  993. }
  994. ///
  995. /// Bind a NULL value to column \a col (starting from 1).
  996. ///
  997. /// Should throw invalid_placeholder() if the value of col is out of range. May
  998. /// ignore if it is impossible to know whether the placeholder exists without special
  999. /// support from back-end.
  1000. ///
  1001. virtual void bind_null(int col)
  1002. {
  1003. at(col) = param();
  1004. }
  1005. ///
  1006. /// Fetch the last sequence generated for last inserted row. May use sequence as parameter
  1007. /// if the database uses sequences, should ignore the parameter \a sequence if the last
  1008. /// id is fetched without parameter.
  1009. ///
  1010. /// Should be called after exec() for insert statement, otherwise the behavior is undefined.
  1011. ///
  1012. /// MUST throw not_supported_by_backend() if such option is not supported by the DB engine.
  1013. ///
  1014. virtual long long sequence_last(std::string const&/*sequence*/)
  1015. {
  1016. return mysql_stmt_insert_id(stmt_);
  1017. }
  1018. ///
  1019. /// Return the number of affected rows by last statement.
  1020. ///
  1021. /// Should be called after exec(), otherwise behavior is undefined.
  1022. ///
  1023. virtual unsigned long long affected()
  1024. {
  1025. return mysql_stmt_affected_rows(stmt_);
  1026. }
  1027. void bind_all()
  1028. {
  1029. if (!params_.empty()) {
  1030. for (unsigned i = 0; i < params_.size(); i++)
  1031. params_[i].bind_it(&bind_[i]);
  1032. if (mysql_stmt_bind_param(stmt_, &bind_.front())) {
  1033. throw cppdb_myerror(mysql_stmt_error(stmt_));
  1034. }
  1035. }
  1036. }
  1037. ///
  1038. /// Return SQL Query result, MAY throw cppdb_error if the statement is not a query
  1039. ///
  1040. virtual result* query()
  1041. {
  1042. bind_all();
  1043. if (mysql_stmt_execute(stmt_)) {
  1044. throw cppdb_myerror(mysql_stmt_error(stmt_));
  1045. }
  1046. return new result(stmt_);
  1047. }
  1048. ///
  1049. /// Execute a statement, MAY throw cppdb_error if the statement returns results.
  1050. ///
  1051. virtual void exec()
  1052. {
  1053. bind_all();
  1054. if (mysql_stmt_execute(stmt_)) {
  1055. throw cppdb_myerror(mysql_stmt_error(stmt_));
  1056. }
  1057. if (mysql_stmt_store_result(stmt_)) {
  1058. throw cppdb_myerror(mysql_stmt_error(stmt_));
  1059. }
  1060. MYSQL_RES* r = mysql_stmt_result_metadata(stmt_);
  1061. if (r) {
  1062. mysql_free_result(r);
  1063. throw cppdb_myerror("Calling exec() on query!");
  1064. }
  1065. }
  1066. // End of API
  1067. // Caching support
  1068. statement(std::string const& q, MYSQL* conn) :
  1069. query_(q),
  1070. stmt_(0),
  1071. params_count_(0)
  1072. {
  1073. fmt_.imbue(std::locale::classic());
  1074. stmt_ = mysql_stmt_init(conn);
  1075. try {
  1076. if (!stmt_) {
  1077. throw cppdb_myerror(" Failed to create a statement");
  1078. }
  1079. if (mysql_stmt_prepare(stmt_, q.c_str(), q.size())) {
  1080. throw cppdb_myerror(mysql_stmt_error(stmt_));
  1081. }
  1082. params_count_ = mysql_stmt_param_count(stmt_);
  1083. reset_data();
  1084. }
  1085. catch (...) {
  1086. if (stmt_)
  1087. mysql_stmt_close(stmt_);
  1088. throw;
  1089. }
  1090. }
  1091. virtual ~statement()
  1092. {
  1093. mysql_stmt_close(stmt_);
  1094. }
  1095. void reset_data()
  1096. {
  1097. params_.resize(0);
  1098. params_.resize(params_count_);
  1099. bind_.resize(0);
  1100. bind_.resize(params_count_, MYSQL_BIND());
  1101. }
  1102. virtual void reset()
  1103. {
  1104. reset_data();
  1105. mysql_stmt_reset(stmt_);
  1106. }
  1107. private:
  1108. param& at(int col)
  1109. {
  1110. if (col < 1 || col > params_count_)
  1111. throw invalid_placeholder();
  1112. return params_[col - 1];
  1113. }
  1114. std::ostringstream fmt_;
  1115. std::vector<param> params_;
  1116. std::vector<MYSQL_BIND> bind_;
  1117. std::string query_;
  1118. MYSQL_STMT* stmt_;
  1119. int params_count_;
  1120. };
  1121. } // prep
  1122. class connection;
  1123. class connection : public backend::connection {
  1124. public:
  1125. connection(connection_info const& ci) :
  1126. backend::connection(ci),
  1127. conn_(0)
  1128. {
  1129. conn_ = mysql_init(0);
  1130. if (!conn_) {
  1131. throw cppdb_error("cppdb::mysql failed to create connection");
  1132. }
  1133. std::string host = ci.get("host", "");
  1134. char const* phost = host.empty() ? 0 : host.c_str();
  1135. std::string user = ci.get("user", "");
  1136. char const* puser = user.empty() ? 0 : user.c_str();
  1137. std::string password = ci.get("password", "");
  1138. char const* ppassword = password.empty() ? 0 : password.c_str();
  1139. std::string database = ci.get("database", "");
  1140. char const* pdatabase = database.empty() ? 0 : database.c_str();
  1141. int port = ci.get("port", 0);
  1142. std::string unix_socket = ci.get("unix_socket", "");
  1143. char const* punix_socket = unix_socket.empty() ? 0 : unix_socket.c_str();
  1144. #if MYSQL_VERSION_ID >= 50507
  1145. std::string default_auth = ci.get("default_auth", "");
  1146. if (!default_auth.empty()) {
  1147. mysql_set_option(MYSQL_DEFAULT_AUTH, default_auth.c_str());
  1148. }
  1149. #endif
  1150. std::string init_command = ci.get("init_command", "");
  1151. if (!init_command.empty()) {
  1152. mysql_set_option(MYSQL_INIT_COMMAND, init_command.c_str());
  1153. }
  1154. if (ci.has("opt_compress")) {
  1155. if (ci.get("opt_compress", 1)) {
  1156. mysql_set_option(MYSQL_OPT_COMPRESS, NULL);
  1157. }
  1158. }
  1159. if (ci.has("opt_connect_timeout")) {
  1160. if (unsigned connect_timeout = ci.get("opt_connect_timeout", 0)) {
  1161. mysql_set_option(MYSQL_OPT_CONNECT_TIMEOUT, &connect_timeout);
  1162. }
  1163. }
  1164. #if (MYSQL_VERSION_ID < 80000) || defined(MARIADB_BASE_VERSION)
  1165. if (ci.has("opt_guess_connection")) {
  1166. if (ci.get("opt_guess_connection", 1)) {
  1167. mysql_set_option(MYSQL_OPT_GUESS_CONNECTION, NULL);
  1168. }
  1169. }
  1170. #endif
  1171. if (ci.has("opt_local_infile")) {
  1172. if (unsigned local_infile = ci.get("opt_local_infile", 0)) {
  1173. mysql_set_option(MYSQL_OPT_CONNECT_TIMEOUT, &local_infile);
  1174. }
  1175. }
  1176. if (ci.has("opt_named_pipe")) {
  1177. if (ci.get("opt_named_pipe", 1)) {
  1178. mysql_set_option(MYSQL_OPT_NAMED_PIPE, NULL);
  1179. }
  1180. }
  1181. if (ci.has("opt_protocol")) {
  1182. if (unsigned protocol = ci.get("opt_protocol", 0)) {
  1183. mysql_set_option(MYSQL_OPT_PROTOCOL, &protocol);
  1184. }
  1185. }
  1186. if (ci.has("opt_read_timeout")) {
  1187. if (unsigned read_timeout = ci.get("opt_read_timeout", 0)) {
  1188. mysql_set_option(MYSQL_OPT_READ_TIMEOUT, &read_timeout);
  1189. }
  1190. }
  1191. if (ci.has("opt_reconnect")) {
  1192. if (unsigned reconnect = ci.get("opt_reconnect", 1)) {
  1193. bool value = reconnect;
  1194. mysql_set_option(MYSQL_OPT_RECONNECT, &value);
  1195. }
  1196. }
  1197. #if MYSQL_VERSION_ID >= 50507
  1198. std::string plugin_dir = ci.get("plugin_dir", "");
  1199. if (!plugin_dir.empty()) {
  1200. mysql_set_option(MYSQL_PLUGIN_DIR, plugin_dir.c_str());
  1201. }
  1202. #endif
  1203. std::string set_client_ip = ci.get("set_client_ip", "");
  1204. #if (MYSQL_VERSION_ID < 80000) || defined(MARIADB_BASE_VERSION)
  1205. if (!set_client_ip.empty()) {
  1206. mysql_set_option(MYSQL_SET_CLIENT_IP, set_client_ip.c_str());
  1207. }
  1208. if (ci.has("opt_ssl_verify_server_cert")) {
  1209. if (unsigned verify = ci.get("opt_ssl_verify_server_cert", 1)) {
  1210. bool value = verify;
  1211. mysql_set_option(MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &value);
  1212. }
  1213. }
  1214. if (ci.has("opt_use_embedded_connection")) {
  1215. if (ci.get("opt_use_embedded_connection", 1)) {
  1216. mysql_set_option(MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
  1217. }
  1218. }
  1219. if (ci.has("opt_use_remote_connection")) {
  1220. if (ci.get("opt_use_remote_connection", 1)) {
  1221. mysql_set_option(MYSQL_OPT_USE_REMOTE_CONNECTION, NULL);
  1222. }
  1223. }
  1224. #endif
  1225. if (ci.has("opt_write_timeout")) {
  1226. if (unsigned write_timeout = ci.get("opt_write_timeout", 0)) {
  1227. mysql_set_option(MYSQL_OPT_WRITE_TIMEOUT, &write_timeout);
  1228. }
  1229. }
  1230. std::string read_default_file = ci.get("read_default_file", "");
  1231. if (!read_default_file.empty()) {
  1232. mysql_set_option(MYSQL_READ_DEFAULT_FILE, read_default_file.c_str());
  1233. }
  1234. std::string read_default_group = ci.get("read_default_group", "");
  1235. if (!read_default_group.empty()) {
  1236. mysql_set_option(MYSQL_READ_DEFAULT_GROUP, read_default_group.c_str());
  1237. }
  1238. if (ci.has("report_data_truncation")) {
  1239. if (unsigned report = ci.get("report_data_truncation", 1)) {
  1240. bool value = report;
  1241. mysql_set_option(MYSQL_REPORT_DATA_TRUNCATION, &value);
  1242. }
  1243. }
  1244. #if MYSQL_VERSION_ID >= 40101
  1245. #if (MYSQL_VERSION_ID < 80000) || defined(MARIADB_BASE_VERSION)
  1246. if (ci.has("secure_auth")) {
  1247. if (unsigned secure = ci.get("secure_auth", 1)) {
  1248. bool value = secure;
  1249. mysql_set_option(MYSQL_SECURE_AUTH, &value);
  1250. }
  1251. }
  1252. #endif
  1253. #endif
  1254. std::string set_charset_dir = ci.get("set_charset_dir", "");
  1255. if (!set_charset_dir.empty()) {
  1256. mysql_set_option(MYSQL_SET_CHARSET_DIR, set_charset_dir.c_str());
  1257. }
  1258. std::string set_charset_name = ci.get("set_charset_name", "");
  1259. if (!set_charset_name.empty()) {
  1260. mysql_set_option(MYSQL_SET_CHARSET_NAME, set_charset_name.c_str());
  1261. }
  1262. std::string shared_memory_base_name = ci.get("shared_memory_base_name", "");
  1263. if (!shared_memory_base_name.empty()) {
  1264. mysql_set_option(MYSQL_SHARED_MEMORY_BASE_NAME, shared_memory_base_name.c_str());
  1265. }
  1266. if (!mysql_real_connect(conn_, phost, puser, ppassword, pdatabase, port, punix_socket, 0)) {
  1267. std::string err = "unknown";
  1268. try { err = mysql_error(conn_); }
  1269. catch (...) {}
  1270. mysql_close(conn_);
  1271. throw cppdb_myerror(err);
  1272. }
  1273. }
  1274. ~connection()
  1275. {
  1276. mysql_close(conn_);
  1277. }
  1278. // API
  1279. void exec(std::string const& s)
  1280. {
  1281. if (mysql_real_query(conn_, s.c_str(), s.size())) {
  1282. throw cppdb_myerror(mysql_error(conn_));
  1283. }
  1284. }
  1285. ///
  1286. /// Start new isolated transaction. Would not be called
  1287. /// withing other transaction on current connection.
  1288. ///
  1289. virtual void begin()
  1290. {
  1291. exec("BEGIN");
  1292. }
  1293. ///
  1294. /// Commit the transaction, you may assume that is called after begin()
  1295. /// was called.
  1296. ///
  1297. virtual void commit()
  1298. {
  1299. exec("COMMIT");
  1300. }
  1301. ///
  1302. /// Rollback the transaction. MUST never throw!!!
  1303. ///
  1304. virtual void rollback()
  1305. {
  1306. try {
  1307. exec("ROLLBACK");
  1308. }
  1309. catch (...) {
  1310. }
  1311. }
  1312. ///
  1313. /// Create a prepared statement \a q. May throw if preparation had failed.
  1314. /// Should never return null value.
  1315. ///
  1316. virtual backend::statement* prepare_statement(std::string const& q)
  1317. {
  1318. return new prep::statement(q, conn_);
  1319. }
  1320. virtual backend::statement* create_statement(std::string const& q)
  1321. {
  1322. return new unprep::statement(q, conn_);
  1323. }
  1324. ///
  1325. /// Escape a string for inclusion in SQL query. May throw not_supported_by_backend() if not supported by backend.
  1326. ///
  1327. virtual std::string escape(std::string const& s)
  1328. {
  1329. return escape(s.c_str(), s.c_str() + s.size());
  1330. }
  1331. ///
  1332. /// Escape a string for inclusion in SQL query. May throw not_supported_by_backend() if not supported by backend.
  1333. ///
  1334. virtual std::string escape(char const* s)
  1335. {
  1336. return escape(s, s + strlen(s));
  1337. }
  1338. ///
  1339. /// Escape a string for inclusion in SQL query. May throw not_supported_by_backend() if not supported by backend.
  1340. ///
  1341. virtual std::string escape(char const* b, char const* e)
  1342. {
  1343. std::vector<char> buf(2 * (e - b) + 1);
  1344. size_t len = mysql_real_escape_string(conn_, &buf.front(), b, e - b);
  1345. std::string result;
  1346. result.assign(&buf.front(), len);
  1347. return result;
  1348. }
  1349. ///
  1350. /// Get the name of the driver, for example sqlite3, odbc
  1351. ///
  1352. virtual std::string driver()
  1353. {
  1354. return "mysql";
  1355. }
  1356. ///
  1357. /// Get the name of the SQL Server, for example sqlite3, mssql, oracle, differs from driver() when
  1358. /// the backend supports multiple databases like odbc backend.
  1359. ///
  1360. virtual std::string engine()
  1361. {
  1362. return "mysql";
  1363. }
  1364. // API
  1365. private:
  1366. ///
  1367. /// Set a custom MYSQL option on the connection.
  1368. ///
  1369. ///
  1370. void mysql_set_option(mysql_option option, const void* arg)
  1371. {
  1372. // char can be casted to void but not the other way, support older API
  1373. if (mysql_options(conn_, option, static_cast<char const*>(arg))) {
  1374. throw cppdb_error("cppdb::mysql failed to set option");
  1375. }
  1376. }
  1377. connection_info ci_;
  1378. MYSQL* conn_;
  1379. };
  1380. } // backend
  1381. } // cppdb
  1382. extern "C" {
  1383. CPPDB_DRIVER_API cppdb::backend::connection* cppdb_mysql_get_connection(cppdb::connection_info const& cs)
  1384. {
  1385. return new cppdb::mysql_backend::connection(cs);
  1386. }
  1387. }