3 namespace Drupal\Core\Database\Query;
5 use Drupal\Core\Database\Database;
8 * General class for an abstracted INSERT query.
12 class Insert extends Query implements \Countable {
17 * A SelectQuery object to fetch the rows that should be inserted.
19 * @var \Drupal\Core\Database\Query\SelectInterface
24 * Constructs an Insert object.
26 * @param \Drupal\Core\Database\Connection $connection
27 * A Connection object.
28 * @param string $table
29 * Name of the table to associate with this query.
30 * @param array $options
31 * Array of database options.
33 public function __construct($connection, $table, array $options = []) {
34 if (!isset($options['return'])) {
35 $options['return'] = Database::RETURN_INSERT_ID;
37 parent::__construct($connection, $options);
38 $this->table = $table;
42 * Sets the fromQuery on this InsertQuery object.
44 * @param \Drupal\Core\Database\Query\SelectInterface $query
45 * The query to fetch the rows that should be inserted.
47 * @return \Drupal\Core\Database\Query\Insert
50 public function from(SelectInterface $query) {
51 $this->fromQuery = $query;
56 * Executes the insert query.
59 * The last insert ID of the query, if one exists. If the query was given
60 * multiple sets of values to insert, the return value is undefined. If no
61 * fields are specified, this method will do nothing and return NULL. That
62 * That makes it safe to use in multi-insert loops.
64 public function execute() {
65 // If validation fails, simply return NULL. Note that validation routines
66 // in preExecute() may throw exceptions instead.
67 if (!$this->preExecute()) {
71 // If we're selecting from a SelectQuery, finish building the query and
72 // pass it back, as any remaining options are irrelevant.
73 if (!empty($this->fromQuery)) {
74 $sql = (string) $this;
75 // The SelectQuery may contain arguments, load and pass them through.
76 return $this->connection->query($sql, $this->fromQuery->getArguments(), $this->queryOptions);
81 // Each insert happens in its own query in the degenerate case. However,
82 // we wrap it in a transaction so that it is atomic where possible. On many
83 // databases, such as SQLite, this is also a notable performance boost.
84 $transaction = $this->connection->startTransaction();
87 $sql = (string) $this;
88 foreach ($this->insertValues as $insert_values) {
89 $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
92 catch (\Exception $e) {
93 // One of the INSERTs failed, rollback the whole batch.
94 $transaction->rollBack();
95 // Rethrow the exception for the calling code.
99 // Re-initialize the values array so that we can re-use this query.
100 $this->insertValues = [];
102 // Transaction commits here where $transaction looses scope.
104 return $last_insert_id;
108 * Implements PHP magic __toString method to convert the query to a string.
111 * The prepared statement.
113 public function __toString() {
114 // Create a sanitized comment string to prepend to the query.
115 $comments = $this->connection->makeComment($this->comments);
117 // Default fields are always placed first for consistency.
118 $insert_fields = array_merge($this->defaultFields, $this->insertFields);
120 if (!empty($this->fromQuery)) {
121 return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') ' . $this->fromQuery;
124 // For simplicity, we will use the $placeholders array to inject
125 // default keywords even though they are not, strictly speaking,
126 // placeholders for prepared statements.
128 $placeholders = array_pad($placeholders, count($this->defaultFields), 'default');
129 $placeholders = array_pad($placeholders, count($this->insertFields), '?');
131 return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES (' . implode(', ', $placeholders) . ')';
135 * Preprocesses and validates the query.
138 * TRUE if the validation was successful, FALSE if not.
140 * @throws \Drupal\Core\Database\Query\FieldsOverlapException
141 * @throws \Drupal\Core\Database\Query\NoFieldsException
143 protected function preExecute() {
144 // Confirm that the user did not try to specify an identical
145 // field and default field.
146 if (array_intersect($this->insertFields, $this->defaultFields)) {
147 throw new FieldsOverlapException('You may not specify the same field to have a value and a schema-default value.');
150 if (!empty($this->fromQuery)) {
151 // We have to assume that the used aliases match the insert fields.
152 // Regular fields are added to the query before expressions, maintain the
153 // same order for the insert fields.
154 // This behavior can be overridden by calling fields() manually as only the
155 // first call to fields() does have an effect.
156 $this->fields(array_merge(array_keys($this->fromQuery->getFields()), array_keys($this->fromQuery->getExpressions())));
159 // Don't execute query without fields.
160 if (count($this->insertFields) + count($this->defaultFields) == 0) {
161 throw new NoFieldsException('There are no fields available to insert with.');
165 // If no values have been added, silently ignore this query. This can happen
166 // if values are added conditionally, so we don't want to throw an
168 if (!isset($this->insertValues[0]) && count($this->insertFields) > 0 && empty($this->fromQuery)) {