You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

267 lines
8.5 KiB

11 years ago
  1. <?php namespace Majestic\Model;
  2. class SqlCriteria
  3. {
  4. const JOIN_TYPE_DEFAULT = 100;
  5. const JOIN_TYPE_LEFT = 101;
  6. const JOIN_TYPE_RIGHT = 102;
  7. const JOIN_TYPE_INNER = 103;
  8. const JOIN_TYPE_OUTER = 104;
  9. private static $join_reserved_keyword = array(
  10. self::JOIN_TYPE_DEFAULT => 'JOIN',
  11. self::JOIN_TYPE_LEFT => 'LEFT JOIN',
  12. self::JOIN_TYPE_RIGHT => 'RIGHT JOIN',
  13. self::JOIN_TYPE_INNER => 'INNER JOIN',
  14. self::JOIN_TYPE_OUTER => 'OUTER JOIN',
  15. );
  16. private $select = array();
  17. private $distinct = '';
  18. private $where = array();
  19. private $group_by = array();
  20. private $order = array('sort' => array(), 'order' => array());
  21. private $limit = '';
  22. /**
  23. * @var SqlModel
  24. */
  25. private $model;
  26. private $sql_expression;
  27. private $sql_expression_params = array();
  28. private $sql_join_expressions = array();
  29. private $join_table_placeholder = array();
  30. /**
  31. * @param $model SqlModel
  32. * @param $sql_expression string|null Sql expression with SELECT and FROM operators. If fetched, then SqlCriteria::select(), SqlCriteria::distinct() disabled for use.
  33. * @param $sql_expression_params array additional params to be replaced in sql expression
  34. */
  35. public function __construct($model, $sql_expression = null, $sql_expression_params = array())
  36. {
  37. $this->model = $model;
  38. $this->sql_expression = $sql_expression;
  39. $this->sql_expression_params = $sql_expression_params;
  40. }
  41. /**
  42. * @return SqlResultProvider
  43. */
  44. public function find()
  45. {
  46. $this->defineJoinExpressions();
  47. return $this->model->find($this->select, $this->distinct, $this->where, $this->order, $this->limit, null, $this->group_by, $this->sql_expression, $this->sql_expression_params);
  48. }
  49. private function defineJoinExpressions($select = null)
  50. {
  51. if ($this->sql_join_expressions) {
  52. if (!$this->sql_expression) {
  53. $select = $this->model->getDb()->selectExpr($select ? : $this->select, $this->distinct);
  54. $this->sql_expression = 'SELECT ' . $select . ' FROM :table';
  55. }
  56. $this->sql_expression .= ' ' . implode(' ', $this->sql_join_expressions);
  57. $this->sql_join_expressions = null;
  58. }
  59. }
  60. public function delete()
  61. {
  62. return $this->model->find('', '', $this->where, null, null, null, null, 'DELETE FROM :table', $this->sql_expression_params)->affectedRows();
  63. }
  64. //TODO: перенести определение sql_expression в модель
  65. public function count($select = null)
  66. {
  67. $this->defineJoinExpressions($select);
  68. $sql_expression_backup = $this->sql_expression;
  69. $select_parent_query = 'COUNT(*) as count';
  70. if (!$this->sql_expression) {
  71. $this->sql_expression = 'SELECT COUNT(' . ($select ? $select : '*') . ') as count FROM :table';
  72. $select_parent_query = 'x.count';
  73. }
  74. $count = $this->model->count($select_parent_query, $this->where, null, $this->group_by, $this->sql_expression, $this->sql_expression_params)->fetchField('count');
  75. $this->sql_expression = $sql_expression_backup;
  76. return $count;
  77. }
  78. private function defineJoinTablePlaceholder($table_name)
  79. {
  80. if (!isset($this->join_table_placeholder[$table_name])) {
  81. $this->join_table_placeholder[$table_name] = ':table' . (count($this->join_table_placeholder) + 1);
  82. }
  83. }
  84. public function getTablePh($table_name)
  85. {
  86. $this->defineJoinTablePlaceholder($table_name);
  87. return $this->join_table_placeholder[$table_name];
  88. }
  89. public function join($join_table_name, $join_field_name, $donor_table_name = null, $donor_field_name = null, $join_type = self::JOIN_TYPE_DEFAULT)
  90. {
  91. $donor_field_name = $donor_field_name ? : $join_field_name;
  92. $donor_table_placeholder = $donor_table_name ? $this->getTablePh($donor_table_name) : ':table';
  93. $join_table_placeholder = $this->getTablePh($join_table_name);
  94. $this->sql_join_expressions[] = self::$join_reserved_keyword[$join_type]
  95. . ' ' . $join_table_placeholder
  96. . ' ON ' . $donor_table_placeholder . '.' . $donor_field_name . '='
  97. . ' ' . $join_table_placeholder . '.' . $join_field_name;
  98. if ($donor_table_name) {
  99. $this->sql_expression_params[substr($donor_table_placeholder, 1)] = new DbExpr($this->model->identify($donor_table_name));
  100. }
  101. $this->sql_expression_params[substr($join_table_placeholder, 1)] = new DbExpr($this->model->identify($join_table_name));
  102. return $this;
  103. }
  104. /**
  105. * @param $cond string|array Condition with "?" placeholder @ex 'field=?' or 'field=1' or array('field=?' => 1', 'field=1')
  106. * @param $value string|array|DbExpr|null Value. Array transformed to DbExpr(implode(',' Array)) All elements in the array mast be integer
  107. * @return SqlCriteria
  108. * @desc Allow multiple calls
  109. */
  110. public function where($cond, $value = null)
  111. {
  112. if (is_null($value)) {
  113. if (is_array($cond)) {
  114. $this->where = $this->where + $cond;
  115. } else {
  116. $this->where[] = $cond;
  117. }
  118. } else {
  119. $this->where[$cond] = $value;
  120. }
  121. return $this;
  122. }
  123. public function whereJoin($join_table_name, $cond, $value = null)
  124. {
  125. $join_table_placeholder = $this->getTablePh($join_table_name);
  126. if (is_array($cond)) {
  127. $cond_replace = array();
  128. foreach ($cond as $key => $value) {
  129. $cond_replace[$this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $key)] = $value;
  130. }
  131. } else {
  132. $cond = $this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $cond);
  133. }
  134. return $this->where($cond, $value);
  135. }
  136. private function getCondWithTablePlaceholderIfNeed($table_placeholder, $cond)
  137. {
  138. if (!strstr('.', $cond)) {
  139. $cond = $table_placeholder . '.' . $cond;
  140. }
  141. return $cond;
  142. }
  143. /**
  144. * @param $field string
  145. * @param $value array
  146. * @return SqlCriteria
  147. */
  148. public function whereIn($field, $value)
  149. {
  150. return $this->where($field . ' in ?', $value);
  151. }
  152. /**
  153. * @param $field string
  154. * @param $value array
  155. * @return SqlCriteria
  156. */
  157. public function whereNotIn($field, $value)
  158. {
  159. return $this->where($field . ' not in ?', $value);
  160. }
  161. /**
  162. * @param $field string
  163. * @param $value array
  164. * @return SqlCriteria
  165. * @deprecated
  166. */
  167. public function whereNot($field, $value)
  168. {
  169. return $this->whereNotIn($field, $value);
  170. }
  171. public function groupBy($fields)
  172. {
  173. if (is_array($fields)) {
  174. $this->group_by = $this->group_by + $fields;
  175. } else {
  176. $this->group_by[] = $fields;
  177. }
  178. return $this;
  179. }
  180. /**
  181. * @param $field string Field @ex 'field'
  182. * @param $order_desc bool Descendant sort direction
  183. * @return SqlCriteria
  184. * @desc Allow multiple calls
  185. */
  186. public function order($field, $order_desc = false)
  187. {
  188. $this->order['sort'][] = $field;
  189. if ($order_desc) {
  190. $this->order['order'][$field] = 'desc';
  191. }
  192. return $this;
  193. }
  194. /**
  195. * @param $offset int
  196. * @param $limit int
  197. * @return SqlCriteria
  198. */
  199. public function limit($offset = 0, $limit)
  200. {
  201. if ($offset) {
  202. $this->limit = (int) $offset . ',';
  203. }
  204. $this->limit .= (int) $limit;
  205. return $this;
  206. }
  207. /**
  208. * @param string|array $fields
  209. * @param bool $convert_to_db_expression
  210. * @ex SqlCriteria::select('field')
  211. * @ex SqlCriteria->select(array('field1', 'field2'))
  212. * @ex SqlCriteria->select('field1,field2')
  213. * @return SqlCriteria
  214. */
  215. public function select($fields, $convert_to_db_expression = false)
  216. {
  217. if (!is_array($fields)) {
  218. $fields = explode(',', $fields);
  219. }
  220. $fields = array_map(function($item){return trim($item);},$fields);
  221. if ($convert_to_db_expression) {
  222. $fields = array_map(function($item){return new DbExpr($item);},$fields);
  223. }
  224. $this->select = array_merge($this->select,$fields);
  225. return $this;
  226. }
  227. /**
  228. * @param $field string|bool If true then distinct by *
  229. * @return SqlCriteria
  230. */
  231. public function distinct($field)
  232. {
  233. $this->distinct = $field;
  234. return $this;
  235. }
  236. }