Update.cc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright: All Rights Reserved
  2. // Author: egametang@gmail.com (tanghai)
  3. #include <google/protobuf/descriptor.h>
  4. #include "Orm/Update.h"
  5. #include "Orm/Column.h"
  6. #include "Orm/Exception.h"
  7. #include "Orm/MessageField.h"
  8. namespace Egametang {
  9. Update::Update(google::protobuf::Message& message): message(message)
  10. {
  11. }
  12. Update& Update::Where(Expr expr)
  13. {
  14. expr.CheckAllColumns(message);
  15. where = expr;
  16. return *this;
  17. }
  18. std::string Update::ToString() const
  19. {
  20. int fieldIsSetCount = 0;
  21. std::string sql = "update " + message.GetDescriptor()->full_name();
  22. sql += " set ";
  23. const google::protobuf::Descriptor* descriptor = message.GetDescriptor();
  24. const google::protobuf::Reflection* reflection = message.GetReflection();
  25. for (int i = 0; i < descriptor->field_count(); ++i)
  26. {
  27. const google::protobuf::FieldDescriptor* field = descriptor->field(i);
  28. if (!reflection->HasField(message, field))
  29. {
  30. continue;
  31. }
  32. ++fieldIsSetCount;
  33. MessageField messageField(message, field);
  34. sql += field->name() + " = " + messageField.GetField() + ", ";
  35. }
  36. if (fieldIsSetCount == 0)
  37. {
  38. throw MessageNoFeildIsSetException() << MessageNoFeildIsSetErrStr("no field is set");
  39. }
  40. // 去除最后的逗号和空格
  41. sql.resize(sql.size() - 2);
  42. if (!where.Empty())
  43. {
  44. sql += " where " + where.ToString();
  45. }
  46. return sql;
  47. }
  48. } // namespace Egametang