QueryInterface.php 14 KB

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