Insert.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Drupal\Core\Database\Driver\mysql;
  3. use Drupal\Core\Database\Query\Insert as QueryInsert;
  4. /**
  5. * MySQL implementation of \Drupal\Core\Database\Query\Insert.
  6. */
  7. class Insert extends QueryInsert {
  8. public function execute() {
  9. if (!$this->preExecute()) {
  10. return NULL;
  11. }
  12. // If we're selecting from a SelectQuery, finish building the query and
  13. // pass it back, as any remaining options are irrelevant.
  14. if (empty($this->fromQuery)) {
  15. $max_placeholder = 0;
  16. $values = [];
  17. foreach ($this->insertValues as $insert_values) {
  18. foreach ($insert_values as $value) {
  19. $values[':db_insert_placeholder_' . $max_placeholder++] = $value;
  20. }
  21. }
  22. }
  23. else {
  24. $values = $this->fromQuery->getArguments();
  25. }
  26. $last_insert_id = $this->connection->query((string) $this, $values, $this->queryOptions);
  27. // Re-initialize the values array so that we can re-use this query.
  28. $this->insertValues = [];
  29. return $last_insert_id;
  30. }
  31. public function __toString() {
  32. // Create a sanitized comment string to prepend to the query.
  33. $comments = $this->connection->makeComment($this->comments);
  34. // Default fields are always placed first for consistency.
  35. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  36. $insert_fields = array_map(function ($field) {
  37. return $this->connection->escapeField($field);
  38. }, $insert_fields);
  39. // If we're selecting from a SelectQuery, finish building the query and
  40. // pass it back, as any remaining options are irrelevant.
  41. if (!empty($this->fromQuery)) {
  42. $insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
  43. return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
  44. }
  45. $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
  46. $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
  47. $query .= implode(', ', $values);
  48. return $query;
  49. }
  50. }