query.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. <?php namespace System\DB;
  2. class Query {
  3. /**
  4. * The database connection name.
  5. *
  6. * @var string
  7. */
  8. private $connection;
  9. /**
  10. * The SELECT clause.
  11. *
  12. * @var string
  13. */
  14. public $select;
  15. /**
  16. * Indicates if the query should return distinct results.
  17. *
  18. * @var bool
  19. */
  20. public $distinct = false;
  21. /**
  22. * The FROM clause.
  23. *
  24. * @var string
  25. */
  26. public $from;
  27. /**
  28. * The table name.
  29. *
  30. * @var string
  31. */
  32. public $table;
  33. /**
  34. * The WHERE clause.
  35. *
  36. * @var string
  37. */
  38. public $where = 'WHERE 1 = 1';
  39. /**
  40. * The ORDER BY columns.
  41. *
  42. * @var array
  43. */
  44. public $orderings = array();
  45. /**
  46. * The LIMIT value.
  47. *
  48. * @var int
  49. */
  50. public $limit;
  51. /**
  52. * The OFFSET value.
  53. *
  54. * @var int
  55. */
  56. public $offset;
  57. /**
  58. * The query value bindings.
  59. *
  60. * @var array
  61. */
  62. public $bindings = array();
  63. /**
  64. * Create a new query instance.
  65. *
  66. * @param string $table
  67. * @param string $connection
  68. * @return void
  69. */
  70. public function __construct($table, $connection = null)
  71. {
  72. // ---------------------------------------------------
  73. // Set the database connection name.
  74. // ---------------------------------------------------
  75. $this->connection = (is_null($connection)) ? \System\Config::get('db.default') : $connection;
  76. // ---------------------------------------------------
  77. // Build the FROM clause.
  78. // ---------------------------------------------------
  79. $this->from = 'FROM '.$this->wrap($this->table = $table);
  80. }
  81. /**
  82. * Create a new query instance.
  83. *
  84. * @param string $table
  85. * @param string $connection
  86. * @return Query
  87. */
  88. public static function table($table, $connection = null)
  89. {
  90. return new static($table, $connection);
  91. }
  92. /**
  93. * Force the query to return distinct results.
  94. *
  95. * @return Query
  96. */
  97. public function distinct()
  98. {
  99. $this->distinct = true;
  100. return $this;
  101. }
  102. /**
  103. * Add columns to the SELECT clause.
  104. *
  105. * @return Query
  106. */
  107. public function select()
  108. {
  109. // ---------------------------------------------------
  110. // Handle DISTINCT selections.
  111. // ---------------------------------------------------
  112. $this->select = ($this->distinct) ? 'SELECT DISTINCT ' : 'SELECT ';
  113. // ---------------------------------------------------
  114. // Wrap all of the columns in keyword identifiers.
  115. // ---------------------------------------------------
  116. $this->select .= implode(', ', array_map(array($this, 'wrap'), func_get_args()));
  117. return $this;
  118. }
  119. /**
  120. * Add a join to the query.
  121. *
  122. * @param string $table
  123. * @param string $column1
  124. * @param string $operator
  125. * @param string $column2
  126. * @param string $type
  127. * @return Query
  128. */
  129. public function join($table, $column1, $operator, $column2, $type = 'INNER')
  130. {
  131. $this->from .= ' '.$type.' JOIN '.$this->wrap($table).' ON '.$this->wrap($column1).' '.$operator.' '.$this->wrap($column2);
  132. return $this;
  133. }
  134. /**
  135. * Add a left join to the query.
  136. *
  137. * @param string $table
  138. * @param string $column1
  139. * @param string $operator
  140. * @param string $column2
  141. * @return Query
  142. */
  143. public function left_join($table, $column1, $operator, $column2)
  144. {
  145. return $this->join($table, $column1, $operator, $column2, 'LEFT');
  146. }
  147. /**
  148. * Add a raw where condition to the query.
  149. *
  150. * @param string $where
  151. * @param array $bindings
  152. * @param string $connector
  153. * @return Query
  154. */
  155. public function raw_where($where, $bindings = array(), $connector = 'AND')
  156. {
  157. $this->where .= ' '.$connector.' '.$where;
  158. $this->bindings = array_merge($this->bindings, $bindings);
  159. return $this;
  160. }
  161. /**
  162. * Add a raw or where condition to the query.
  163. *
  164. * @param string $where
  165. * @param array $bindings
  166. * @return Query
  167. */
  168. public function raw_or_where($where, $bindings = array())
  169. {
  170. return $this->raw_where($where, $bindings, 'OR');
  171. }
  172. /**
  173. * Add a where condition to the query.
  174. *
  175. * @param string $column
  176. * @param string $operator
  177. * @param mixed $value
  178. * @param string $connector
  179. * @return Query
  180. */
  181. public function where($column, $operator, $value, $connector = 'AND')
  182. {
  183. $this->where .= ' '.$connector.' '.$this->wrap($column).' '.$operator.' ?';
  184. $this->bindings[] = $value;
  185. return $this;
  186. }
  187. /**
  188. * Add an or where condition to the query.
  189. *
  190. * @param string $column
  191. * @param string $operator
  192. * @param mixed $value
  193. * @return Query
  194. */
  195. public function or_where($column, $operator, $value)
  196. {
  197. return $this->where($column, $operator, $value, 'OR');
  198. }
  199. /**
  200. * Add a where in condition to the query.
  201. *
  202. * @param string $column
  203. * @param array $values
  204. * @param string $connector
  205. * @return Query
  206. */
  207. public function where_in($column, $values, $connector = 'AND')
  208. {
  209. $this->where .= ' '.$connector.' '.$this->wrap($column).' IN ('.$this->parameterize($values).')';
  210. $this->bindings = array_merge($this->bindings, $values);
  211. return $this;
  212. }
  213. /**
  214. * Add an or where in condition to the query.
  215. *
  216. * @param string $column
  217. * @param array $values
  218. * @return Query
  219. */
  220. public function or_where_in($column, $values)
  221. {
  222. return $this->where_in($column, $values, 'OR');
  223. }
  224. /**
  225. * Add a where not in condition to the query.
  226. *
  227. * @param string $column
  228. * @param array $values
  229. * @param string $connector
  230. * @return Query
  231. */
  232. public function where_not_in($column, $values, $connector = 'AND')
  233. {
  234. $this->where .= ' '.$connector.' '.$this->wrap($column).' NOT IN ('.$this->parameterize($values).')';
  235. $this->bindings = array_merge($this->bindings, $values);
  236. return $this;
  237. }
  238. /**
  239. * Add an or where not in condition to the query.
  240. *
  241. * @param string $column
  242. * @param array $values
  243. * @return Query
  244. */
  245. public function or_where_not_in($column, $values)
  246. {
  247. return $this->where_not_in($column, $values, 'OR');
  248. }
  249. /**
  250. * Add a where null condition to the query.
  251. *
  252. * @param string $column
  253. * @param string $connector
  254. * @return Query
  255. */
  256. public function where_null($column, $connector = 'AND')
  257. {
  258. $this->where .= ' '.$connector.' '.$this->wrap($column).' IS NULL';
  259. return $this;
  260. }
  261. /**
  262. * Add an or where null condition to the query.
  263. *
  264. * @param string $column
  265. * @return Query
  266. */
  267. public function or_where_null($column)
  268. {
  269. return $this->where_null($column, 'OR');
  270. }
  271. /**
  272. * Add a where not null condition to the query.
  273. *
  274. * @param string $column
  275. * @param string $connector
  276. * @return Query
  277. */
  278. public function where_not_null($column, $connector = 'AND')
  279. {
  280. $this->where .= ' '.$connector.' '.$this->wrap($column).' IS NOT NULL';
  281. return $this;
  282. }
  283. /**
  284. * Add an or where not null condition to the query.
  285. *
  286. * @param string $column
  287. * @return Query
  288. */
  289. public function or_where_not_null($column)
  290. {
  291. return $this->where_not_null($column, 'OR');
  292. }
  293. /**
  294. * Add an ordering to the query.
  295. *
  296. * @param string $column
  297. * @param string $direction
  298. * @return Query
  299. */
  300. public function order_by($column, $direction)
  301. {
  302. $this->orderings[] = $this->wrap($column).' '.\System\Str::upper($direction);
  303. return $this;
  304. }
  305. /**
  306. * Set the query offset.
  307. *
  308. * @param int $value
  309. * @return Query
  310. */
  311. public function skip($value)
  312. {
  313. $this->offset = $value;
  314. return $this;
  315. }
  316. /**
  317. * Set the query limit.
  318. *
  319. * @param int $value
  320. * @return Query
  321. */
  322. public function take($value)
  323. {
  324. $this->limit = $value;
  325. return $this;
  326. }
  327. /**
  328. * Find a record by the primary key.
  329. *
  330. * @param int $id
  331. * @return object
  332. */
  333. public function find($id)
  334. {
  335. // ---------------------------------------------------
  336. // Set the primary key.
  337. // ---------------------------------------------------
  338. $this->where('id', '=', $id);
  339. // ---------------------------------------------------
  340. // Get the first result.
  341. // ---------------------------------------------------
  342. return $this->first();
  343. }
  344. /**
  345. * Execute the query as a SELECT statement and return the first result.
  346. *
  347. * @return object
  348. */
  349. public function first()
  350. {
  351. return (count($results = call_user_func_array(array($this->take(1), 'get'), func_get_args())) > 0) ? $results[0] : null;
  352. }
  353. /**
  354. * Execute the query as a SELECT statement.
  355. *
  356. * @return array
  357. */
  358. public function get()
  359. {
  360. // ---------------------------------------------------
  361. // Initialize the SELECT clause if it's null.
  362. // ---------------------------------------------------
  363. if (is_null($this->select))
  364. {
  365. call_user_func_array(array($this, 'select'), (count(func_get_args()) > 0) ? func_get_args() : array('*'));
  366. }
  367. return \System\DB::query(Query\Compiler::select($this), $this->bindings, $this->connection);
  368. }
  369. /**
  370. * Get an aggregate value.
  371. *
  372. * @param string $aggregate
  373. * @param string $column
  374. * @return mixed
  375. */
  376. private function aggregate($aggregator, $column)
  377. {
  378. // ---------------------------------------------------
  379. // Build the SELECT clause.
  380. // ---------------------------------------------------
  381. $this->select = 'SELECT '.$aggregator.'('.$this->wrap($column).') AS '.$this->wrap('aggregate');
  382. // ---------------------------------------------------
  383. // Execute the statement.
  384. // ---------------------------------------------------
  385. $results = \System\DB::query(Query\Compiler::select($this), $this->bindings);
  386. return $results[0]->aggregate;
  387. }
  388. /**
  389. * Execute an INSERT statement.
  390. *
  391. * @param array $values
  392. * @return bool
  393. */
  394. public function insert($values)
  395. {
  396. return \System\DB::query(Query\Compiler::insert($this, $values), array_values($values), $this->connection);
  397. }
  398. /**
  399. * Execute an INSERT statement and get the insert ID.
  400. *
  401. * @param array $values
  402. * @return int
  403. */
  404. public function insert_get_id($values)
  405. {
  406. // ---------------------------------------------------
  407. // Compile the SQL statement.
  408. // ---------------------------------------------------
  409. $sql = Query\Compiler::insert($this, $values);
  410. // ---------------------------------------------------
  411. // The Postgres PDO implementation does not cleanly
  412. // implement the last insert ID function. So, we'll
  413. // use the RETURNING clause available in Postgres.
  414. // ---------------------------------------------------
  415. if (\System\DB::connection($this->connection)->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'pgsql')
  416. {
  417. // ---------------------------------------------------
  418. // Add the RETURNING clause to the SQL.
  419. // ---------------------------------------------------
  420. $sql .= ' RETURNING '.$this->wrap('id');
  421. // ---------------------------------------------------
  422. // Prepare the PDO statement.
  423. // ---------------------------------------------------
  424. $query = \System\DB::connection($this->connection)->prepare($sql);
  425. // ---------------------------------------------------
  426. // Execute the PDO statement.
  427. // ---------------------------------------------------
  428. $query->execute(array_values($values));
  429. // ---------------------------------------------------
  430. // Fetch the insert ID from the results.
  431. // ---------------------------------------------------
  432. $result = $query->fetch(\PDO::FETCH_ASSOC);
  433. return $result['id'];
  434. }
  435. // ---------------------------------------------------
  436. // When using MySQL or SQLite, we can just use the PDO
  437. // last insert ID function.
  438. // ---------------------------------------------------
  439. else
  440. {
  441. // ---------------------------------------------------
  442. // Execute the statement.
  443. // ---------------------------------------------------
  444. \System\DB::query($sql, array_values($values), $this->connection);
  445. // ---------------------------------------------------
  446. // Get the last insert ID.
  447. // ---------------------------------------------------
  448. return \System\DB::connection($this->connection)->lastInsertId();
  449. }
  450. }
  451. /**
  452. * Execute the query as an UPDATE statement.
  453. *
  454. * @param array $values
  455. * @return bool
  456. */
  457. public function update($values)
  458. {
  459. return \System\DB::query(Query\Compiler::update($this, $values), array_merge(array_values($values), $this->bindings), $this->connection);
  460. }
  461. /**
  462. * Execute the query as a DELETE statement.
  463. *
  464. * @param int $id
  465. * @return bool
  466. */
  467. public function delete($id = null)
  468. {
  469. // ---------------------------------------------------
  470. // Set the primary key.
  471. // ---------------------------------------------------
  472. if ( ! is_null($id))
  473. {
  474. $this->where('id', '=', $id);
  475. }
  476. // ---------------------------------------------------
  477. // Execute the statement.
  478. // ---------------------------------------------------
  479. return \System\DB::query(Query\Compiler::delete($this), $this->bindings, $this->connection);
  480. }
  481. /**
  482. * Wrap a value in keyword identifiers.
  483. *
  484. * @param string $value
  485. * @param string $wrap
  486. * @return string
  487. */
  488. public function wrap($value, $wrap = '"')
  489. {
  490. // ---------------------------------------------------
  491. // If the application is using MySQL, we need to use
  492. // a non-standard keyword identifier.
  493. // ---------------------------------------------------
  494. if (\System\DB::connection($this->connection)->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'mysql')
  495. {
  496. $wrap = '`';
  497. }
  498. // ---------------------------------------------------
  499. // Wrap the element in keyword identifiers.
  500. // ---------------------------------------------------
  501. return implode('.', array_map(function($segment) use ($wrap) {return ($segment != '*') ? $wrap.$segment.$wrap : $segment;}, explode('.', $value)));
  502. }
  503. /**
  504. * Create query parameters from an array of values.
  505. *
  506. * @param array $values
  507. * @return string
  508. */
  509. public function parameterize($values)
  510. {
  511. return implode(', ', array_fill(0, count($values), '?'));
  512. }
  513. /**
  514. * Magic Method for handling dynamic functions.
  515. */
  516. public function __call($method, $parameters)
  517. {
  518. // ---------------------------------------------------
  519. // Handle any of the aggregate functions.
  520. // ---------------------------------------------------
  521. if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
  522. {
  523. return ($method == 'count') ? $this->aggregate(\System\Str::upper($method), '*') : $this->aggregate(\System\Str::upper($method), $parameters[0]);
  524. }
  525. else
  526. {
  527. throw new \Exception("Method [$method] is not defined on the Query class.");
  528. }
  529. }
  530. }