You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MySql.cpp 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Created by robin on 8/9/15.
  3. //
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <fstream>
  8. #include "MySql.h"
  9. #define tmpTemplate "/tmp/pdns-slave.XXXXXX"
  10. MySql::MySql(const SqlConfiguration &masterConfig, const SqlConfiguration &slaveConfig)
  11. : _masterConfig(masterConfig)
  12. , _slaveConfig(slaveConfig)
  13. {
  14. }
  15. MySql::~MySql()
  16. {
  17. clean();
  18. }
  19. BResult MySql::dump()
  20. {
  21. BResult res;
  22. _dumpFilePath = getTempFile();
  23. int status = system(std::string("mysqldump '-h" + _masterConfig.getHost() + "'"
  24. + " '-u" + _masterConfig.getUser() + "'"
  25. + " '-p" + _masterConfig.getPassword() + "'"
  26. + " " + _masterConfig.getDatabase()
  27. + " > " + _dumpFilePath).c_str());
  28. if (status == 0)
  29. return res.ok(true);
  30. return res.error("mysqldump exited with code " + std::to_string(status));
  31. }
  32. const std::string MySql::getTempFile()
  33. {
  34. char tmp[sizeof(tmpTemplate)];
  35. strcpy(tmp, tmpTemplate);
  36. mkstemp(tmp);
  37. return std::string(tmp);
  38. }
  39. void MySql::clean()
  40. {
  41. if (!_dumpFilePath.empty())
  42. {
  43. unlink(_dumpFilePath.c_str());
  44. _dumpFilePath = "";
  45. }
  46. if (!_overrideFilePath.empty())
  47. {
  48. unlink(_overrideFilePath.c_str());
  49. _overrideFilePath = "";
  50. }
  51. }
  52. BResult MySql::insert()
  53. {
  54. return insertSlave(_dumpFilePath);
  55. }
  56. BResult MySql::override(const std::string &sql)
  57. {
  58. _overrideFilePath = getTempFile();
  59. std::ofstream file(_overrideFilePath);
  60. if (!file)
  61. return BResult().error("Could not open temp file " + _overrideFilePath);
  62. file << sql;
  63. file.close();
  64. return insertSlave(_overrideFilePath);
  65. }
  66. BResult MySql::insertSlave(const std::string &file)
  67. {
  68. BResult res;
  69. int status = system(std::string("cat " + file + " | mysql '-h" + _slaveConfig.getHost() + "'"
  70. + " '-u" + _slaveConfig.getUser() + "'"
  71. + " '-p" + _slaveConfig.getPassword() + "'"
  72. + " " + _slaveConfig.getDatabase()).c_str());
  73. if (status == 0)
  74. return res.ok(true);
  75. return res.error("mysql exited with code " + std::to_string(status));
  76. }