query.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <?php namespace System\DB;
  2. use System\Str;
  3. use System\Config;
  4. class Query {
  5. /**
  6. * The database connection.
  7. *
  8. * @var Connection
  9. */
  10. public $connection;
  11. /**
  12. * The SELECT clause.
  13. *
  14. * @var string
  15. */
  16. public $select;
  17. /**
  18. * Indicates if the query should return distinct results.
  19. *
  20. * @var bool
  21. */
  22. public $distinct = false;
  23. /**
  24. * The FROM clause.
  25. *
  26. * @var string
  27. */
  28. public $from;
  29. /**
  30. * The table name.
  31. *
  32. * @var string
  33. */
  34. public $table;
  35. /**
  36. * The WHERE clause.
  37. *
  38. * @var string
  39. */
  40. public $where = 'WHERE 1 = 1';
  41. /**
  42. * The ORDER BY columns.
  43. *
  44. * @var array
  45. */
  46. public $orderings = array();
  47. /**
  48. * The LIMIT value.
  49. *
  50. * @var int
  51. */
  52. public $limit;
  53. /**
  54. * The OFFSET value.
  55. *
  56. * @var int
  57. */
  58. public $offset;
  59. /**
  60. * The query value bindings.
  61. *
  62. * @var array
  63. */
  64. public $bindings = array();
  65. /**
  66. * Create a new query instance.
  67. *
  68. * @param string $table
  69. * @param Connection $connection
  70. * @return void
  71. */
  72. public function __construct($table, $connection)
  73. {
  74. $this->connection = $connection;
  75. $this->table = $table;
  76. $this->from = 'FROM '.$this->wrap($table);
  77. }
  78. /**
  79. * Create a new query instance.
  80. *
  81. * @param string $table
  82. * @param Connection $connection
  83. * @return Query
  84. */
  85. public static function table($table, $connection)
  86. {
  87. return new static($table, $connection);
  88. }
  89. /**
  90. * Force the query to return distinct results.
  91. *
  92. * @return Query
  93. */
  94. public function distinct()
  95. {
  96. $this->distinct = true;
  97. return $this;
  98. }
  99. /**
  100. * Add columns to the SELECT clause.
  101. *
  102. * @param array $columns
  103. * @return Query
  104. */
  105. public function select($columns = array('*'))
  106. {
  107. $this->select = ($this->distinct) ? 'SELECT DISTINCT ' : 'SELECT ';
  108. foreach ($columns as $column)
  109. {
  110. $wrapped[] = $this->wrap($column);
  111. }
  112. $this->select .= implode(', ', $wrapped);
  113. return $this;
  114. }
  115. /**
  116. * Set the FROM clause.
  117. *
  118. * @param string $from
  119. * @return Query
  120. */
  121. public function from($from)
  122. {
  123. $this->from = $from;
  124. return $this;
  125. }
  126. /**
  127. * Add a join to the query.
  128. *
  129. * @param string $table
  130. * @param string $column1
  131. * @param string $operator
  132. * @param string $column2
  133. * @param string $type
  134. * @return Query
  135. */
  136. public function join($table, $column1, $operator, $column2, $type = 'INNER')
  137. {
  138. $this->from .= ' '.$type.' JOIN '.$this->wrap($table).' ON '.$this->wrap($column1).' '.$operator.' '.$this->wrap($column2);
  139. return $this;
  140. }
  141. /**
  142. * Add a left join to the query.
  143. *
  144. * @param string $table
  145. * @param string $column1
  146. * @param string $operator
  147. * @param string $column2
  148. * @return Query
  149. */
  150. public function left_join($table, $column1, $operator, $column2)
  151. {
  152. return $this->join($table, $column1, $operator, $column2, 'LEFT');
  153. }
  154. /**
  155. * Reset the where clause to its initial state.
  156. *
  157. * @return void
  158. */
  159. public function reset_where()
  160. {
  161. $this->where = 'WHERE 1 = 1';
  162. $this->bindings = array();
  163. }
  164. /**
  165. * Add a raw where condition to the query.
  166. *
  167. * @param string $where
  168. * @param array $bindings
  169. * @param string $connector
  170. * @return Query
  171. */
  172. public function raw_where($where, $bindings = array(), $connector = 'AND')
  173. {
  174. $this->where .= ' '.$connector.' '.$where;
  175. $this->bindings = array_merge($this->bindings, $bindings);
  176. return $this;
  177. }
  178. /**
  179. * Add a raw or where condition to the query.
  180. *
  181. * @param string $where
  182. * @param array $bindings
  183. * @return Query
  184. */
  185. public function raw_or_where($where, $bindings = array())
  186. {
  187. return $this->raw_where($where, $bindings, 'OR');
  188. }
  189. /**
  190. * Add a where condition to the query.
  191. *
  192. * @param string $column
  193. * @param string $operator
  194. * @param mixed $value
  195. * @param string $connector
  196. * @return Query
  197. */
  198. public function where($column, $operator, $value, $connector = 'AND')
  199. {
  200. $this->where .= ' '.$connector.' '.$this->wrap($column).' '.$operator.' ?';
  201. $this->bindings[] = $value;
  202. return $this;
  203. }
  204. /**
  205. * Add an or where condition to the query.
  206. *
  207. * @param string $column
  208. * @param string $operator
  209. * @param mixed $value
  210. * @return Query
  211. */
  212. public function or_where($column, $operator, $value)
  213. {
  214. return $this->where($column, $operator, $value, 'OR');
  215. }
  216. /**
  217. * Add a where in condition to the query.
  218. *
  219. * @param string $column
  220. * @param array $values
  221. * @param string $connector
  222. * @return Query
  223. */
  224. public function where_in($column, $values, $connector = 'AND')
  225. {
  226. $this->where .= ' '.$connector.' '.$this->wrap($column).' IN ('.$this->parameterize($values).')';
  227. $this->bindings = array_merge($this->bindings, $values);
  228. return $this;
  229. }
  230. /**
  231. * Add an or where in condition to the query.
  232. *
  233. * @param string $column
  234. * @param array $values
  235. * @return Query
  236. */
  237. public function or_where_in($column, $values)
  238. {
  239. return $this->where_in($column, $values, 'OR');
  240. }
  241. /**
  242. * Add a where not in condition to the query.
  243. *
  244. * @param string $column
  245. * @param array $values
  246. * @param string $connector
  247. * @return Query
  248. */
  249. public function where_not_in($column, $values, $connector = 'AND')
  250. {
  251. $this->where .= ' '.$connector.' '.$this->wrap($column).' NOT IN ('.$this->parameterize($values).')';
  252. $this->bindings = array_merge($this->bindings, $values);
  253. return $this;
  254. }
  255. /**
  256. * Add an or where not in condition to the query.
  257. *
  258. * @param string $column
  259. * @param array $values
  260. * @return Query
  261. */
  262. public function or_where_not_in($column, $values)
  263. {
  264. return $this->where_not_in($column, $values, 'OR');
  265. }
  266. /**
  267. * Add a where null condition to the query.
  268. *
  269. * @param string $column
  270. * @param string $connector
  271. * @return Query
  272. */
  273. public function where_null($column, $connector = 'AND')
  274. {
  275. $this->where .= ' '.$connector.' '.$this->wrap($column).' IS NULL';
  276. return $this;
  277. }
  278. /**
  279. * Add an or where null condition to the query.
  280. *
  281. * @param string $column
  282. * @return Query
  283. */
  284. public function or_where_null($column)
  285. {
  286. return $this->where_null($column, 'OR');
  287. }
  288. /**
  289. * Add a where not null condition to the query.
  290. *
  291. * @param string $column
  292. * @param string $connector
  293. * @return Query
  294. */
  295. public function where_not_null($column, $connector = 'AND')
  296. {
  297. $this->where .= ' '.$connector.' '.$this->wrap($column).' IS NOT NULL';
  298. return $this;
  299. }
  300. /**
  301. * Add an or where not null condition to the query.
  302. *
  303. * @param string $column
  304. * @return Query
  305. */
  306. public function or_where_not_null($column)
  307. {
  308. return $this->where_not_null($column, 'OR');
  309. }
  310. /**
  311. * Add dynamic where conditions to the query.
  312. *
  313. * @param string $method
  314. * @param array $parameters
  315. * @return Query
  316. */
  317. private function dynamic_where($method, $parameters)
  318. {
  319. // Strip the "where_" off of the method.
  320. $finder = substr($method, 6);
  321. // Split the column names from the connectors.
  322. $segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
  323. // The connector variable will determine which connector will be used for the condition.
  324. // We'll change it as we come across new connectors in the dynamic method string.
  325. //
  326. // The index variable helps us get the correct parameter value for the where condition.
  327. // We increment it each time we add a condition.
  328. $connector = 'AND';
  329. $index = 0;
  330. foreach ($segments as $segment)
  331. {
  332. if ($segment != '_and_' and $segment != '_or_')
  333. {
  334. $this->where($segment, '=', $parameters[$index], $connector);
  335. $index++;
  336. }
  337. else
  338. {
  339. $connector = trim(strtoupper($segment), '_');
  340. }
  341. }
  342. return $this;
  343. }
  344. /**
  345. * Add an ordering to the query.
  346. *
  347. * @param string $column
  348. * @param string $direction
  349. * @return Query
  350. */
  351. public function order_by($column, $direction)
  352. {
  353. $this->orderings[] = $this->wrap($column).' '.strtoupper($direction);
  354. return $this;
  355. }
  356. /**
  357. * Set the query offset.
  358. *
  359. * @param int $value
  360. * @return Query
  361. */
  362. public function skip($value)
  363. {
  364. $this->offset = $value;
  365. return $this;
  366. }
  367. /**
  368. * Set the query limit.
  369. *
  370. * @param int $value
  371. * @return Query
  372. */
  373. public function take($value)
  374. {
  375. $this->limit = $value;
  376. return $this;
  377. }
  378. /**
  379. * Set the limit and offset values for a given page.
  380. *
  381. * @param int $page
  382. * @param int $per_page
  383. * @return Query
  384. */
  385. public function for_page($page, $per_page)
  386. {
  387. return $this->skip(($page - 1) * $per_page)->take($per_page);
  388. }
  389. /**
  390. * Find a record by the primary key.
  391. *
  392. * @param int $id
  393. * @param array $columns
  394. * @return object
  395. */
  396. public function find($id, $columns = array('*'))
  397. {
  398. return $this->where('id', '=', $id)->first($columns);
  399. }
  400. /**
  401. * Get an aggregate value.
  402. *
  403. * @param string $aggregate
  404. * @param string $column
  405. * @return mixed
  406. */
  407. private function aggregate($aggregator, $column)
  408. {
  409. $this->select = 'SELECT '.$aggregator.'('.$this->wrap($column).') AS '.$this->wrap('aggregate');
  410. return $this->first()->aggregate;
  411. }
  412. /**
  413. * Get paginated query results.
  414. *
  415. * @param int $per_page
  416. * @param array $columns
  417. * @return Paginator
  418. */
  419. public function paginate($per_page, $columns = array('*'))
  420. {
  421. list($select, $total) = array($this->select, $this->count());
  422. // Every query clears the SELECT clause, so we store the contents of the clause
  423. // before executing the count query and then put the contents back in afterwards.
  424. if ( ! is_null($select))
  425. {
  426. $this->select = $select;
  427. }
  428. else
  429. {
  430. $this->select($columns);
  431. }
  432. $current_page = \System\Paginator::page($total, $per_page);
  433. return \System\Paginator::make($this->for_page($current_page, $per_page)->get(), $total, $per_page);
  434. }
  435. /**
  436. * Execute the query as a SELECT statement and return the first result.
  437. *
  438. * @param array $columns
  439. * @return object
  440. */
  441. public function first($columns = array('*'))
  442. {
  443. return (count($results = $this->take(1)->get($columns)) > 0) ? $results[0] : null;
  444. }
  445. /**
  446. * Execute the query as a SELECT statement.
  447. *
  448. * @param array $columns
  449. * @return array
  450. */
  451. public function get($columns = array('*'))
  452. {
  453. if (is_null($this->select))
  454. {
  455. $this->select($columns);
  456. }
  457. $sql = $this->select.' '.$this->from.' '.$this->where;
  458. if (count($this->orderings) > 0)
  459. {
  460. $sql .= ' ORDER BY '.implode(', ', $this->orderings);
  461. }
  462. if ( ! is_null($this->limit))
  463. {
  464. $sql .= ' LIMIT '.$this->limit;
  465. }
  466. if ( ! is_null($this->offset))
  467. {
  468. $sql .= ' OFFSET '.$this->offset;
  469. }
  470. $results = $this->connection->query($sql, $this->bindings);
  471. // Reset the SELECT clause so more queries can be performed using the same instance.
  472. // This is helpful for getting aggregates and then getting actual results.
  473. $this->select = null;
  474. return $results;
  475. }
  476. /**
  477. * Execute an INSERT statement.
  478. *
  479. * @param array $values
  480. * @return bool
  481. */
  482. public function insert($values)
  483. {
  484. return $this->connection->query($this->compile_insert($values), array_values($values));
  485. }
  486. /**
  487. * Execute an INSERT statement and get the insert ID.
  488. *
  489. * @param array $values
  490. * @return int
  491. */
  492. public function insert_get_id($values)
  493. {
  494. $sql = $this->compile_insert($values);
  495. // Use the RETURNING clause on Postgres instead of the PDO lastInsertID method.
  496. // The PDO method is a little cumbersome using Postgres.
  497. if ($this->connection->driver() == 'pgsql')
  498. {
  499. $query = $this->connection->pdo->prepare($sql.' RETURNING '.$this->wrap('id'));
  500. $query->execute(array_values($values));
  501. return $query->fetch(\PDO::FETCH_CLASS, 'stdClass')->id;
  502. }
  503. $this->connection->query($sql, array_values($values));
  504. return $this->connection->pdo->lastInsertId();
  505. }
  506. /**
  507. * Compile an SQL INSERT statement.
  508. *
  509. * @param array $values
  510. * @return string
  511. */
  512. private function compile_insert($values)
  513. {
  514. $sql = 'INSERT INTO '.$this->wrap($this->table);
  515. foreach (array_keys($values) as $column)
  516. {
  517. $columns[] = $this->wrap($column);
  518. }
  519. return $sql .= ' ('.implode(', ', $columns).') VALUES ('.$this->parameterize($values).')';
  520. }
  521. /**
  522. * Execute the query as an UPDATE statement.
  523. *
  524. * @param array $values
  525. * @return bool
  526. */
  527. public function update($values)
  528. {
  529. $sql = 'UPDATE '.$this->wrap($this->table).' SET ';
  530. foreach (array_keys($values) as $column)
  531. {
  532. $sets[] = $this->wrap($column).' = ?';
  533. }
  534. $sql .= implode(', ', $sets).' '.$this->where;
  535. return $this->connection->query($sql, array_merge(array_values($values), $this->bindings));
  536. }
  537. /**
  538. * Execute the query as a DELETE statement.
  539. *
  540. * @param int $id
  541. * @return bool
  542. */
  543. public function delete($id = null)
  544. {
  545. if ( ! is_null($id))
  546. {
  547. $this->where('id', '=', $id);
  548. }
  549. return $this->connection->query('DELETE FROM '.$this->wrap($this->table).' '.$this->where, $this->bindings);
  550. }
  551. /**
  552. * Wrap a value in keyword identifiers.
  553. *
  554. * @param string $value
  555. * @return string
  556. */
  557. private function wrap($value)
  558. {
  559. if (strpos(strtolower($value), ' as ') !== false)
  560. {
  561. return $this->wrap_alias($value, $connection);
  562. }
  563. $wrap = $this->connection->wrapper();
  564. return implode('.', array_map(function($segment) use ($wrap) { return ($segment != '*') ? $wrap.$segment.$wrap : $segment; }, explode('.', $value)));
  565. }
  566. /**
  567. * Wrap an alias in keyword identifiers.
  568. *
  569. * @param string $value
  570. * @return string
  571. */
  572. private function wrap_alias($value)
  573. {
  574. $segments = explode(' ', $value);
  575. return $this->wrap($segments[0]).' AS '.$this->wrap($segments[2]);
  576. }
  577. /**
  578. * Create query parameters from an array of values.
  579. *
  580. * @param array $values
  581. * @return string
  582. */
  583. private function parameterize($values)
  584. {
  585. return implode(', ', array_fill(0, count($values), '?'));
  586. }
  587. /**
  588. * Magic Method for handling dynamic functions.
  589. */
  590. public function __call($method, $parameters)
  591. {
  592. if (strpos($method, 'where_') === 0)
  593. {
  594. return $this->dynamic_where($method, $parameters, $this);
  595. }
  596. if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
  597. {
  598. return ($method == 'count') ? $this->aggregate(strtoupper($method), '*') : $this->aggregate(strtoupper($method), $parameters[0]);
  599. }
  600. throw new \Exception("Method [$method] is not defined on the Query class.");
  601. }
  602. }