QueryInterface.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.1
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Datasource;
  16. /**
  17. * The basis for every query object
  18. *
  19. * @method $this andWhere($conditions, $types = [])
  20. * @method $this select($fields = [], $overwrite = false)
  21. * @method \Cake\Datasource\RepositoryInterface getRepository()
  22. */
  23. interface QueryInterface
  24. {
  25. /**
  26. * @var string
  27. */
  28. const JOIN_TYPE_INNER = 'INNER';
  29. /**
  30. * @var string
  31. */
  32. const JOIN_TYPE_LEFT = 'LEFT';
  33. /**
  34. * @var string
  35. */
  36. const JOIN_TYPE_RIGHT = 'RIGHT';
  37. /**
  38. * Returns a key => value array representing a single aliased field
  39. * that can be passed directly to the select() method.
  40. * The key will contain the alias and the value the actual field name.
  41. *
  42. * If the field is already aliased, then it will not be changed.
  43. * If no $alias is passed, the default table for this query will be used.
  44. *
  45. * @param string $field The field to alias
  46. * @param string|null $alias the alias used to prefix the field
  47. * @return string
  48. */
  49. public function aliasField($field, $alias = null);
  50. /**
  51. * Runs `aliasField()` for each field in the provided list and returns
  52. * the result under a single array.
  53. *
  54. * @param array $fields The fields to alias
  55. * @param string|null $defaultAlias The default alias
  56. * @return string[]
  57. */
  58. public function aliasFields($fields, $defaultAlias = null);
  59. /**
  60. * Fetch the results for this query.
  61. *
  62. * Will return either the results set through setResult(), or execute this query
  63. * and return the ResultSetDecorator object ready for streaming of results.
  64. *
  65. * ResultSetDecorator is a traversable object that implements the methods found
  66. * on Cake\Collection\Collection.
  67. *
  68. * @return \Cake\Datasource\ResultSetInterface
  69. */
  70. public function all();
  71. /**
  72. * Populates or adds parts to current query clauses using an array.
  73. * This is handy for passing all query clauses at once. The option array accepts:
  74. *
  75. * - fields: Maps to the select method
  76. * - conditions: Maps to the where method
  77. * - limit: Maps to the limit method
  78. * - order: Maps to the order method
  79. * - offset: Maps to the offset method
  80. * - group: Maps to the group method
  81. * - having: Maps to the having method
  82. * - contain: Maps to the contain options for eager loading
  83. * - join: Maps to the join method
  84. * - page: Maps to the page method
  85. *
  86. * ### Example:
  87. *
  88. * ```
  89. * $query->applyOptions([
  90. * 'fields' => ['id', 'name'],
  91. * 'conditions' => [
  92. * 'created >=' => '2013-01-01'
  93. * ],
  94. * 'limit' => 10
  95. * ]);
  96. * ```
  97. *
  98. * Is equivalent to:
  99. *
  100. * ```
  101. * $query
  102. * ->select(['id', 'name'])
  103. * ->where(['created >=' => '2013-01-01'])
  104. * ->limit(10)
  105. * ```
  106. *
  107. * @param array $options list of query clauses to apply new parts to.
  108. * @return $this
  109. */
  110. public function applyOptions(array $options);
  111. /**
  112. * Apply custom finds to against an existing query object.
  113. *
  114. * Allows custom find methods to be combined and applied to each other.
  115. *
  116. * ```
  117. * $repository->find('all')->find('recent');
  118. * ```
  119. *
  120. * The above is an example of stacking multiple finder methods onto
  121. * a single query.
  122. *
  123. * @param string $finder The finder method to use.
  124. * @param array $options The options for the finder.
  125. * @return $this Returns a modified query.
  126. */
  127. public function find($finder, array $options = []);
  128. /**
  129. * Returns the first result out of executing this query, if the query has not been
  130. * executed before, it will set the limit clause to 1 for performance reasons.
  131. *
  132. * ### Example:
  133. *
  134. * ```
  135. * $singleUser = $query->select(['id', 'username'])->first();
  136. * ```
  137. *
  138. * @return mixed the first result from the ResultSet
  139. */
  140. public function first();
  141. /**
  142. * Returns the total amount of results for the query.
  143. *
  144. * @return int
  145. */
  146. public function count();
  147. /**
  148. * Sets the number of records that should be retrieved from database,
  149. * accepts an integer or an expression object that evaluates to an integer.
  150. * In some databases, this operation might not be supported or will require
  151. * the query to be transformed in order to limit the result set size.
  152. *
  153. * ### Examples
  154. *
  155. * ```
  156. * $query->limit(10) // generates LIMIT 10
  157. * $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
  158. * ```
  159. *
  160. * @param int $num number of records to be returned
  161. * @return $this
  162. */
  163. public function limit($num);
  164. /**
  165. * Sets the number of records that should be skipped from the original result set
  166. * This is commonly used for paginating large results. Accepts an integer or an
  167. * expression object that evaluates to an integer.
  168. *
  169. * In some databases, this operation might not be supported or will require
  170. * the query to be transformed in order to limit the result set size.
  171. *
  172. * ### Examples
  173. *
  174. * ```
  175. * $query->offset(10) // generates OFFSET 10
  176. * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  177. * ```
  178. *
  179. * @param int $num number of records to be skipped
  180. * @return $this
  181. */
  182. public function offset($num);
  183. /**
  184. * Adds a single or multiple fields to be used in the ORDER clause for this query.
  185. * Fields can be passed as an array of strings, array of expression
  186. * objects, a single expression or a single string.
  187. *
  188. * If an array is passed, keys will be used as the field itself and the value will
  189. * represent the order in which such field should be ordered. When called multiple
  190. * times with the same fields as key, the last order definition will prevail over
  191. * the others.
  192. *
  193. * By default this function will append any passed argument to the list of fields
  194. * to be selected, unless the second argument is set to true.
  195. *
  196. * ### Examples:
  197. *
  198. * ```
  199. * $query->order(['title' => 'DESC', 'author_id' => 'ASC']);
  200. * ```
  201. *
  202. * Produces:
  203. *
  204. * `ORDER BY title DESC, author_id ASC`
  205. *
  206. * ```
  207. * $query
  208. * ->order(['title' => $query->newExpr('DESC NULLS FIRST')])
  209. * ->order('author_id');
  210. * ```
  211. *
  212. * Will generate:
  213. *
  214. * `ORDER BY title DESC NULLS FIRST, author_id`
  215. *
  216. * ```
  217. * $expression = $query->newExpr()->add(['id % 2 = 0']);
  218. * $query->order($expression)->order(['title' => 'ASC']);
  219. * ```
  220. *
  221. * Will become:
  222. *
  223. * `ORDER BY (id %2 = 0), title ASC`
  224. *
  225. * If you need to set complex expressions as order conditions, you
  226. * should use `orderAsc()` or `orderDesc()`.
  227. *
  228. * @param array|string $fields fields to be added to the list
  229. * @param bool $overwrite whether to reset order with field list or not
  230. * @return $this
  231. */
  232. public function order($fields, $overwrite = false);
  233. /**
  234. * Set the page of results you want.
  235. *
  236. * This method provides an easier to use interface to set the limit + offset
  237. * in the record set you want as results. If empty the limit will default to
  238. * the existing limit clause, and if that too is empty, then `25` will be used.
  239. *
  240. * Pages must start at 1.
  241. *
  242. * @param int $num The page number you want.
  243. * @param int|null $limit The number of rows you want in the page. If null
  244. * the current limit clause will be used.
  245. * @return $this
  246. * @throws \InvalidArgumentException If page number < 1.
  247. */
  248. public function page($num, $limit = null);
  249. /**
  250. * Returns an array representation of the results after executing the query.
  251. *
  252. * @return array
  253. */
  254. public function toArray();
  255. /**
  256. * Returns the default repository object that will be used by this query,
  257. * that is, the repository that will appear in the from clause.
  258. *
  259. * @param \Cake\Datasource\RepositoryInterface|null $repository The default repository object to use
  260. * @return \Cake\Datasource\RepositoryInterface|$this
  261. */
  262. public function repository(RepositoryInterface $repository = null);
  263. /**
  264. * Adds a condition or set of conditions to be used in the WHERE clause for this
  265. * query. Conditions can be expressed as an array of fields as keys with
  266. * comparison operators in it, the values for the array will be used for comparing
  267. * the field to such literal. Finally, conditions can be expressed as a single
  268. * string or an array of strings.
  269. *
  270. * When using arrays, each entry will be joined to the rest of the conditions using
  271. * an AND operator. Consecutive calls to this function will also join the new
  272. * conditions specified using the AND operator. Additionally, values can be
  273. * expressed using expression objects which can include other query objects.
  274. *
  275. * Any conditions created with this methods can be used with any SELECT, UPDATE
  276. * and DELETE type of queries.
  277. *
  278. * ### Conditions using operators:
  279. *
  280. * ```
  281. * $query->where([
  282. * 'posted >=' => new DateTime('3 days ago'),
  283. * 'title LIKE' => 'Hello W%',
  284. * 'author_id' => 1,
  285. * ], ['posted' => 'datetime']);
  286. * ```
  287. *
  288. * The previous example produces:
  289. *
  290. * `WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1`
  291. *
  292. * Second parameter is used to specify what type is expected for each passed
  293. * key. Valid types can be used from the mapped with Database\Type class.
  294. *
  295. * ### Nesting conditions with conjunctions:
  296. *
  297. * ```
  298. * $query->where([
  299. * 'author_id !=' => 1,
  300. * 'OR' => ['published' => true, 'posted <' => new DateTime('now')],
  301. * 'NOT' => ['title' => 'Hello']
  302. * ], ['published' => boolean, 'posted' => 'datetime']
  303. * ```
  304. *
  305. * The previous example produces:
  306. *
  307. * `WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')`
  308. *
  309. * You can nest conditions using conjunctions as much as you like. Sometimes, you
  310. * may want to define 2 different options for the same key, in that case, you can
  311. * wrap each condition inside a new array:
  312. *
  313. * `$query->where(['OR' => [['published' => false], ['published' => true]])`
  314. *
  315. * Keep in mind that every time you call where() with the third param set to false
  316. * (default), it will join the passed conditions to the previous stored list using
  317. * the AND operator. Also, using the same array key twice in consecutive calls to
  318. * this method will not override the previous value.
  319. *
  320. * ### Using expressions objects:
  321. *
  322. * ```
  323. * $exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->tieWith('OR');
  324. * $query->where(['published' => true], ['published' => 'boolean'])->where($exp);
  325. * ```
  326. *
  327. * The previous example produces:
  328. *
  329. * `WHERE (id != 100 OR author_id != 1) AND published = 1`
  330. *
  331. * Other Query objects that be used as conditions for any field.
  332. *
  333. * ### Adding conditions in multiple steps:
  334. *
  335. * You can use callable functions to construct complex expressions, functions
  336. * receive as first argument a new QueryExpression object and this query instance
  337. * as second argument. Functions must return an expression object, that will be
  338. * added the list of conditions for the query using the AND operator.
  339. *
  340. * ```
  341. * $query
  342. * ->where(['title !=' => 'Hello World'])
  343. * ->where(function ($exp, $query) {
  344. * $or = $exp->or(['id' => 1]);
  345. * $and = $exp->and(['id >' => 2, 'id <' => 10]);
  346. * return $or->add($and);
  347. * });
  348. * ```
  349. *
  350. * * The previous example produces:
  351. *
  352. * `WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))`
  353. *
  354. * ### Conditions as strings:
  355. *
  356. * ```
  357. * $query->where(['articles.author_id = authors.id', 'modified IS NULL']);
  358. * ```
  359. *
  360. * The previous example produces:
  361. *
  362. * `WHERE articles.author_id = authors.id AND modified IS NULL`
  363. *
  364. * Please note that when using the array notation or the expression objects, all
  365. * values will be correctly quoted and transformed to the correspondent database
  366. * data type automatically for you, thus securing your application from SQL injections.
  367. * If you use string conditions make sure that your values are correctly quoted.
  368. * The safest thing you can do is to never use string conditions.
  369. *
  370. * @param string|array|callable|null $conditions The conditions to filter on.
  371. * @param array $types associative array of type names used to bind values to query
  372. * @param bool $overwrite whether to reset conditions with passed list or not
  373. * @return $this
  374. */
  375. public function where($conditions = null, $types = [], $overwrite = false);
  376. }