3 namespace Drupal\Core\Database\Driver\mysql;
5 use Drupal\Core\Database\Query\Insert as QueryInsert;
8 * MySQL implementation of \Drupal\Core\Database\Query\Insert.
10 class Insert extends QueryInsert {
12 public function execute() {
13 if (!$this->preExecute()) {
17 // If we're selecting from a SelectQuery, finish building the query and
18 // pass it back, as any remaining options are irrelevant.
19 if (empty($this->fromQuery)) {
22 foreach ($this->insertValues as $insert_values) {
23 foreach ($insert_values as $value) {
24 $values[':db_insert_placeholder_' . $max_placeholder++] = $value;
29 $values = $this->fromQuery->getArguments();
32 $last_insert_id = $this->connection->query((string) $this, $values, $this->queryOptions);
34 // Re-initialize the values array so that we can re-use this query.
35 $this->insertValues = [];
37 return $last_insert_id;
40 public function __toString() {
41 // Create a sanitized comment string to prepend to the query.
42 $comments = $this->connection->makeComment($this->comments);
44 // Default fields are always placed first for consistency.
45 $insert_fields = array_merge($this->defaultFields, $this->insertFields);
47 $insert_fields = array_map(function ($field) {
48 return $this->connection->escapeField($field);
51 // If we're selecting from a SelectQuery, finish building the query and
52 // pass it back, as any remaining options are irrelevant.
53 if (!empty($this->fromQuery)) {
54 $insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
55 return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
58 $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
60 $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
61 $query .= implode(', ', $values);