Upsert.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\Core\Database\Driver\mysql;
  3. use Drupal\Core\Database\Query\Upsert as QueryUpsert;
  4. /**
  5. * MySQL implementation of \Drupal\Core\Database\Query\Upsert.
  6. */
  7. class Upsert extends QueryUpsert {
  8. /**
  9. * {@inheritdoc}
  10. */
  11. public function __toString() {
  12. // Create a sanitized comment string to prepend to the query.
  13. $comments = $this->connection->makeComment($this->comments);
  14. // Default fields are always placed first for consistency.
  15. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  16. $insert_fields = array_map(function ($field) {
  17. return $this->connection->escapeField($field);
  18. }, $insert_fields);
  19. $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
  20. $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
  21. $query .= implode(', ', $values);
  22. // Updating the unique / primary key is not necessary.
  23. unset($insert_fields[$this->key]);
  24. $update = [];
  25. foreach ($insert_fields as $field) {
  26. $update[] = "$field = VALUES($field)";
  27. }
  28. $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);
  29. return $query;
  30. }
  31. }