Query.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #ifndef ORM_QUERY_H
  2. #define ORM_QUERY_H
  3. #include <string>
  4. #include <vector>
  5. #include <boost/lexical_cast.hpp>
  6. #include "Orm/Expr.h"
  7. #include "Orm/Column.h"
  8. namespace Egametang {
  9. template <typename Table>
  10. class Query
  11. {
  12. std::string columns;
  13. bool distinct;
  14. std::string where;
  15. std::string groupBy;
  16. std::string having;
  17. std::string orderBy;
  18. int limit;
  19. int offset;
  20. public:
  21. Query(): distinct(false), where("true"), limit(0), offset(0)
  22. {
  23. }
  24. ~Query()
  25. {
  26. }
  27. Query<Table>& Select(Column column)
  28. {
  29. columns = column.ToString();
  30. return *this;
  31. }
  32. Query<Table>& Distinct(bool value)
  33. {
  34. distinct = value;
  35. return *this;
  36. }
  37. Query<Table>& Where(const Expr& expr)
  38. {
  39. where = expr.ToString();
  40. return *this;
  41. }
  42. Query<Table>& GroupBy(Column column)
  43. {
  44. groupBy = column.ToString();
  45. return *this;
  46. }
  47. Query<Table>& Having(const Expr& having)
  48. {
  49. having = having.ToString();
  50. return *this;
  51. }
  52. Query<Table>& OrderBy(Column column, bool ascending)
  53. {
  54. std::string value = column.ToString();
  55. if (!ascending)
  56. {
  57. value += " desc";
  58. }
  59. orderBy = value;
  60. return *this;
  61. }
  62. Query<Table>& Limit(int value)
  63. {
  64. limit = value;
  65. return *this;
  66. }
  67. Query<Table>& Offset(int value)
  68. {
  69. offset = value;
  70. return *this;
  71. }
  72. std::string ToString() const
  73. {
  74. std::string sql = "select ";
  75. if (!columns.empty())
  76. {
  77. sql += columns;
  78. }
  79. if (distinct)
  80. {
  81. sql += " distinct";
  82. }
  83. sql += " from " + Table::descriptor()->full_name();
  84. if (where != "true")
  85. {
  86. sql += " where " + where;
  87. }
  88. if (!groupBy.empty())
  89. {
  90. sql += " group by " + groupBy;
  91. }
  92. if (!having.empty())
  93. {
  94. sql += " having " + having;
  95. }
  96. if (!orderBy.empty())
  97. {
  98. sql += " order by " + orderBy;
  99. }
  100. if (limit)
  101. {
  102. sql += " limit " + boost::lexical_cast<std::string>(limit);
  103. }
  104. if (offset)
  105. {
  106. sql += " offset " + boost::lexical_cast<std::string>(offset);
  107. }
  108. return sql;
  109. }
  110. };
  111. } // namespace Egametang
  112. #endif // ORM_QUERY_H