ValuesExpression.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.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 = null;
  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. if ($cols !== null) {
  124. return $this->setColumns($cols);
  125. }
  126. return $this->getColumns();
  127. }
  128. /**
  129. * Get the bare column names.
  130. *
  131. * Because column names could be identifier quoted, we
  132. * need to strip the identifiers off of the columns.
  133. *
  134. * @return array
  135. */
  136. protected function _columnNames()
  137. {
  138. $columns = [];
  139. foreach ($this->_columns as $col) {
  140. if (is_string($col)) {
  141. $col = trim($col, '`[]"');
  142. }
  143. $columns[] = $col;
  144. }
  145. return $columns;
  146. }
  147. /**
  148. * Sets the values to be inserted.
  149. *
  150. * @param array $values Array with values to be inserted.
  151. * @return $this
  152. */
  153. public function setValues($values)
  154. {
  155. $this->_values = $values;
  156. $this->_castedExpressions = false;
  157. return $this;
  158. }
  159. /**
  160. * Gets the values to be inserted.
  161. *
  162. * @return array
  163. */
  164. public function getValues()
  165. {
  166. if (!$this->_castedExpressions) {
  167. $this->_processExpressions();
  168. }
  169. return $this->_values;
  170. }
  171. /**
  172. * Sets the values to be inserted. If no params are passed, then it returns
  173. * the currently stored values
  174. *
  175. * @deprecated 3.4.0 Use setValues()/getValues() instead.
  176. * @param array|null $values Array with values to be inserted.
  177. * @return array|$this
  178. */
  179. public function values($values = null)
  180. {
  181. if ($values !== null) {
  182. return $this->setValues($values);
  183. }
  184. return $this->getValues();
  185. }
  186. /**
  187. * Sets the query object to be used as the values expression to be evaluated
  188. * to insert records in the table.
  189. *
  190. * @param \Cake\Database\Query $query The query to set
  191. * @return $this
  192. */
  193. public function setQuery(Query $query)
  194. {
  195. $this->_query = $query;
  196. return $this;
  197. }
  198. /**
  199. * Gets the query object to be used as the values expression to be evaluated
  200. * to insert records in the table.
  201. *
  202. * @return \Cake\Database\Query
  203. */
  204. public function getQuery()
  205. {
  206. return $this->_query;
  207. }
  208. /**
  209. * Sets the query object to be used as the values expression to be evaluated
  210. * to insert records in the table. If no params are passed, then it returns
  211. * the currently stored query
  212. *
  213. * @deprecated 3.4.0 Use setQuery()/getQuery() instead.
  214. * @param \Cake\Database\Query|null $query The query to set
  215. * @return \Cake\Database\Query|null|$this
  216. */
  217. public function query(Query $query = null)
  218. {
  219. if ($query !== null) {
  220. return $this->setQuery($query);
  221. }
  222. return $this->getQuery();
  223. }
  224. /**
  225. * Convert the values into a SQL string with placeholders.
  226. *
  227. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  228. * @return string
  229. */
  230. public function sql(ValueBinder $generator)
  231. {
  232. if (empty($this->_values) && empty($this->_query)) {
  233. return '';
  234. }
  235. if (!$this->_castedExpressions) {
  236. $this->_processExpressions();
  237. }
  238. $columns = $this->_columnNames();
  239. $defaults = array_fill_keys($columns, null);
  240. $placeholders = [];
  241. $types = [];
  242. $typeMap = $this->getTypeMap();
  243. foreach ($defaults as $col => $v) {
  244. $types[$col] = $typeMap->type($col);
  245. }
  246. foreach ($this->_values as $row) {
  247. $row += $defaults;
  248. $rowPlaceholders = [];
  249. foreach ($columns as $column) {
  250. $value = $row[$column];
  251. if ($value instanceof ExpressionInterface) {
  252. $rowPlaceholders[] = '(' . $value->sql($generator) . ')';
  253. continue;
  254. }
  255. $placeholder = $generator->placeholder('c');
  256. $rowPlaceholders[] = $placeholder;
  257. $generator->bind($placeholder, $value, $types[$column]);
  258. }
  259. $placeholders[] = implode(', ', $rowPlaceholders);
  260. }
  261. if ($this->getQuery()) {
  262. return ' ' . $this->getQuery()->sql($generator);
  263. }
  264. return sprintf(' VALUES (%s)', implode('), (', $placeholders));
  265. }
  266. /**
  267. * Traverse the values expression.
  268. *
  269. * This method will also traverse any queries that are to be used in the INSERT
  270. * values.
  271. *
  272. * @param callable $visitor The visitor to traverse the expression with.
  273. * @return void
  274. */
  275. public function traverse(callable $visitor)
  276. {
  277. if ($this->_query) {
  278. return;
  279. }
  280. if (!$this->_castedExpressions) {
  281. $this->_processExpressions();
  282. }
  283. foreach ($this->_values as $v) {
  284. if ($v instanceof ExpressionInterface) {
  285. $v->traverse($visitor);
  286. }
  287. if (!is_array($v)) {
  288. continue;
  289. }
  290. foreach ($v as $column => $field) {
  291. if ($field instanceof ExpressionInterface) {
  292. $visitor($field);
  293. $field->traverse($visitor);
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * Converts values that need to be casted to expressions
  300. *
  301. * @return void
  302. */
  303. protected function _processExpressions()
  304. {
  305. $types = [];
  306. $typeMap = $this->getTypeMap();
  307. $columns = $this->_columnNames();
  308. foreach ($columns as $c) {
  309. if (!is_scalar($c)) {
  310. continue;
  311. }
  312. $types[$c] = $typeMap->type($c);
  313. }
  314. $types = $this->_requiresToExpressionCasting($types);
  315. if (empty($types)) {
  316. return;
  317. }
  318. foreach ($this->_values as $row => $values) {
  319. foreach ($types as $col => $type) {
  320. /* @var \Cake\Database\Type\ExpressionTypeInterface $type */
  321. $this->_values[$row][$col] = $type->toExpression($values[$col]);
  322. }
  323. }
  324. $this->_castedExpressions = true;
  325. }
  326. }