ValuesExpression.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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\Expression;
  16. use Cake\Database\Exception;
  17. use Cake\Database\ExpressionInterface;
  18. use Cake\Database\Query;
  19. use Cake\Database\TypeMapTrait;
  20. use Cake\Database\Type\ExpressionTypeCasterTrait;
  21. use Cake\Database\ValueBinder;
  22. /**
  23. * An expression object to contain values being inserted.
  24. *
  25. * Helps generate SQL with the correct number of placeholders and bind
  26. * values correctly into the statement.
  27. */
  28. class ValuesExpression implements ExpressionInterface
  29. {
  30. use ExpressionTypeCasterTrait;
  31. use TypeMapTrait;
  32. /**
  33. * Array of values to insert.
  34. *
  35. * @var array
  36. */
  37. protected $_values = [];
  38. /**
  39. * List of columns to ensure are part of the insert.
  40. *
  41. * @var array
  42. */
  43. protected $_columns = [];
  44. /**
  45. * The Query object to use as a values expression
  46. *
  47. * @var \Cake\Database\Query|null
  48. */
  49. protected $_query;
  50. /**
  51. * Whether or not values have been casted to expressions
  52. * already.
  53. *
  54. * @var bool
  55. */
  56. protected $_castedExpressions = false;
  57. /**
  58. * Constructor
  59. *
  60. * @param array $columns The list of columns that are going to be part of the values.
  61. * @param \Cake\Database\TypeMap $typeMap A dictionary of column -> type names
  62. */
  63. public function __construct(array $columns, $typeMap)
  64. {
  65. $this->_columns = $columns;
  66. $this->setTypeMap($typeMap);
  67. }
  68. /**
  69. * Add a row of data to be inserted.
  70. *
  71. * @param array|\Cake\Database\Query $data Array of data to append into the insert, or
  72. * a query for doing INSERT INTO .. SELECT style commands
  73. * @return void
  74. * @throws \Cake\Database\Exception When mixing array + Query data types.
  75. */
  76. public function add($data)
  77. {
  78. if ((count($this->_values) && $data instanceof Query) ||
  79. ($this->_query && is_array($data))
  80. ) {
  81. throw new Exception(
  82. 'You cannot mix subqueries and array data in inserts.'
  83. );
  84. }
  85. if ($data instanceof Query) {
  86. $this->setQuery($data);
  87. return;
  88. }
  89. $this->_values[] = $data;
  90. $this->_castedExpressions = false;
  91. }
  92. /**
  93. * Sets the columns to be inserted.
  94. *
  95. * @param array $cols Array with columns to be inserted.
  96. * @return $this
  97. */
  98. public function setColumns($cols)
  99. {
  100. $this->_columns = $cols;
  101. $this->_castedExpressions = false;
  102. return $this;
  103. }
  104. /**
  105. * Gets the columns to be inserted.
  106. *
  107. * @return array
  108. */
  109. public function getColumns()
  110. {
  111. return $this->_columns;
  112. }
  113. /**
  114. * Sets the columns to be inserted. If no params are passed, then it returns
  115. * the currently stored columns.
  116. *
  117. * @deprecated 3.4.0 Use setColumns()/getColumns() instead.
  118. * @param array|null $cols Array with columns to be inserted.
  119. * @return array|$this
  120. */
  121. public function columns($cols = null)
  122. {
  123. deprecationWarning(
  124. 'ValuesExpression::columns() is deprecated. ' .
  125. 'Use ValuesExpression::setColumns()/getColumns() instead.'
  126. );
  127. if ($cols !== null) {
  128. return $this->setColumns($cols);
  129. }
  130. return $this->getColumns();
  131. }
  132. /**
  133. * Get the bare column names.
  134. *
  135. * Because column names could be identifier quoted, we
  136. * need to strip the identifiers off of the columns.
  137. *
  138. * @return array
  139. */
  140. protected function _columnNames()
  141. {
  142. $columns = [];
  143. foreach ($this->_columns as $col) {
  144. if (is_string($col)) {
  145. $col = trim($col, '`[]"');
  146. }
  147. $columns[] = $col;
  148. }
  149. return $columns;
  150. }
  151. /**
  152. * Sets the values to be inserted.
  153. *
  154. * @param array $values Array with values to be inserted.
  155. * @return $this
  156. */
  157. public function setValues($values)
  158. {
  159. $this->_values = $values;
  160. $this->_castedExpressions = false;
  161. return $this;
  162. }
  163. /**
  164. * Gets the values to be inserted.
  165. *
  166. * @return array
  167. */
  168. public function getValues()
  169. {
  170. if (!$this->_castedExpressions) {
  171. $this->_processExpressions();
  172. }
  173. return $this->_values;
  174. }
  175. /**
  176. * Sets the values to be inserted. If no params are passed, then it returns
  177. * the currently stored values
  178. *
  179. * @deprecated 3.4.0 Use setValues()/getValues() instead.
  180. * @param array|null $values Array with values to be inserted.
  181. * @return array|$this
  182. */
  183. public function values($values = null)
  184. {
  185. deprecationWarning(
  186. 'ValuesExpression::values() is deprecated. ' .
  187. 'Use ValuesExpression::setValues()/getValues() instead.'
  188. );
  189. if ($values !== null) {
  190. return $this->setValues($values);
  191. }
  192. return $this->getValues();
  193. }
  194. /**
  195. * Sets the query object to be used as the values expression to be evaluated
  196. * to insert records in the table.
  197. *
  198. * @param \Cake\Database\Query $query The query to set
  199. * @return $this
  200. */
  201. public function setQuery(Query $query)
  202. {
  203. $this->_query = $query;
  204. return $this;
  205. }
  206. /**
  207. * Gets the query object to be used as the values expression to be evaluated
  208. * to insert records in the table.
  209. *
  210. * @return \Cake\Database\Query|null
  211. */
  212. public function getQuery()
  213. {
  214. return $this->_query;
  215. }
  216. /**
  217. * Sets the query object to be used as the values expression to be evaluated
  218. * to insert records in the table. If no params are passed, then it returns
  219. * the currently stored query
  220. *
  221. * @deprecated 3.4.0 Use setQuery()/getQuery() instead.
  222. * @param \Cake\Database\Query|null $query The query to set
  223. * @return \Cake\Database\Query|null|$this
  224. */
  225. public function query(Query $query = null)
  226. {
  227. deprecationWarning(
  228. 'ValuesExpression::query() is deprecated. ' .
  229. 'Use ValuesExpression::setQuery()/getQuery() instead.'
  230. );
  231. if ($query !== null) {
  232. return $this->setQuery($query);
  233. }
  234. return $this->getQuery();
  235. }
  236. /**
  237. * Convert the values into a SQL string with placeholders.
  238. *
  239. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  240. * @return string
  241. */
  242. public function sql(ValueBinder $generator)
  243. {
  244. if (empty($this->_values) && empty($this->_query)) {
  245. return '';
  246. }
  247. if (!$this->_castedExpressions) {
  248. $this->_processExpressions();
  249. }
  250. $columns = $this->_columnNames();
  251. $defaults = array_fill_keys($columns, null);
  252. $placeholders = [];
  253. $types = [];
  254. $typeMap = $this->getTypeMap();
  255. foreach ($defaults as $col => $v) {
  256. $types[$col] = $typeMap->type($col);
  257. }
  258. foreach ($this->_values as $row) {
  259. $row += $defaults;
  260. $rowPlaceholders = [];
  261. foreach ($columns as $column) {
  262. $value = $row[$column];
  263. if ($value instanceof ExpressionInterface) {
  264. $rowPlaceholders[] = '(' . $value->sql($generator) . ')';
  265. continue;
  266. }
  267. $placeholder = $generator->placeholder('c');
  268. $rowPlaceholders[] = $placeholder;
  269. $generator->bind($placeholder, $value, $types[$column]);
  270. }
  271. $placeholders[] = implode(', ', $rowPlaceholders);
  272. }
  273. if ($this->getQuery()) {
  274. return ' ' . $this->getQuery()->sql($generator);
  275. }
  276. return sprintf(' VALUES (%s)', implode('), (', $placeholders));
  277. }
  278. /**
  279. * Traverse the values expression.
  280. *
  281. * This method will also traverse any queries that are to be used in the INSERT
  282. * values.
  283. *
  284. * @param callable $visitor The visitor to traverse the expression with.
  285. * @return void
  286. */
  287. public function traverse(callable $visitor)
  288. {
  289. if ($this->_query) {
  290. return;
  291. }
  292. if (!$this->_castedExpressions) {
  293. $this->_processExpressions();
  294. }
  295. foreach ($this->_values as $v) {
  296. if ($v instanceof ExpressionInterface) {
  297. $v->traverse($visitor);
  298. }
  299. if (!is_array($v)) {
  300. continue;
  301. }
  302. foreach ($v as $column => $field) {
  303. if ($field instanceof ExpressionInterface) {
  304. $visitor($field);
  305. $field->traverse($visitor);
  306. }
  307. }
  308. }
  309. }
  310. /**
  311. * Converts values that need to be casted to expressions
  312. *
  313. * @return void
  314. */
  315. protected function _processExpressions()
  316. {
  317. $types = [];
  318. $typeMap = $this->getTypeMap();
  319. $columns = $this->_columnNames();
  320. foreach ($columns as $c) {
  321. if (!is_scalar($c)) {
  322. continue;
  323. }
  324. $types[$c] = $typeMap->type($c);
  325. }
  326. $types = $this->_requiresToExpressionCasting($types);
  327. if (empty($types)) {
  328. return;
  329. }
  330. foreach ($this->_values as $row => $values) {
  331. foreach ($types as $col => $type) {
  332. /* @var \Cake\Database\Type\ExpressionTypeInterface $type */
  333. $this->_values[$row][$col] = $type->toExpression($values[$col]);
  334. }
  335. }
  336. $this->_castedExpressions = true;
  337. }
  338. }