Select.h 2.0 KB

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