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.

269 lines
8.7 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. } else {
  74. $this->sql_expression = preg_replace('#SELECT.+FROM#', 'SELECT COUNT(' . ($select ? $select : '*') . ') as count FROM', $this->sql_expression);
  75. }
  76. $count = $this->model->count($select_parent_query, $this->where, null, $this->group_by, $this->sql_expression, $this->sql_expression_params)->fetchField('count');
  77. $this->sql_expression = $sql_expression_backup;
  78. return $count;
  79. }
  80. private function defineJoinTablePlaceholder($table_name)
  81. {
  82. if (!isset($this->join_table_placeholder[$table_name])) {
  83. $this->join_table_placeholder[$table_name] = ':table' . (count($this->join_table_placeholder) + 1);
  84. }
  85. }
  86. public function getTablePh($table_name)
  87. {
  88. $this->defineJoinTablePlaceholder($table_name);
  89. return $this->join_table_placeholder[$table_name];
  90. }
  91. public function join($join_table_name, $join_field_name, $donor_table_name = null, $donor_field_name = null, $join_type = self::JOIN_TYPE_DEFAULT)
  92. {
  93. $donor_field_name = $donor_field_name ? : $join_field_name;
  94. $donor_table_placeholder = $donor_table_name ? $this->getTablePh($donor_table_name) : ':table';
  95. $join_table_placeholder = $this->getTablePh($join_table_name);
  96. $this->sql_join_expressions[] = self::$join_reserved_keyword[$join_type]
  97. . ' ' . $join_table_placeholder
  98. . ' ON ' . $donor_table_placeholder . '.' . $donor_field_name . '='
  99. . ' ' . $join_table_placeholder . '.' . $join_field_name;
  100. if ($donor_table_name) {
  101. $this->sql_expression_params[substr($donor_table_placeholder, 1)] = new DbExpr($this->model->identify($donor_table_name));
  102. }
  103. $this->sql_expression_params[substr($join_table_placeholder, 1)] = new DbExpr($this->model->identify($join_table_name));
  104. return $this;
  105. }
  106. /**
  107. * @param $cond string|array Condition with "?" placeholder @ex 'field=?' or 'field=1' or array('field=?' => 1', 'field=1')
  108. * @param $value string|array|DbExpr|null Value. Array transformed to DbExpr(implode(',' Array)) All elements in the array mast be integer
  109. * @return SqlCriteria
  110. * @desc Allow multiple calls
  111. */
  112. public function where($cond, $value = null)
  113. {
  114. if (is_null($value)) {
  115. if (is_array($cond)) {
  116. $this->where = $this->where + $cond;
  117. } else {
  118. $this->where[] = $cond;
  119. }
  120. } else {
  121. $this->where[$cond] = $value;
  122. }
  123. return $this;
  124. }
  125. public function whereJoin($join_table_name, $cond, $value = null)
  126. {
  127. $join_table_placeholder = $this->getTablePh($join_table_name);
  128. if (is_array($cond)) {
  129. $cond_replace = array();
  130. foreach ($cond as $key => $value) {
  131. $cond_replace[$this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $key)] = $value;
  132. }
  133. } else {
  134. $cond = $this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $cond);
  135. }
  136. return $this->where($cond, $value);
  137. }
  138. private function getCondWithTablePlaceholderIfNeed($table_placeholder, $cond)
  139. {
  140. if (!strstr('.', $cond)) {
  141. $cond = $table_placeholder . '.' . $cond;
  142. }
  143. return $cond;
  144. }
  145. /**
  146. * @param $field string
  147. * @param $value array
  148. * @return SqlCriteria
  149. */
  150. public function whereIn($field, $value)
  151. {
  152. return $this->where($field . ' in ?', $value);
  153. }
  154. /**
  155. * @param $field string
  156. * @param $value array
  157. * @return SqlCriteria
  158. */
  159. public function whereNotIn($field, $value)
  160. {
  161. return $this->where($field . ' not in ?', $value);
  162. }
  163. /**
  164. * @param $field string
  165. * @param $value array
  166. * @return SqlCriteria
  167. * @deprecated
  168. */
  169. public function whereNot($field, $value)
  170. {
  171. return $this->whereNotIn($field, $value);
  172. }
  173. public function groupBy($fields)
  174. {
  175. if (is_array($fields)) {
  176. $this->group_by = $this->group_by + $fields;
  177. } else {
  178. $this->group_by[] = $fields;
  179. }
  180. return $this;
  181. }
  182. /**
  183. * @param $field string Field @ex 'field'
  184. * @param $order_desc bool Descendant sort direction
  185. * @return SqlCriteria
  186. * @desc Allow multiple calls
  187. */
  188. public function order($field, $order_desc = false)
  189. {
  190. $this->order['sort'][] = $field;
  191. if ($order_desc) {
  192. $this->order['order'][$field] = 'desc';
  193. }
  194. return $this;
  195. }
  196. /**
  197. * @param $offset int
  198. * @param $limit int
  199. * @return SqlCriteria
  200. */
  201. public function limit($offset = 0, $limit)
  202. {
  203. if ($offset) {
  204. $this->limit = (int) $offset . ',';
  205. }
  206. $this->limit .= (int) $limit;
  207. return $this;
  208. }
  209. /**
  210. * @param string|array $fields
  211. * @param bool $convert_to_db_expression
  212. * @ex SqlCriteria::select('field')
  213. * @ex SqlCriteria->select(array('field1', 'field2'))
  214. * @ex SqlCriteria->select('field1,field2')
  215. * @return SqlCriteria
  216. */
  217. public function select($fields, $convert_to_db_expression = false)
  218. {
  219. if (!is_array($fields)) {
  220. $fields = explode(',', $fields);
  221. }
  222. $fields = array_map(function($item){return trim($item);},$fields);
  223. if ($convert_to_db_expression) {
  224. $fields = array_map(function($item){return new DbExpr($item);},$fields);
  225. }
  226. $this->select = array_merge($this->select,$fields);
  227. return $this;
  228. }
  229. /**
  230. * @param $field string|bool If true then distinct by *
  231. * @return SqlCriteria
  232. */
  233. public function distinct($field)
  234. {
  235. $this->distinct = $field;
  236. return $this;
  237. }
  238. }