Query.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include <google/protobuf/descriptor.h>
  2. #include <glog/logging.h>
  3. #include "Orm/Query.h"
  4. namespace Egametang {
  5. SelectQuery& SelectQuery::Distinct(bool d)
  6. {
  7. distinct = d;
  8. return *this;
  9. }
  10. SelectQuery& SelectQuery::Limit(int value)
  11. {
  12. limit = value;
  13. return *this;
  14. }
  15. SelectQuery& SelectQuery::Offset(int value)
  16. {
  17. offset = value;
  18. return *this;
  19. }
  20. SelectQuery& SelectQuery::Result(std::string r)
  21. {
  22. results.push_back(r);
  23. return *this;
  24. }
  25. SelectQuery& SelectQuery::ClearResults()
  26. {
  27. results.clear();
  28. return *this;
  29. }
  30. SelectQuery& SelectQuery::Source(std::string s, std::string alias)
  31. {
  32. if (!alias.empty())
  33. s += " as " + alias;
  34. sources.push_back(s);
  35. return *this;
  36. }
  37. SelectQuery& SelectQuery::Where(const Expr& w)
  38. {
  39. where = (RawExpr(where) && w).asString();
  40. return *this;
  41. }
  42. SelectQuery& SelectQuery::Where(std::string w)
  43. {
  44. where = (RawExpr(where) && RawExpr(w)).asString();
  45. return *this;
  46. }
  47. SelectQuery& SelectQuery::GroupBy(std::string gb)
  48. {
  49. groupBy.push_back(gb);
  50. return *this;
  51. }
  52. SelectQuery& SelectQuery::Having(const Expr & h)
  53. {
  54. having = h.asString();
  55. return *this;
  56. }
  57. SelectQuery& SelectQuery::Having(std::string h)
  58. {
  59. having = h;
  60. return *this;
  61. }
  62. SelectQuery& SelectQuery::OrderBy(std::string ob, bool ascending)
  63. {
  64. std::string value = ob;
  65. if (!ascending)
  66. {
  67. value += " desc";
  68. }
  69. orderBy.push_back(value);
  70. return *this;
  71. }
  72. SelectQuery::operator std::string() const
  73. {
  74. std::string sql = "select ";
  75. if (distinct)
  76. {
  77. sql += "distinct ";
  78. }
  79. if (where != "true")
  80. {
  81. sql += " where " + where;
  82. }
  83. if (!groupBy.empty())
  84. {
  85. sql += " group by " + groupBy;
  86. }
  87. if (!having.empty())
  88. {
  89. sql += " having " + having;
  90. }
  91. if (orderBy.size() > 0)
  92. {
  93. sql += " order by " + orderBy.join(",");
  94. }
  95. if (limit)
  96. {
  97. sql += " limit " + boost::lexical_cast<std::string>(limit);
  98. }
  99. if (offset)
  100. {
  101. sql += " offset " + boost::lexical_cast<std::string>(offset);
  102. }
  103. return sql;
  104. }
  105. } // namespace Egametang