StatementDecorator.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Statement;
  16. use Cake\Database\StatementInterface;
  17. use Cake\Database\TypeConverterTrait;
  18. use Countable;
  19. use IteratorAggregate;
  20. /**
  21. * Represents a database statement. Statements contains queries that can be
  22. * executed multiple times by binding different values on each call. This class
  23. * also helps convert values to their valid representation for the corresponding
  24. * types.
  25. *
  26. * This class is but a decorator of an actual statement implementation, such as
  27. * PDOStatement.
  28. *
  29. * @property-read string $queryString
  30. */
  31. class StatementDecorator implements StatementInterface, Countable, IteratorAggregate
  32. {
  33. use TypeConverterTrait;
  34. /**
  35. * Statement instance implementation, such as PDOStatement
  36. * or any other custom implementation.
  37. *
  38. * @var \Cake\Database\StatementInterface|\PDOStatement|null
  39. */
  40. protected $_statement;
  41. /**
  42. * Reference to the driver object associated to this statement.
  43. *
  44. * @var \Cake\Database\Driver|null
  45. */
  46. protected $_driver;
  47. /**
  48. * Whether or not this statement has already been executed
  49. *
  50. * @var bool
  51. */
  52. protected $_hasExecuted = false;
  53. /**
  54. * Constructor
  55. *
  56. * @param \Cake\Database\StatementInterface|\PDOStatement|null $statement Statement implementation such as PDOStatement
  57. * @param \Cake\Database\Driver|null $driver Driver instance
  58. */
  59. public function __construct($statement = null, $driver = null)
  60. {
  61. $this->_statement = $statement;
  62. $this->_driver = $driver;
  63. }
  64. /**
  65. * Magic getter to return $queryString as read-only.
  66. *
  67. * @param string $property internal property to get
  68. * @return mixed
  69. */
  70. public function __get($property)
  71. {
  72. if ($property === 'queryString') {
  73. return $this->_statement->queryString;
  74. }
  75. }
  76. /**
  77. * Assign a value to a positional or named variable in prepared query. If using
  78. * positional variables you need to start with index one, if using named params then
  79. * just use the name in any order.
  80. *
  81. * It is not allowed to combine positional and named variables in the same statement.
  82. *
  83. * ### Examples:
  84. *
  85. * ```
  86. * $statement->bindValue(1, 'a title');
  87. * $statement->bindValue('active', true, 'boolean');
  88. * $statement->bindValue(5, new \DateTime(), 'date');
  89. * ```
  90. *
  91. * @param string|int $column name or param position to be bound
  92. * @param mixed $value The value to bind to variable in query
  93. * @param string $type name of configured Type class
  94. * @return void
  95. */
  96. public function bindValue($column, $value, $type = 'string')
  97. {
  98. $this->_statement->bindValue($column, $value, $type);
  99. }
  100. /**
  101. * Closes a cursor in the database, freeing up any resources and memory
  102. * allocated to it. In most cases you don't need to call this method, as it is
  103. * automatically called after fetching all results from the result set.
  104. *
  105. * @return void
  106. */
  107. public function closeCursor()
  108. {
  109. $this->_statement->closeCursor();
  110. }
  111. /**
  112. * Returns the number of columns this statement's results will contain.
  113. *
  114. * ### Example:
  115. *
  116. * ```
  117. * $statement = $connection->prepare('SELECT id, title from articles');
  118. * $statement->execute();
  119. * echo $statement->columnCount(); // outputs 2
  120. * ```
  121. *
  122. * @return int
  123. */
  124. public function columnCount()
  125. {
  126. return $this->_statement->columnCount();
  127. }
  128. /**
  129. * Returns the error code for the last error that occurred when executing this statement.
  130. *
  131. * @return int|string
  132. */
  133. public function errorCode()
  134. {
  135. return $this->_statement->errorCode();
  136. }
  137. /**
  138. * Returns the error information for the last error that occurred when executing
  139. * this statement.
  140. *
  141. * @return array
  142. */
  143. public function errorInfo()
  144. {
  145. return $this->_statement->errorInfo();
  146. }
  147. /**
  148. * Executes the statement by sending the SQL query to the database. It can optionally
  149. * take an array or arguments to be bound to the query variables. Please note
  150. * that binding parameters from this method will not perform any custom type conversion
  151. * as it would normally happen when calling `bindValue`.
  152. *
  153. * @param array|null $params list of values to be bound to query
  154. * @return bool true on success, false otherwise
  155. */
  156. public function execute($params = null)
  157. {
  158. $this->_hasExecuted = true;
  159. return $this->_statement->execute($params);
  160. }
  161. /**
  162. * Returns the next row for the result set after executing this statement.
  163. * Rows can be fetched to contain columns as names or positions. If no
  164. * rows are left in result set, this method will return false.
  165. *
  166. * ### Example:
  167. *
  168. * ```
  169. * $statement = $connection->prepare('SELECT id, title from articles');
  170. * $statement->execute();
  171. * print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
  172. * ```
  173. *
  174. * @param string $type 'num' for positional columns, assoc for named columns
  175. * @return array|false Result array containing columns and values or false if no results
  176. * are left
  177. */
  178. public function fetch($type = 'num')
  179. {
  180. return $this->_statement->fetch($type);
  181. }
  182. /**
  183. * Returns an array with all rows resulting from executing this statement.
  184. *
  185. * ### Example:
  186. *
  187. * ```
  188. * $statement = $connection->prepare('SELECT id, title from articles');
  189. * $statement->execute();
  190. * print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
  191. * ```
  192. *
  193. * @param string $type num for fetching columns as positional keys or assoc for column names as keys
  194. * @return array List of all results from database for this statement
  195. */
  196. public function fetchAll($type = 'num')
  197. {
  198. return $this->_statement->fetchAll($type);
  199. }
  200. /**
  201. * Returns the number of rows affected by this SQL statement.
  202. *
  203. * ### Example:
  204. *
  205. * ```
  206. * $statement = $connection->prepare('SELECT id, title from articles');
  207. * $statement->execute();
  208. * print_r($statement->rowCount()); // will show 1
  209. * ```
  210. *
  211. * @return int
  212. */
  213. public function rowCount()
  214. {
  215. return $this->_statement->rowCount();
  216. }
  217. /**
  218. * Statements are iterable as arrays, this method will return
  219. * the iterator object for traversing all items in the result.
  220. *
  221. * ### Example:
  222. *
  223. * ```
  224. * $statement = $connection->prepare('SELECT id, title from articles');
  225. * foreach ($statement as $row) {
  226. * //do stuff
  227. * }
  228. * ```
  229. *
  230. * @return \Cake\Database\StatementInterface|\PDOStatement
  231. */
  232. public function getIterator()
  233. {
  234. if (!$this->_hasExecuted) {
  235. $this->execute();
  236. }
  237. return $this->_statement;
  238. }
  239. /**
  240. * Statements can be passed as argument for count() to return the number
  241. * for affected rows from last execution.
  242. *
  243. * @return int
  244. */
  245. public function count()
  246. {
  247. return $this->rowCount();
  248. }
  249. /**
  250. * Binds a set of values to statement object with corresponding type.
  251. *
  252. * @param array $params list of values to be bound
  253. * @param array $types list of types to be used, keys should match those in $params
  254. * @return void
  255. */
  256. public function bind($params, $types)
  257. {
  258. if (empty($params)) {
  259. return;
  260. }
  261. $anonymousParams = is_int(key($params)) ? true : false;
  262. $offset = 1;
  263. foreach ($params as $index => $value) {
  264. $type = null;
  265. if (isset($types[$index])) {
  266. $type = $types[$index];
  267. }
  268. if ($anonymousParams) {
  269. $index += $offset;
  270. }
  271. $this->bindValue($index, $value, $type);
  272. }
  273. }
  274. /**
  275. * Returns the latest primary inserted using this statement.
  276. *
  277. * @param string|null $table table name or sequence to get last insert value from
  278. * @param string|null $column the name of the column representing the primary key
  279. * @return string
  280. */
  281. public function lastInsertId($table = null, $column = null)
  282. {
  283. $row = null;
  284. if ($column && $this->columnCount()) {
  285. $row = $this->fetch('assoc');
  286. }
  287. if (isset($row[$column])) {
  288. return $row[$column];
  289. }
  290. return $this->_driver->lastInsertId($table, $column);
  291. }
  292. /**
  293. * Returns the statement object that was decorated by this class.
  294. *
  295. * @return \Cake\Database\StatementInterface|\PDOStatement
  296. */
  297. public function getInnerStatement()
  298. {
  299. return $this->_statement;
  300. }
  301. }