QueryInterface.php 13 KB

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