PageRenderTime 69ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/fuel/category_tool/fuel/packages/orm/classes/query.php

https://github.com/connvoi/dev
PHP | 1202 lines | 727 code | 162 blank | 313 comment | 65 complexity | b72788dc59f9472aa693bac9b8e40636 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. <?php
  2. /**
  3. * Fuel is a fast, lightweight, community driven PHP5 framework.
  4. *
  5. * @package Fuel
  6. * @version 1.0
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2012 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Orm;
  13. class Query
  14. {
  15. public static function forge($model, $connection = null, $options = array())
  16. {
  17. return new static($model, $connection, $options);
  18. }
  19. /**
  20. * @var string classname of the model
  21. */
  22. protected $model;
  23. /**
  24. * @var null|string connection name to use
  25. */
  26. protected $connection;
  27. /**
  28. * @var array database view to use with keys 'view' and 'columns'
  29. */
  30. protected $view;
  31. /**
  32. * @var string table alias
  33. */
  34. protected $alias = 't0';
  35. /**
  36. * @var array relations to join on
  37. */
  38. protected $relations = array();
  39. /**
  40. * @var array tables to join without returning any info
  41. */
  42. protected $joins = array();
  43. /**
  44. * @var array fields to select
  45. */
  46. protected $select = array();
  47. /**
  48. * @var int max number of returned base model instances
  49. */
  50. protected $limit;
  51. /**
  52. * @var int offset of base model table
  53. */
  54. protected $offset;
  55. /**
  56. * @var int max number of requested rows
  57. */
  58. protected $rows_limit;
  59. /**
  60. * @var int offset of requested rows
  61. */
  62. protected $rows_offset;
  63. /**
  64. * @var array where conditions
  65. */
  66. protected $where = array();
  67. /**
  68. * @var array order by clauses
  69. */
  70. protected $order_by = array();
  71. /**
  72. * @var array values for insert or update
  73. */
  74. protected $values = array();
  75. protected function __construct($model, $connection, $options, $table_alias = null)
  76. {
  77. $this->model = $model;
  78. $this->connection = $connection;
  79. foreach ($options as $opt => $val)
  80. {
  81. switch ($opt)
  82. {
  83. case 'select':
  84. $val = (array) $val;
  85. call_user_func_array(array($this, 'select'), $val);
  86. break;
  87. case 'related':
  88. $val = (array) $val;
  89. $this->related($val);
  90. break;
  91. case 'use_view':
  92. $this->use_view($val);
  93. break;
  94. case 'where':
  95. $this->_parse_where_array($val);
  96. break;
  97. case 'order_by':
  98. $val = (array) $val;
  99. $this->order_by($val);
  100. break;
  101. case 'limit':
  102. $this->limit($val);
  103. break;
  104. case 'offset':
  105. $this->offset($val);
  106. break;
  107. case 'rows_limit':
  108. $this->rows_limit($val);
  109. break;
  110. case 'rows_offset':
  111. $this->rows_offset($val);
  112. break;
  113. }
  114. }
  115. }
  116. /**
  117. * Select which properties are included, each as its own param. Or don't give input to retrieve
  118. * the current selection.
  119. *
  120. * @return void|array
  121. */
  122. public function select()
  123. {
  124. $fields = func_get_args();
  125. if (empty($fields))
  126. {
  127. if (empty($this->select))
  128. {
  129. $fields = array_keys(call_user_func($this->model.'::properties'));
  130. if (empty($fields))
  131. {
  132. throw new \FuelException('No properties found in model.');
  133. }
  134. foreach ($fields as $field)
  135. {
  136. $this->select($field);
  137. }
  138. if ($this->view)
  139. {
  140. foreach ($this->view['columns'] as $field)
  141. {
  142. $this->select($field);
  143. }
  144. }
  145. }
  146. // backup select before adding PKs
  147. $select = $this->select;
  148. // ensure all PKs are being selected
  149. $pks = call_user_func($this->model.'::primary_key');
  150. foreach($pks as $pk)
  151. {
  152. if ( ! in_array($this->alias.'.'.$pk, $this->select))
  153. {
  154. $this->select($pk);
  155. }
  156. }
  157. // convert selection array for DB class
  158. $out = array();
  159. foreach($this->select as $k => $v)
  160. {
  161. $out[] = array($v, $k);
  162. }
  163. // set select back to before the PKs were added
  164. $this->select = $select;
  165. return $out;
  166. }
  167. $i = count($this->select);
  168. foreach ($fields as $val)
  169. {
  170. $this->select[$this->alias.'_c'.$i++] = (strpos($val, '.') === false ? $this->alias.'.' : '').$val;
  171. }
  172. return $this;
  173. }
  174. /**
  175. * Set a view to use instead of the table
  176. *
  177. * @param string
  178. * @return Query
  179. */
  180. public function use_view($view)
  181. {
  182. $views = call_user_func(array($this->model, 'views'));
  183. if ( ! array_key_exists($view, $views))
  184. {
  185. throw new \OutOfBoundsException('Cannot use undefined database view, must be defined with Model.');
  186. }
  187. $this->view = $views[$view];
  188. $this->view['_name'] = $view;
  189. return $this;
  190. }
  191. /**
  192. * Set the limit
  193. *
  194. * @param int
  195. * @return Query
  196. */
  197. public function limit($limit)
  198. {
  199. $this->limit = intval($limit);
  200. return $this;
  201. }
  202. /**
  203. * Set the offset
  204. *
  205. * @param int
  206. * @return Query
  207. */
  208. public function offset($offset)
  209. {
  210. $this->offset = intval($offset);
  211. return $this;
  212. }
  213. /**
  214. * Set the limit of rows requested
  215. *
  216. * @param int
  217. * @return Query
  218. */
  219. public function rows_limit($limit)
  220. {
  221. $this->rows_limit = intval($limit);
  222. return $this;
  223. }
  224. /**
  225. * Set the offset of rows requested
  226. *
  227. * @param int
  228. * @return Query
  229. */
  230. public function rows_offset($offset)
  231. {
  232. $this->rows_offset = intval($offset);
  233. return $this;
  234. }
  235. /**
  236. * Set where condition
  237. *
  238. * @param string property
  239. * @param string comparison type (can be omitted)
  240. * @param string comparison value
  241. * @return Query
  242. */
  243. public function where()
  244. {
  245. $condition = func_get_args();
  246. is_array(reset($condition)) and $condition = reset($condition);
  247. return $this->_where($condition);
  248. }
  249. /**
  250. * Set or_where condition
  251. *
  252. * @param string property
  253. * @param string comparison type (can be omitted)
  254. * @param string comparison value
  255. * @return Query
  256. */
  257. public function or_where()
  258. {
  259. $condition = func_get_args();
  260. is_array(reset($condition)) and $condition = reset($condition);
  261. return $this->_where($condition, 'or_where');
  262. }
  263. /**
  264. * Does the work for where() and or_where()
  265. *
  266. * @param array
  267. * @param string
  268. * @return Query
  269. */
  270. public function _where($condition, $type = 'and_where')
  271. {
  272. if (is_array(reset($condition)) or is_string(key($condition)))
  273. {
  274. foreach ($condition as $k_c => $v_c)
  275. {
  276. is_string($k_c) and $v_c = array($k_c, $v_c);
  277. $this->_where($v_c, $type);
  278. }
  279. return $this;
  280. }
  281. // prefix table alias when not yet prefixed and not a DB expression object
  282. if (strpos($condition[0], '.') === false and ! $condition[0] instanceof \Fuel\Core\Database_Expression)
  283. {
  284. $condition[0] = $this->alias.'.'.$condition[0];
  285. }
  286. if (count($condition) == 2)
  287. {
  288. $this->where[] = array($type, array($condition[0], '=', $condition[1]));
  289. }
  290. elseif (count($condition) == 3)
  291. {
  292. $this->where[] = array($type, $condition);
  293. }
  294. else
  295. {
  296. throw new \FuelException('Invalid param count for where condition.');
  297. }
  298. return $this;
  299. }
  300. /**
  301. * Open a nested and_where condition
  302. *
  303. * @return Query
  304. */
  305. public function and_where_open()
  306. {
  307. $this->where[] = array('and_where_open', array());
  308. return $this;
  309. }
  310. /**
  311. * Close a nested and_where condition
  312. *
  313. * @return Query
  314. */
  315. public function and_where_close()
  316. {
  317. $this->where[] = array('and_where_close', array());
  318. return $this;
  319. }
  320. /**
  321. * Alias to and_where_open()
  322. *
  323. * @return Query
  324. */
  325. public function where_open()
  326. {
  327. $this->where[] = array('and_where_open', array());
  328. return $this;
  329. }
  330. /**
  331. * Alias to and_where_close()
  332. *
  333. * @return Query
  334. */
  335. public function where_close()
  336. {
  337. $this->where[] = array('and_where_close', array());
  338. return $this;
  339. }
  340. /**
  341. * Open a nested or_where condition
  342. *
  343. * @return Query
  344. */
  345. public function or_where_open()
  346. {
  347. $this->where[] = array('or_where_open', array());
  348. return $this;
  349. }
  350. /**
  351. * Close a nested or_where condition
  352. *
  353. * @return Query
  354. */
  355. public function or_where_close()
  356. {
  357. $this->where[] = array('or_where_close', array());
  358. return $this;
  359. }
  360. /**
  361. * Parses an array of where conditions into the query
  362. *
  363. * @param array $val
  364. * @param string $base
  365. * @param bool $or
  366. */
  367. protected function _parse_where_array(array $val, $base = '', $or = false)
  368. {
  369. $or and $this->or_where_open();
  370. foreach ($val as $k_w => $v_w)
  371. {
  372. if (is_array($v_w) and ! empty($v_w[0]) and is_string($v_w[0]))
  373. {
  374. ! $v_w[0] instanceof \Database_Expression and strpos($v_w[0], '.') === false and $v_w[0] = $base.$v_w[0];
  375. call_user_func_array(array($this, ($k_w === 'or' ? 'or_' : '').'where'), $v_w);
  376. }
  377. elseif (is_int($k_w) or $k_w == 'or')
  378. {
  379. $k_w === 'or' ? $this->or_where_open() : $this->where_open();
  380. $this->_parse_where_array($v_w, $base, $k_w === 'or');
  381. $k_w === 'or' ? $this->or_where_close() : $this->where_close();
  382. }
  383. else
  384. {
  385. ! $k_w instanceof \Database_Expression and strpos($k_w, '.') === false and $k_w = $base.$k_w;
  386. $this->where($k_w, $v_w);
  387. }
  388. }
  389. $or and $this->or_where_close();
  390. }
  391. /**
  392. * Set the order_by
  393. *
  394. * @param string|array
  395. * @param string|null
  396. * @return Query
  397. */
  398. public function order_by($property, $direction = 'ASC')
  399. {
  400. if (is_array($property))
  401. {
  402. foreach ($property as $p => $d)
  403. {
  404. if (is_int($p))
  405. {
  406. is_array($d) ? $this->order_by($d[0], $d[1]) : $this->order_by($d, $direction);
  407. }
  408. else
  409. {
  410. $this->order_by($p, $d);
  411. }
  412. }
  413. return $this;
  414. }
  415. // prefix table alias when not yet prefixed and not a DB expression object
  416. if ( ! $property instanceof \Fuel\Core\Database_Expression and strpos($property, '.') === false)
  417. {
  418. $property = $this->alias.'.'.$property;
  419. }
  420. $this->order_by[] = array($property, $direction);
  421. return $this;
  422. }
  423. /**
  424. * Set a relation to include
  425. *
  426. * @param string
  427. * @return Query
  428. */
  429. public function related($relation, $conditions = array())
  430. {
  431. if (is_array($relation))
  432. {
  433. foreach ($relation as $k_r => $v_r)
  434. {
  435. is_array($v_r) ? $this->related($k_r, $v_r) : $this->related($v_r);
  436. }
  437. return $this;
  438. }
  439. if (strpos($relation, '.'))
  440. {
  441. $rels = explode('.', $relation);
  442. $model = $this->model;
  443. foreach ($rels as $r)
  444. {
  445. $rel = call_user_func(array($model, 'relations'), $r);
  446. if (empty($rel))
  447. {
  448. throw new \UnexpectedValueException('Relation "'.$r.'" was not found in the model "'.$model.'".');
  449. }
  450. $model = $rel->model_to;
  451. }
  452. }
  453. else
  454. {
  455. $rel = call_user_func(array($this->model, 'relations'), $relation);
  456. if (empty($rel))
  457. {
  458. throw new \UnexpectedValueException('Relation "'.$relation.'" was not found in the model.');
  459. }
  460. }
  461. $this->relations[$relation] = array($rel, $conditions);
  462. if ( ! empty($conditions['related']))
  463. {
  464. $conditions['related'] = (array) $conditions['related'];
  465. foreach ($conditions['related'] as $k_r => $v_r)
  466. {
  467. is_array($v_r) ? $this->related($relation.'.'.$k_r, $v_r) : $this->related($relation.'.'.$v_r);
  468. }
  469. unset($conditions['related']);
  470. }
  471. return $this;
  472. }
  473. /**
  474. * Add a table to join, consider this a protect method only for Orm package usage
  475. *
  476. * @param array
  477. * @return Query
  478. */
  479. public function _join(array $join)
  480. {
  481. $this->joins[] = $join;
  482. return $this;
  483. }
  484. /**
  485. * Set any properties for insert or update
  486. *
  487. * @param string|array
  488. * @param mixed
  489. * @return Query
  490. */
  491. public function set($property, $value = null)
  492. {
  493. if (is_array($property))
  494. {
  495. foreach ($property as $p => $v)
  496. {
  497. $this->set($p, $v);
  498. }
  499. return $this;
  500. }
  501. $this->values[$property] = $value;
  502. return $this;
  503. }
  504. /**
  505. * Build a select, delete or update query
  506. *
  507. * @param \Fuel\Core\Database_Query_Builder_Where
  508. * @param string|select either array for select query or string update, delete, insert
  509. * @return array with keys query and relations
  510. */
  511. public function build_query(\Fuel\Core\Database_Query_Builder_Where $query, $columns = array(), $type = 'select')
  512. {
  513. // Get the limit
  514. if ( ! is_null($this->limit))
  515. {
  516. $query->limit($this->limit);
  517. }
  518. // Get the offset
  519. if ( ! is_null($this->offset))
  520. {
  521. $query->offset($this->offset);
  522. }
  523. // Get the order
  524. $order_by = $this->order_by;
  525. // create a backup for subquery
  526. $order_by_backup = $order_by;
  527. if ( ! empty($order_by))
  528. {
  529. foreach ($order_by as $key => $ob)
  530. {
  531. if ( ! $ob[0] instanceof \Fuel\Core\Database_Expression and strpos($ob[0], $this->alias.'.') === 0)
  532. {
  533. $query->order_by($type == 'select' ? $ob[0] : substr($ob[0], strlen($this->alias.'.')), $ob[1]);
  534. // order by has been updated to Database_Query_Builder_Where instance, set it to empty to avoid duplicate entries
  535. unset($order_by[$key]);
  536. }
  537. }
  538. }
  539. $where_backup = $this->where;
  540. if ( ! empty($this->where))
  541. {
  542. $open_nests = 0;
  543. foreach ($this->where as $key => $w)
  544. {
  545. list($method, $conditional) = $w;
  546. if ($type == 'select' and (empty($conditional) or $open_nests > 0))
  547. {
  548. strpos($method, '_open') and $open_nests++;
  549. strpos($method, '_close') and $open_nests--;
  550. continue;
  551. }
  552. if (empty($conditional)
  553. or strpos($conditional[0], $this->alias.'.') === 0
  554. or ($type != 'select' and $conditional[0] instanceof \Fuel\Core\Database_Expression))
  555. {
  556. if ($type != 'select' and ! empty($conditional)
  557. and ! $conditional[0] instanceof \Fuel\Core\Database_Expression)
  558. {
  559. $conditional[0] = substr($conditional[0], strlen($this->alias.'.'));
  560. }
  561. call_user_func_array(array($query, $method), $conditional);
  562. unset($this->where[$key]);
  563. }
  564. }
  565. }
  566. // If it's not a select we're done
  567. if ($type != 'select')
  568. {
  569. return array('query' => $query, 'models' => array());
  570. }
  571. $i = 1;
  572. $models = array();
  573. foreach ($this->relations as $name => $rel)
  574. {
  575. // when there's a dot it must be a nested relation
  576. if ($pos = strrpos($name, '.'))
  577. {
  578. if (empty($models[substr($name, 0, $pos)]['table'][1]))
  579. {
  580. throw new \UnexpectedValueException('Trying to get the relation of an unloaded relation, make sure you load the parent relation before any of its children.');
  581. }
  582. $alias = $models[substr($name, 0, $pos)]['table'][1];
  583. }
  584. else
  585. {
  586. $alias = $this->alias;
  587. }
  588. $models = array_merge($models, $rel[0]->join($alias, $name, $i++, $rel[1]));
  589. }
  590. if ($this->use_subquery())
  591. {
  592. // Get the columns for final select
  593. foreach ($models as $m)
  594. {
  595. foreach ($m['columns'] as $c)
  596. {
  597. $columns[] = $c;
  598. }
  599. }
  600. // make current query subquery of ultimate query
  601. $new_query = call_user_func_array('DB::select', $columns);
  602. $query = $new_query->from(array($query, $this->alias));
  603. // set order_by from backup
  604. $order_by = $order_by_backup;
  605. }
  606. else
  607. {
  608. // add additional selected columns
  609. foreach ($models as $m)
  610. {
  611. foreach ($m['columns'] as $c)
  612. {
  613. $query->select($c);
  614. }
  615. }
  616. }
  617. // join tables
  618. foreach ($this->joins as $j)
  619. {
  620. $join_query = $query->join($j['table'], $j['join_type']);
  621. foreach ($j['join_on'] as $on)
  622. {
  623. $join_query->on($on[0], $on[1], $on[2]);
  624. }
  625. }
  626. foreach ($models as $m)
  627. {
  628. if ($m['connection'] != $this->connection)
  629. {
  630. throw new \FuelException('Models cannot be related between connection.');
  631. }
  632. $join_query = $query->join($m['table'], $m['join_type']);
  633. foreach ($m['join_on'] as $on)
  634. {
  635. $join_query->on($on[0], $on[1], $on[2]);
  636. }
  637. }
  638. // Add any additional order_by and where clauses from the relations
  639. foreach ($models as $m_name => $m)
  640. {
  641. if ( ! empty($m['order_by']))
  642. {
  643. foreach ((array) $m['order_by'] as $k_ob => $v_ob)
  644. {
  645. if (is_int($k_ob))
  646. {
  647. $v_dir = is_array($v_ob) ? $v_ob[1] : 'ASC';
  648. $v_ob = is_array($v_ob) ? $v_ob[0] : $v_ob;
  649. if ( ! $v_ob instanceof \Fuel\Core\Database_Expression and strpos($v_ob, '.') === false)
  650. {
  651. $v_ob = $m_name.'.'.$v_ob;
  652. }
  653. $order_by[] = array($v_ob, 'ASC');
  654. }
  655. else
  656. {
  657. strpos($k_ob, '.') === false and $k_ob = $m_name.'.'.$k_ob;
  658. $order_by[] = array($k_ob, $v_ob);
  659. }
  660. }
  661. }
  662. if ( ! empty($m['where']))
  663. {
  664. $this->_parse_where_array($m['where'], $m_name.'.');
  665. }
  666. }
  667. // Get the order
  668. if ( ! empty($order_by))
  669. {
  670. foreach ($order_by as $ob)
  671. {
  672. if ( ! $ob[0] instanceof \Fuel\Core\Database_Expression)
  673. {
  674. // try to rewrite conditions on the relations to their table alias
  675. $dotpos = strrpos($ob[0], '.');
  676. $relation = substr($ob[0], 0, $dotpos);
  677. if ($dotpos > 0 and array_key_exists($relation, $models))
  678. {
  679. $ob[0] = $models[$relation]['table'][1].substr($ob[0], $dotpos);
  680. }
  681. }
  682. $query->order_by($ob[0], $ob[1]);
  683. }
  684. }
  685. // put omitted where conditions back
  686. if ( ! empty($this->where))
  687. {
  688. foreach ($this->where as $w)
  689. {
  690. list($method, $conditional) = $w;
  691. // try to rewrite conditions on the relations to their table alias
  692. if ( ! empty($conditional))
  693. {
  694. $dotpos = strrpos($conditional[0], '.');
  695. $relation = substr($conditional[0], 0, $dotpos);
  696. if ($dotpos > 0 and array_key_exists($relation, $models))
  697. {
  698. $conditional[0] = $models[$relation]['table'][1].substr($conditional[0], $dotpos);
  699. }
  700. }
  701. call_user_func_array(array($query, $method), $conditional);
  702. }
  703. }
  704. $this->where = $where_backup;
  705. // Set the row limit and offset, these are applied to the outer query when a subquery
  706. // is used or overwrite limit/offset when it's a normal query
  707. ! is_null($this->rows_limit) and $query->limit($this->rows_limit);
  708. ! is_null($this->rows_offset) and $query->offset($this->rows_offset);
  709. return array('query' => $query, 'models' => $models);
  710. }
  711. /**
  712. * Determines whether a subquery is needed, is the case if there was a limit/offset on a join
  713. *
  714. * @return bool
  715. */
  716. public function use_subquery()
  717. {
  718. return ( ! empty($this->relations) and ( ! empty($this->limit) or ! empty($this->offset)));
  719. }
  720. /**
  721. * Hydrate model instances with retrieved data
  722. *
  723. * @param array row from the database
  724. * @param array relations to be expected
  725. * @param array current result array (by reference)
  726. * @param string model classname to hydrate
  727. * @param array columns to use
  728. * @return Model
  729. */
  730. public function hydrate(&$row, $models, &$result, $model = null, $select = null, $primary_key = null)
  731. {
  732. // First check the PKs, if null it's an empty row
  733. $r1c1 = reset($select);
  734. $prefix = substr($r1c1[0], 0, strpos($r1c1[0], '.') + 1);
  735. $obj = array();
  736. foreach ($primary_key as $pk)
  737. {
  738. $pk_c = null;
  739. foreach ($select as $s)
  740. {
  741. $s[0] === $prefix.$pk and $pk_c = $s[1];
  742. }
  743. if (is_null($row[$pk_c]))
  744. {
  745. return false;
  746. }
  747. $obj[$pk] = $row[$pk_c];
  748. }
  749. // Check for cached object
  750. $pk = count($primary_key) == 1 ? reset($obj) : '['.implode('][', $obj).']';
  751. $obj = Model::cached_object($pk, $model);
  752. // Create the object when it wasn't found
  753. if ( ! $obj)
  754. {
  755. // Retrieve the object array from the row
  756. $obj = array();
  757. foreach ($select as $s)
  758. {
  759. $obj[substr($s[0], strpos($s[0], '.') + 1)] = $row[$s[1]];
  760. unset($row[$s[1]]);
  761. }
  762. $obj = $model::forge($obj, false, $this->view ? $this->view['_name'] : null);
  763. }
  764. // if the result to be generated is an array and the current object is not yet in there
  765. if (is_array($result) and ! array_key_exists($pk, $result))
  766. {
  767. $result[$pk] = $obj;
  768. }
  769. // if the result to be generated is a single object and empty
  770. elseif ( ! is_array($result) and empty($result))
  771. {
  772. $result = $obj;
  773. }
  774. // start fetching relationships
  775. $rel_objs = $obj->_relate();
  776. foreach ($models as $m)
  777. {
  778. // when the expected model is empty, there's nothing to be done
  779. if (empty($m['model']))
  780. {
  781. continue;
  782. }
  783. // when not yet set, create the relation result var with null or array
  784. if ( ! array_key_exists($m['rel_name'], $rel_objs))
  785. {
  786. $rel_objs[$m['rel_name']] = $m['relation']->singular ? null : array();
  787. }
  788. // when result is array or singular empty, try to fetch the new relation from the row
  789. $this->hydrate(
  790. $row,
  791. ! empty($m['models']) ? $m['models'] : array(),
  792. $rel_objs[$m['rel_name']],
  793. $m['model'],
  794. $m['columns'],
  795. $m['primary_key']
  796. );
  797. }
  798. // attach the retrieved relations to the object and update its original DB values
  799. $obj->_relate($rel_objs);
  800. $obj->_update_original_relations();
  801. return $obj;
  802. }
  803. /**
  804. * Build the query and return hydrated results
  805. *
  806. * @return array
  807. */
  808. public function get()
  809. {
  810. // Get the columns
  811. $columns = $this->select();
  812. // Start building the query
  813. $select = $columns;
  814. if ($this->use_subquery())
  815. {
  816. $select = array();
  817. foreach ($columns as $c)
  818. {
  819. $select[] = $c[0];
  820. }
  821. }
  822. $query = call_user_func_array('DB::select', $select);
  823. // Set from view/table
  824. $table = $this->view ? $this->view['view'] : call_user_func($this->model.'::table');
  825. $query->from(array($table, $this->alias));
  826. // Build the query further
  827. $tmp = $this->build_query($query, $columns);
  828. $query = $tmp['query'];
  829. $models = $tmp['models'];
  830. // Make models hierarchical
  831. foreach ($models as $name => $values)
  832. {
  833. if (strpos($name, '.'))
  834. {
  835. unset($models[$name]);
  836. $rels = explode('.', $name);
  837. $ref =& $models[array_shift($rels)];
  838. foreach ($rels as $rel)
  839. {
  840. empty($ref['models']) and $ref['models'] = array();
  841. empty($ref['models'][$rel]) and $ref['models'][$rel] = array();
  842. $ref =& $ref['models'][$rel];
  843. }
  844. $ref = $values;
  845. }
  846. }
  847. $rows = $query->execute($this->connection)->as_array();
  848. $result = array();
  849. $model = $this->model;
  850. $select = $this->select();
  851. $primary_key = $model::primary_key();
  852. foreach ($rows as $id => $row)
  853. {
  854. $this->hydrate($row, $models, $result, $model, $select, $primary_key);
  855. unset($rows[$id]);
  856. }
  857. // It's all built, now lets execute and start hydration
  858. return $result;
  859. }
  860. /**
  861. * Get the Query as it's been build up to this point and return it as an object
  862. *
  863. * @return Database_Query
  864. */
  865. public function get_query()
  866. {
  867. // Get the columns
  868. $columns = $this->select();
  869. // Start building the query
  870. $select = $columns;
  871. if ($this->use_subquery())
  872. {
  873. $select = array();
  874. foreach ($columns as $c)
  875. {
  876. $select[] = $c[0];
  877. }
  878. }
  879. $query = call_user_func_array('DB::select', $select);
  880. // Set from table
  881. $query->from(array(call_user_func($this->model.'::table'), $this->alias));
  882. // Build the query further
  883. $tmp = $this->build_query($query, $columns);
  884. return $tmp['query'];
  885. }
  886. /**
  887. * Build the query and return single object hydrated
  888. *
  889. * @return Model
  890. */
  891. public function get_one()
  892. {
  893. // get current limit and save it while fetching the first result
  894. $limit = $this->limit;
  895. $this->limit = 1;
  896. // get the result using normal find
  897. $result = $this->get();
  898. // put back the old limit
  899. $this->limit = $limit;
  900. return $result ? reset($result) : null;
  901. }
  902. /**
  903. * Count the result of a query
  904. *
  905. * @param bool false for random selected column or specific column, only works for main model currently
  906. * @return int number of rows OR false
  907. */
  908. public function count($column = null, $distinct = true)
  909. {
  910. $select = $column ?: \Arr::get(call_user_func($this->model.'::primary_key'), 0);
  911. $select = (strpos($select, '.') === false ? $this->alias.'.'.$select : $select);
  912. // Get the columns
  913. $columns = \DB::expr('COUNT('.($distinct ? 'DISTINCT ' : '').
  914. \Database_Connection::instance()->quote_identifier($select).
  915. ') AS count_result');
  916. // Remove the current select and
  917. $query = call_user_func('DB::select', $columns);
  918. // Set from table
  919. $query->from(array(call_user_func($this->model.'::table'), $this->alias));
  920. $tmp = $this->build_query($query, $columns, 'select');
  921. $query = $tmp['query'];
  922. $count = $query->execute($this->connection)->get('count_result');
  923. // Database_Result::get('count_result') returns a string | null
  924. if ($count === null)
  925. {
  926. return false;
  927. }
  928. return (int) $count;
  929. }
  930. /**
  931. * Get the maximum of a column for the current query
  932. *
  933. * @param string column
  934. * @return mixed maximum value OR false
  935. */
  936. public function max($column)
  937. {
  938. is_array($column) and $column = array_shift($column);
  939. // Get the columns
  940. $columns = \DB::expr('MAX('.
  941. \Database_Connection::instance()->quote_identifier($this->alias.'.'.$column).
  942. ') AS max_result');
  943. // Remove the current select and
  944. $query = call_user_func('DB::select', $columns);
  945. // Set from table
  946. $query->from(array(call_user_func($this->model.'::table'), $this->alias));
  947. $tmp = $this->build_query($query, $columns, 'max');
  948. $query = $tmp['query'];
  949. $max = $query->execute($this->connection)->get('max_result');
  950. // Database_Result::get('max_result') returns a string | null
  951. if ($max === null)
  952. {
  953. return false;
  954. }
  955. return $max;
  956. }
  957. /**
  958. * Get the minimum of a column for the current query
  959. *
  960. * @param string column
  961. * @return mixed minimum value OR false
  962. */
  963. public function min($column)
  964. {
  965. is_array($column) and $column = array_shift($column);
  966. // Get the columns
  967. $columns = \DB::expr('MIN('.
  968. \Database_Connection::instance()->quote_identifier($this->alias.'.'.$column).
  969. ') AS min_result');
  970. // Remove the current select and
  971. $query = call_user_func('DB::select', $columns);
  972. // Set from table
  973. $query->from(array(call_user_func($this->model.'::table'), $this->alias));
  974. $tmp = $this->build_query($query, $columns, 'min');
  975. $query = $tmp['query'];
  976. $min = $query->execute($this->connection)->get('min_result');
  977. // Database_Result::get('min_result') returns a string | null
  978. if ($min === null)
  979. {
  980. return false;
  981. }
  982. return $min;
  983. }
  984. /**
  985. * Run INSERT with the current values
  986. *
  987. * @return mixed last inserted ID or false on failure
  988. */
  989. public function insert()
  990. {
  991. $res = \DB::insert(call_user_func($this->model.'::table'), array_keys($this->values))
  992. ->values(array_values($this->values))
  993. ->execute($this->connection);
  994. // Failed to save the new record
  995. if ($res[0] === 0)
  996. {
  997. return false;
  998. }
  999. return $res[0];
  1000. }
  1001. /**
  1002. * Run UPDATE with the current values
  1003. *
  1004. * @return bool success of update operation
  1005. */
  1006. public function update()
  1007. {
  1008. // temporary disable relations
  1009. $tmp_relations = $this->relations;
  1010. $this->relations = array();
  1011. // Build query and execute update
  1012. $query = \DB::update(call_user_func($this->model.'::table'));
  1013. $tmp = $this->build_query($query, array(), 'update');
  1014. $query = $tmp['query'];
  1015. $res = $query->set($this->values)->execute($this->connection);
  1016. // put back any relations settings
  1017. $this->relations = $tmp_relations;
  1018. // Update can affect 0 rows when input types are different but outcome stays the same
  1019. return $res >= 0;
  1020. }
  1021. /**
  1022. * Run DELETE with the current values
  1023. *
  1024. * @return bool success of delete operation
  1025. */
  1026. public function delete()
  1027. {
  1028. // temporary disable relations
  1029. $tmp_relations = $this->relations;
  1030. $this->relations = array();
  1031. // Build query and execute update
  1032. $query = \DB::delete(call_user_func($this->model.'::table'));
  1033. $tmp = $this->build_query($query, array(), 'delete');
  1034. $query = $tmp['query'];
  1035. $res = $query->execute($this->connection);
  1036. // put back any relations settings
  1037. $this->relations = $tmp_relations;
  1038. return $res > 0;
  1039. }
  1040. }