Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Database / Query / Insert.php
1 <?php
2
3 namespace Drupal\Core\Database\Query;
4
5 use Drupal\Core\Database\Database;
6
7 /**
8  * General class for an abstracted INSERT query.
9  *
10  * @ingroup database
11  */
12 class Insert extends Query implements \Countable {
13
14   use InsertTrait;
15
16   /**
17    * A SelectQuery object to fetch the rows that should be inserted.
18    *
19    * @var \Drupal\Core\Database\Query\SelectInterface
20    */
21   protected $fromQuery;
22
23   /**
24    * Constructs an Insert object.
25    *
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.
32    */
33   public function __construct($connection, $table, array $options = []) {
34     if (!isset($options['return'])) {
35       $options['return'] = Database::RETURN_INSERT_ID;
36     }
37     parent::__construct($connection, $options);
38     $this->table = $table;
39   }
40
41   /**
42    * Sets the fromQuery on this InsertQuery object.
43    *
44    * @param \Drupal\Core\Database\Query\SelectInterface $query
45    *   The query to fetch the rows that should be inserted.
46    *
47    * @return \Drupal\Core\Database\Query\Insert
48    *   The called object.
49    */
50   public function from(SelectInterface $query) {
51     $this->fromQuery = $query;
52     return $this;
53   }
54
55   /**
56    * Executes the insert query.
57    *
58    * @return
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.
63    */
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()) {
68       return NULL;
69     }
70
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);
77     }
78
79     $last_insert_id = 0;
80
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();
85
86     try {
87       $sql = (string) $this;
88       foreach ($this->insertValues as $insert_values) {
89         $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
90       }
91     }
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.
96       throw $e;
97     }
98
99     // Re-initialize the values array so that we can re-use this query.
100     $this->insertValues = [];
101
102     // Transaction commits here where $transaction looses scope.
103
104     return $last_insert_id;
105   }
106
107   /**
108    * Implements PHP magic __toString method to convert the query to a string.
109    *
110    * @return string
111    *   The prepared statement.
112    */
113   public function __toString() {
114     // Create a sanitized comment string to prepend to the query.
115     $comments = $this->connection->makeComment($this->comments);
116
117     // Default fields are always placed first for consistency.
118     $insert_fields = array_merge($this->defaultFields, $this->insertFields);
119
120     if (!empty($this->fromQuery)) {
121       return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') ' . $this->fromQuery;
122     }
123
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.
127     $placeholders = [];
128     $placeholders = array_pad($placeholders, count($this->defaultFields), 'default');
129     $placeholders = array_pad($placeholders, count($this->insertFields), '?');
130
131     return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES (' . implode(', ', $placeholders) . ')';
132   }
133
134   /**
135    * Preprocesses and validates the query.
136    *
137    * @return bool
138    *   TRUE if the validation was successful, FALSE if not.
139    *
140    * @throws \Drupal\Core\Database\Query\FieldsOverlapException
141    * @throws \Drupal\Core\Database\Query\NoFieldsException
142    */
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.');
148     }
149
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())));
157     }
158     else {
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.');
162       }
163     }
164
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
167     // exception.
168     if (!isset($this->insertValues[0]) && count($this->insertFields) > 0 && empty($this->fromQuery)) {
169       return FALSE;
170     }
171     return TRUE;
172   }
173
174 }