ValuesExpression.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. * @internal
  29. */
  30. class ValuesExpression implements ExpressionInterface
  31. {
  32. use ExpressionTypeCasterTrait;
  33. use TypeMapTrait;
  34. /**
  35. * Array of values to insert.
  36. *
  37. * @var array
  38. */
  39. protected $_values = [];
  40. /**
  41. * List of columns to ensure are part of the insert.
  42. *
  43. * @var array
  44. */
  45. protected $_columns = [];
  46. /**
  47. * The Query object to use as a values expression
  48. *
  49. * @var \Cake\Database\Query
  50. */
  51. protected $_query = false;
  52. /**
  53. * Whether or not values have been casted to expressions
  54. * already.
  55. *
  56. * @var string
  57. */
  58. protected $_castedExpressions = false;
  59. /**
  60. * Constructor
  61. *
  62. * @param array $columns The list of columns that are going to be part of the values.
  63. * @param \Cake\Database\TypeMap $typeMap A dictionary of column -> type names
  64. */
  65. public function __construct(array $columns, $typeMap)
  66. {
  67. $this->_columns = $columns;
  68. $this->typeMap($typeMap);
  69. }
  70. /**
  71. * Add a row of data to be inserted.
  72. *
  73. * @param array|\Cake\Database\Query $data Array of data to append into the insert, or
  74. * a query for doing INSERT INTO .. SELECT style commands
  75. * @return void
  76. * @throws \Cake\Database\Exception When mixing array + Query data types.
  77. */
  78. public function add($data)
  79. {
  80. if ((count($this->_values) && $data instanceof Query) ||
  81. ($this->_query && is_array($data))
  82. ) {
  83. throw new Exception(
  84. 'You cannot mix subqueries and array data in inserts.'
  85. );
  86. }
  87. if ($data instanceof Query) {
  88. $this->query($data);
  89. return;
  90. }
  91. $this->_values[] = $data;
  92. $this->_castedExpressions = false;
  93. }
  94. /**
  95. * Sets the columns to be inserted. If no params are passed, then it returns
  96. * the currently stored columns
  97. *
  98. * @param array|null $cols arrays with columns to be inserted
  99. * @return array|$this
  100. */
  101. public function columns($cols = null)
  102. {
  103. if ($cols === null) {
  104. return $this->_columns;
  105. }
  106. $this->_columns = $cols;
  107. $this->_castedExpressions = false;
  108. return $this;
  109. }
  110. /**
  111. * Sets the values to be inserted. If no params are passed, then it returns
  112. * the currently stored values
  113. *
  114. * @param array|null $values arrays with values to be inserted
  115. * @return array|$this
  116. */
  117. public function values($values = null)
  118. {
  119. if ($values === null) {
  120. if (!$this->_castedExpressions) {
  121. $this->_processExpressions();
  122. }
  123. return $this->_values;
  124. }
  125. $this->_values = $values;
  126. $this->_castedExpressions = false;
  127. return $this;
  128. }
  129. /**
  130. * Sets the query object to be used as the values expression to be evaluated
  131. * to insert records in the table. If no params are passed, then it returns
  132. * the currently stored query
  133. *
  134. * @param \Cake\Database\Query|null $query The query to set/get
  135. * @return \Cake\Database\Query
  136. */
  137. public function query(Query $query = null)
  138. {
  139. if ($query === null) {
  140. return $this->_query;
  141. }
  142. $this->_query = $query;
  143. }
  144. /**
  145. * Convert the values into a SQL string with placeholders.
  146. *
  147. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  148. * @return string
  149. */
  150. public function sql(ValueBinder $generator)
  151. {
  152. if (empty($this->_values) && empty($this->_query)) {
  153. return '';
  154. }
  155. if (!$this->_castedExpressions) {
  156. $this->_processExpressions();
  157. }
  158. $i = 0;
  159. $columns = [];
  160. // Remove identifier quoting so column names match keys.
  161. foreach ($this->_columns as $col) {
  162. $columns[] = trim($col, '`[]"');
  163. }
  164. $defaults = array_fill_keys($columns, null);
  165. $placeholders = [];
  166. $types = [];
  167. $typeMap = $this->typeMap();
  168. foreach ($defaults as $col => $v) {
  169. $types[$col] = $typeMap->type($col);
  170. }
  171. foreach ($this->_values as $row) {
  172. $row += $defaults;
  173. $rowPlaceholders = [];
  174. foreach ($this->_columns as $column) {
  175. $value = $row[$column];
  176. if ($value instanceof ExpressionInterface) {
  177. $rowPlaceholders[] = '(' . $value->sql($generator) . ')';
  178. continue;
  179. }
  180. $placeholder = $generator->placeholder($i);
  181. $rowPlaceholders[] = $placeholder;
  182. $generator->bind($placeholder, $value, $types[$column]);
  183. }
  184. $placeholders[] = implode(', ', $rowPlaceholders);
  185. }
  186. if ($this->query()) {
  187. return ' ' . $this->query()->sql($generator);
  188. }
  189. return sprintf(' VALUES (%s)', implode('), (', $placeholders));
  190. }
  191. /**
  192. * Traverse the values expression.
  193. *
  194. * This method will also traverse any queries that are to be used in the INSERT
  195. * values.
  196. *
  197. * @param callable $visitor The visitor to traverse the expression with.
  198. * @return void
  199. */
  200. public function traverse(callable $visitor)
  201. {
  202. if ($this->_query) {
  203. return;
  204. }
  205. if (!$this->_castedExpressions) {
  206. $this->_processExpressions();
  207. }
  208. foreach ($this->_values as $v) {
  209. if ($v instanceof ExpressionInterface) {
  210. $v->traverse($visitor);
  211. }
  212. if (!is_array($v)) {
  213. continue;
  214. }
  215. foreach ($v as $column => $field) {
  216. if ($field instanceof ExpressionInterface) {
  217. $visitor($field);
  218. $field->traverse($visitor);
  219. }
  220. }
  221. }
  222. }
  223. /**
  224. * Converts values that need to be casted to expressions
  225. *
  226. * @return void
  227. */
  228. protected function _processExpressions()
  229. {
  230. $types = [];
  231. $typeMap = $this->typeMap();
  232. foreach ($this->_columns as $c) {
  233. if (!is_scalar($c)) {
  234. continue;
  235. }
  236. $types[$c] = $typeMap->type($c);
  237. }
  238. $types = $this->_requiresToExpressionCasting($types);
  239. if (empty($types)) {
  240. return;
  241. }
  242. foreach ($this->_values as $row => $values) {
  243. foreach ($types as $col => $type) {
  244. $this->_values[$row][$col] = $type->toExpression($values[$col]);
  245. }
  246. }
  247. $this->_castedExpressions = true;
  248. }
  249. }