Select.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 Select
  11. {
  12. private:
  13. Column select;
  14. bool distinct;
  15. Expr where;
  16. Column groupBy;
  17. Expr having;
  18. Column orderBy;
  19. bool desc;
  20. int limit;
  21. int offset;
  22. public:
  23. Select(Column columns):
  24. select(columns), distinct(false),
  25. desc(false), limit(0),
  26. offset(0)
  27. {
  28. }
  29. Select<Table>& Distinct()
  30. {
  31. distinct = true;
  32. return *this;
  33. }
  34. Select<Table>& Where(Expr expr)
  35. {
  36. where = expr;
  37. return *this;
  38. }
  39. Select<Table>& GroupBy(Column columns)
  40. {
  41. groupBy = columns;
  42. return *this;
  43. }
  44. Select<Table>& Having(Expr expr)
  45. {
  46. having = expr;
  47. return *this;
  48. }
  49. Select<Table>& OrderBy(Column columns)
  50. {
  51. orderBy = columns;
  52. return *this;
  53. }
  54. Select<Table>& Desc()
  55. {
  56. desc = true;
  57. return *this;
  58. }
  59. Select<Table>& Limit(int value)
  60. {
  61. limit = value;
  62. return *this;
  63. }
  64. Select<Table>& Offset(int value)
  65. {
  66. offset = value;
  67. return *this;
  68. }
  69. std::string ToString() const
  70. {
  71. // TODO: 加入异常处理机制
  72. std::string sql = "select ";
  73. if (!select.Empty())
  74. {
  75. sql += select.ToString();
  76. }
  77. if (distinct)
  78. {
  79. sql += " distinct";
  80. }
  81. sql += " from " + Table::descriptor()->full_name();
  82. if (!where.Empty())
  83. {
  84. sql += " where " + where.ToString();
  85. }
  86. if (!groupBy.Empty())
  87. {
  88. sql += " group by " + groupBy.ToString();
  89. if (!having.Empty())
  90. {
  91. sql += " having " + having.ToString();
  92. }
  93. if (!orderBy.Empty())
  94. {
  95. sql += " order by " + orderBy.ToString();
  96. }
  97. if (desc)
  98. {
  99. sql += " desc ";
  100. }
  101. }
  102. if (limit)
  103. {
  104. sql += " limit " + boost::lexical_cast<std::string>(limit);
  105. }
  106. if (offset)
  107. {
  108. sql += " offset " + boost::lexical_cast<std::string>(offset);
  109. }
  110. return sql;
  111. }
  112. };
  113. } // namespace Egametang
  114. #endif // ORM_QUERY_H