database_controller.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * @Description: 数据库操作类
  3. * @Author: yct
  4. * @Date: 2020-07-15 14:08:46
  5. * @LastEditTime: 2020-07-24 14:19:31
  6. * @LastEditors: yct
  7. */
  8. #include "database_controller.h"
  9. Database_controller::Database_controller()
  10. {
  11. m_database_controller_status = E_UNKNOWN;
  12. mp_reconnect_thread = nullptr;
  13. m_conn_pool_size = 0;
  14. }
  15. Database_controller::~Database_controller()
  16. {
  17. database_controller_uninit();
  18. }
  19. Error_manager Database_controller::database_controller_init()
  20. {
  21. return database_controller_init_from_protobuf(DATABASE_COMMUNICATION_PARAMETER_PATH);
  22. }
  23. Error_manager Database_controller::database_controller_init_from_protobuf(std::string prototxt_path)
  24. {
  25. parkspace_proto::Database_communication_configuration_all t_database_config;
  26. if(! proto_tool::read_proto_param(prototxt_path,t_database_config) )
  27. {
  28. return Error_manager(DB_PROTOBUF_ERROR,MINOR_ERROR,
  29. "database_controller_init_from_protobuf(std::string prototxt_path) failed");
  30. }
  31. else
  32. {
  33. Error_manager t_error;
  34. t_error=database_controller_init(t_database_config.database_communication_configurations().db_ip(),\
  35. t_database_config.database_communication_configurations().db_port(),\
  36. t_database_config.database_communication_configurations().db_username(),\
  37. t_database_config.database_communication_configurations().db_passwd(),\
  38. t_database_config.database_communication_configurations().db_name(),\
  39. t_database_config.database_communication_configurations().db_conn_pool_size());
  40. if ( t_error != Error_code::SUCCESS )
  41. {
  42. return t_error;
  43. }
  44. }
  45. return SUCCESS;
  46. }
  47. //初始化
  48. Error_manager Database_controller::database_controller_init(std::string ip, int port, std::string username, std::string pass, std::string db_name, int conn_size)
  49. {
  50. Error_manager t_error;
  51. //系统结束标记与连接池大小
  52. // mb_exit = false;
  53. m_conn_pool_size = conn_size;
  54. m_db_param.connect_string = std::string("tcp://").append(ip).append(":").append(std::to_string(port));
  55. m_db_param.username = username;
  56. m_db_param.pass = pass;
  57. m_db_param.db_name = db_name;
  58. if(sql::mysql::get_driver_instance() == nullptr)
  59. {
  60. //胡力 直接修改状态
  61. m_database_controller_status = E_FAULT;
  62. // mb_initialized = false;
  63. return DB_INIT_FAILED;
  64. return Error_manager(Error_code::DB_INIT_FAILED, Error_level::MAJOR_ERROR,
  65. "数据库初始化失败 Database_controller::database_controller_init error ");
  66. }
  67. ////创建补充 数据库连接的通路
  68. t_error = fill_up_connect_channel();
  69. //守护线程,检查连接状态并保持连接数量
  70. m_database_reconnect_condition.reset(false,false,false);
  71. mp_reconnect_thread = new std::thread(&Database_controller::database_reconnect_thread, this);
  72. return t_error;
  73. }
  74. //反初始化
  75. Error_manager Database_controller::database_controller_uninit()
  76. {
  77. // mb_exit = true;
  78. if(mp_reconnect_thread!=nullptr)
  79. {
  80. m_database_reconnect_condition.kill_all();
  81. }
  82. if(mp_reconnect_thread!=nullptr)
  83. {
  84. if(mp_reconnect_thread->joinable())
  85. mp_reconnect_thread->join();
  86. delete mp_reconnect_thread;
  87. mp_reconnect_thread = nullptr;
  88. }
  89. m_database_connect_channel_list.clear();
  90. return SUCCESS;
  91. }
  92. Database_controller::Database_controller_status Database_controller::get_database_controller_status()
  93. {
  94. return m_database_controller_status;
  95. }
  96. Error_manager Database_controller::check_status()
  97. {
  98. if(get_database_controller_status()==E_READY)
  99. {
  100. return SUCCESS;
  101. }
  102. else if(get_database_controller_status() == E_UNKNOWN)
  103. {
  104. return Error_manager(Error_code::DB_INIT_FAILED, Error_level::MINOR_ERROR,
  105. "数据库初始化失败 check_status() error ");
  106. }
  107. else if(get_database_controller_status() == E_DISCONNECT)
  108. {
  109. return Error_manager(Error_code::DB_CONNECT_FAILED, Error_level::MINOR_ERROR,
  110. "数据库连接失败 check_status() error ");
  111. }
  112. else if(get_database_controller_status() == E_FAULT)
  113. {
  114. return Error_manager(Error_code::DB_STATUS_ERROR, Error_level::MINOR_ERROR,
  115. "数据库状态错误 check_status() error ");
  116. }
  117. }
  118. //数据库连接状态
  119. bool Database_controller::is_connected()
  120. {
  121. if ( m_database_controller_status == E_READY)
  122. {
  123. return true;
  124. }
  125. else
  126. {
  127. return false;
  128. }
  129. //
  130. // updata_connect_channel();
  131. // return mb_connected;
  132. }
  133. //****** 增删改查功能 *******
  134. //增
  135. Error_manager Database_controller::sql_insert(std::string sql_str)
  136. {
  137. Error_manager t_error;
  138. //huli
  139. t_error = check_status();
  140. if ( t_error != Error_code::SUCCESS )
  141. {
  142. return t_error;
  143. }
  144. boost::shared_ptr<Database_connect_channel> tp_database_connect_channel;
  145. t_error = occupancy_connect_channel(tp_database_connect_channel);
  146. if ( t_error != Error_code::SUCCESS )
  147. {
  148. return t_error;
  149. }
  150. char buf[1024];
  151. memset(buf, 0, 1024);
  152. try
  153. {
  154. tp_database_connect_channel->mp_connect_channel->setSchema(m_db_param.db_name);
  155. boost::scoped_ptr<sql::Statement> stmt(tp_database_connect_channel->mp_connect_channel->createStatement());
  156. stmt->execute(sql_str);
  157. giveback_connect_channel(tp_database_connect_channel);
  158. return SUCCESS;
  159. }
  160. catch (sql::SQLException &e)
  161. {
  162. giveback_connect_channel(tp_database_connect_channel);
  163. /* Use what() (derived from std::runtime_error) to fetch the error message */
  164. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  165. usleep(1000* 3000);
  166. return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  167. }
  168. catch (std::runtime_error &e)
  169. {
  170. giveback_connect_channel(tp_database_connect_channel);
  171. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  172. return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  173. }
  174. // catch (std::exception &e)
  175. // {
  176. // sprintf(buf, "# ERR: %s\n ERR: Standard exception in %s ",e.what(),__FILE__);
  177. // return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  178. // }
  179. return SUCCESS;
  180. }
  181. //删
  182. Error_manager Database_controller::sql_delete(std::string sql_str)
  183. {
  184. // 1.检查状态,一旦无可用连接,则主动创建一个,若依然失败则直接返回错误
  185. Error_manager t_error;
  186. //huli
  187. t_error = check_status();
  188. if ( t_error != Error_code::SUCCESS )
  189. {
  190. return t_error;
  191. }
  192. boost::shared_ptr<Database_connect_channel> tp_database_connect_channel;
  193. t_error = occupancy_connect_channel(tp_database_connect_channel);
  194. if ( t_error != Error_code::SUCCESS )
  195. {
  196. return t_error;
  197. }
  198. char buf[1024];
  199. memset(buf, 0, 1024);
  200. try
  201. {
  202. tp_database_connect_channel->mp_connect_channel->setSchema(m_db_param.db_name);
  203. boost::scoped_ptr<sql::Statement> stmt(tp_database_connect_channel->mp_connect_channel->createStatement());
  204. stmt->execute(sql_str);
  205. giveback_connect_channel(tp_database_connect_channel);
  206. return SUCCESS;
  207. }
  208. catch (sql::SQLException &e)
  209. {
  210. /* Use what() (derived from std::runtime_error) to fetch the error message */
  211. giveback_connect_channel(tp_database_connect_channel);
  212. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  213. return Error_manager(DB_DELETE_FAILED, NEGLIGIBLE_ERROR, buf);
  214. }
  215. catch (std::runtime_error &e)
  216. {
  217. giveback_connect_channel(tp_database_connect_channel);
  218. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  219. return Error_manager(DB_DELETE_FAILED, NEGLIGIBLE_ERROR, buf);
  220. }
  221. return SUCCESS;
  222. }
  223. //改
  224. Error_manager Database_controller::sql_update(std::string sql_str)
  225. {
  226. Error_manager t_error;
  227. //huli
  228. t_error = check_status();
  229. if ( t_error != Error_code::SUCCESS )
  230. {
  231. return t_error;
  232. }
  233. boost::shared_ptr<Database_connect_channel> tp_database_connect_channel;
  234. t_error = occupancy_connect_channel(tp_database_connect_channel);
  235. if ( t_error != Error_code::SUCCESS )
  236. {
  237. return t_error;
  238. }
  239. char buf[1024];
  240. memset(buf, 0, 1024);
  241. try
  242. {
  243. tp_database_connect_channel->mp_connect_channel->setSchema(m_db_param.db_name);
  244. boost::scoped_ptr<sql::Statement> stmt(tp_database_connect_channel->mp_connect_channel->createStatement());
  245. int affected_rows = stmt->executeUpdate(sql_str);
  246. giveback_connect_channel(tp_database_connect_channel);
  247. if (affected_rows > 0)
  248. {
  249. return SUCCESS;
  250. }
  251. else
  252. {
  253. return Error_manager(Error_code::DB_UPDATE_FAILED, Error_level::MINOR_ERROR,
  254. (std::string("数据库修改失败 Database_controller::sql_update error ")+sql_str).c_str());
  255. }
  256. }
  257. catch (sql::SQLException &e)
  258. {
  259. /* Use what() (derived from std::runtime_error) to fetch the error message */
  260. giveback_connect_channel(tp_database_connect_channel);
  261. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  262. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  263. }
  264. catch (std::runtime_error &e)
  265. {
  266. giveback_connect_channel(tp_database_connect_channel);
  267. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  268. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  269. }
  270. return SUCCESS;
  271. }
  272. //查
  273. Error_manager Database_controller::sql_query(std::string sql_str, boost::shared_ptr< sql::ResultSet > &query_result)
  274. {
  275. Error_manager t_error;
  276. //huli
  277. t_error = check_status();
  278. if ( t_error != Error_code::SUCCESS )
  279. {
  280. return t_error;
  281. }
  282. boost::shared_ptr<Database_connect_channel> tp_database_connect_channel;
  283. t_error = occupancy_connect_channel(tp_database_connect_channel);
  284. if ( t_error != Error_code::SUCCESS )
  285. {
  286. return t_error;
  287. }
  288. char buf[1024];
  289. memset(buf, 0, 1024);
  290. try
  291. {
  292. tp_database_connect_channel->mp_connect_channel->setSchema(m_db_param.db_name);
  293. boost::scoped_ptr<sql::Statement> stmt(tp_database_connect_channel->mp_connect_channel->createStatement());
  294. query_result = boost::shared_ptr< sql::ResultSet >(stmt->executeQuery(sql_str));
  295. giveback_connect_channel(tp_database_connect_channel);
  296. // 检查结果
  297. if(query_result==nullptr)
  298. {
  299. return Error_manager(Error_code::DB_QUERY_FAILED, Error_level::MAJOR_ERROR,
  300. (std::string("数据库查询失败 Database_controller::sql_query error ")+sql_str).c_str());
  301. }
  302. }
  303. catch (sql::SQLException &e)
  304. {
  305. /* Use what() (derived from std::runtime_error) to fetch the error message */
  306. giveback_connect_channel(tp_database_connect_channel);
  307. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  308. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  309. }
  310. catch (std::runtime_error &e)
  311. {
  312. giveback_connect_channel(tp_database_connect_channel);
  313. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  314. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  315. }
  316. return SUCCESS;
  317. }
  318. void Database_controller::database_reconnect_thread()
  319. {
  320. //hili 这个用条件变量去控制
  321. while (m_database_reconnect_condition.is_alive())
  322. {
  323. m_database_reconnect_condition.wait_for_ex(std::chrono::seconds(1));
  324. if (m_database_reconnect_condition.is_alive())
  325. {
  326. updata_connect_channel();
  327. fill_up_connect_channel();
  328. }
  329. }
  330. }
  331. // 检查连接状态
  332. Error_manager Database_controller::updata_connect_channel()
  333. {
  334. for (auto iter = m_database_connect_channel_list.begin(); iter != m_database_connect_channel_list.end();)
  335. {
  336. if ((*iter)->mp_connect_channel == nullptr)
  337. {
  338. iter = m_database_connect_channel_list.erase(iter);
  339. }
  340. else if ( (*iter)->m_occupancy_lock.try_lock() )
  341. {
  342. if( (*iter)->mp_connect_channel->isValid() )
  343. {
  344. (*iter)->m_occupancy_lock.unlock();
  345. ++iter;
  346. }
  347. else
  348. {
  349. (*iter)->m_occupancy_lock.unlock();
  350. iter = m_database_connect_channel_list.erase(iter);
  351. }
  352. }
  353. else
  354. {
  355. ++iter;
  356. }
  357. }
  358. return Error_code::SUCCESS;
  359. }
  360. ////创建补充 数据库连接的通路
  361. Error_manager Database_controller::fill_up_connect_channel()
  362. {
  363. if ( m_conn_pool_size <=0 )
  364. {
  365. return Error_manager(Error_code::DB_CONNECT_CHANNEL_NUMBER_ERROR, Error_level::MINOR_ERROR,
  366. "数据库连接通道数量错误 Database_controller::fill_up_connect_channel() error ");
  367. }
  368. // 填充连接池
  369. int retry_count = DB_RECONNECTION_NUMBER;
  370. //胡力 建议修改如下
  371. while (m_database_connect_channel_list.size() < m_conn_pool_size && retry_count > 0)
  372. {
  373. try
  374. {
  375. //胡力 数据库连接的指针 建议改名 tp_sql_connnect
  376. boost::shared_ptr<sql::Connection> tp_connect_channel(sql::mysql::get_driver_instance()->connect(m_db_param.connect_string, m_db_param.username, m_db_param.pass));
  377. if (tp_connect_channel != nullptr && tp_connect_channel->isValid())
  378. {
  379. boost::shared_ptr<Database_connect_channel> tp_database_connect_channel(new Database_connect_channel);
  380. tp_database_connect_channel->mp_connect_channel = tp_connect_channel;
  381. // tp_database_connect_channel->m_occupancy_lock.unlock();
  382. m_database_connect_channel_list.push_back(tp_database_connect_channel);
  383. }
  384. else
  385. {
  386. retry_count--;
  387. }
  388. }
  389. catch (sql::SQLException &e)
  390. {
  391. char buf[1024];
  392. memset(buf, 0, 1024);
  393. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str());
  394. retry_count--;
  395. }
  396. }
  397. if ( retry_count <= 0 )
  398. {
  399. m_database_controller_status = E_DISCONNECT;
  400. //胡力 如果报错 队列中部分成功要回收处理 需要讨论!!!!!!!!!!!!!!!!!!
  401. m_database_connect_channel_list.clear();
  402. return Error_manager(Error_code::DB_CONNECT_FAILED, Error_level::MINOR_ERROR,
  403. "数据库连接失败 Database_controller::fill_up_connect_channel() error ");
  404. }
  405. else
  406. {
  407. m_database_controller_status = E_READY;
  408. return Error_code::SUCCESS;
  409. }
  410. return SUCCESS;
  411. }
  412. //zhan you jieyong
  413. Error_manager Database_controller::occupancy_connect_channel(boost::shared_ptr<Database_connect_channel> & p_database_connect_channel)
  414. {
  415. for (auto iter = m_database_connect_channel_list.begin(); iter != m_database_connect_channel_list.end(); ++iter)
  416. {
  417. if ( (*iter)->mp_connect_channel != nullptr)
  418. {
  419. if ( (*iter)->m_occupancy_lock.try_lock() )
  420. {
  421. if ( (*iter)->mp_connect_channel->isValid() )
  422. // if ( !(*iter)->mp_connect_channel->isClosed() )
  423. {
  424. p_database_connect_channel = (*iter);
  425. return Error_code::SUCCESS;
  426. }
  427. (*iter)->m_occupancy_lock.unlock();
  428. }
  429. }
  430. //
  431. //
  432. //
  433. // if ( (*iter)->mp_connect_channel != nullptr && (*iter)->mp_connect_channel->isValid() )
  434. // {
  435. // if ( (*iter)->m_occupancy_lock.try_lock() )
  436. // {
  437. // p_database_connect_channel = (*iter);
  438. // return Error_code::SUCCESS;
  439. // }
  440. //
  441. // }
  442. }
  443. //if not find
  444. return Error_manager(Error_code::DB_CONNECT_CHANNEL_NOT_FOUND, Error_level::MINOR_ERROR,
  445. "数据库连接通道未找到 Database_controller::occupancy_connect_channel error ");
  446. }
  447. //guihuan
  448. Error_manager Database_controller::giveback_connect_channel(boost::shared_ptr<Database_connect_channel> p_database_connect_channel)
  449. {
  450. if ( p_database_connect_channel == nullptr )
  451. {
  452. return Error_manager(Error_code::POINTER_IS_NULL, Error_level::MINOR_ERROR,
  453. "指针为空 Database_controller::giveback_connect_channel error ");
  454. }
  455. p_database_connect_channel->m_occupancy_lock.unlock();
  456. return Error_code::SUCCESS;
  457. }