3 namespace Drupal\Core\Database\Query;
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\Database\Database;
9 * General class for an abstracted "Upsert" (UPDATE or INSERT) query operation.
11 * This class can only be used with a table with a single unique index.
12 * Often, this will be the primary key. On such a table this class works like
13 * Insert except the rows will be set to the desired values even if the key
16 abstract class Upsert extends Query implements \Countable {
21 * The unique or primary key of the table.
28 * Constructs an Upsert object.
30 * @param \Drupal\Core\Database\Connection $connection
31 * A Connection object.
32 * @param string $table
33 * Name of the table to associate with this query.
34 * @param array $options
35 * (optional) An array of database options.
37 public function __construct(Connection $connection, $table, array $options = []) {
38 $options['return'] = Database::RETURN_AFFECTED;
39 parent::__construct($connection, $options);
40 $this->table = $table;
44 * Sets the unique / primary key field to be used as condition for this query.
46 * @param string $field
47 * The name of the field to set.
51 public function key($field) {
58 * Preprocesses and validates the query.
61 * TRUE if the validation was successful, FALSE otherwise.
63 * @throws \Drupal\Core\Database\Query\NoUniqueFieldException
64 * @throws \Drupal\Core\Database\Query\FieldsOverlapException
65 * @throws \Drupal\Core\Database\Query\NoFieldsException
67 protected function preExecute() {
68 // Confirm that the user set the unique/primary key of the table.
70 throw new NoUniqueFieldException('There is no unique field specified.');
73 // Confirm that the user did not try to specify an identical
74 // field and default field.
75 if (array_intersect($this->insertFields, $this->defaultFields)) {
76 throw new FieldsOverlapException('You may not specify the same field to have a value and a schema-default value.');
79 // Don't execute query without fields.
80 if (count($this->insertFields) + count($this->defaultFields) == 0) {
81 throw new NoFieldsException('There are no fields available to insert with.');
84 // If no values have been added, silently ignore this query. This can happen
85 // if values are added conditionally, so we don't want to throw an
87 return isset($this->insertValues[0]) || $this->insertFields;
93 public function execute() {
94 if (!$this->preExecute()) {
100 foreach ($this->insertValues as $insert_values) {
101 foreach ($insert_values as $value) {
102 $values[':db_insert_placeholder_' . $max_placeholder++] = $value;
106 $last_insert_id = $this->connection->query((string) $this, $values, $this->queryOptions);
108 // Re-initialize the values array so that we can re-use this query.
109 $this->insertValues = [];
111 return $last_insert_id;