Select.h 1.9 KB

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