diff --git a/core/lib/Drupal/Core/Database/Driver/mysql/Insert.php b/core/lib/Drupal/Core/Database/Driver/mysql/Insert.php index 3647125..b458d36 100644 --- a/core/lib/Drupal/Core/Database/Driver/mysql/Insert.php +++ b/core/lib/Drupal/Core/Database/Driver/mysql/Insert.php @@ -55,7 +55,7 @@ public function __toString() { $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES '; - $values = $this->prepareInsertValues(); + $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields); $query .= implode(', ', $values); return $query; diff --git a/core/lib/Drupal/Core/Database/Driver/mysql/Upsert.php b/core/lib/Drupal/Core/Database/Driver/mysql/Upsert.php index d2da688..6d50251 100644 --- a/core/lib/Drupal/Core/Database/Driver/mysql/Upsert.php +++ b/core/lib/Drupal/Core/Database/Driver/mysql/Upsert.php @@ -26,11 +26,11 @@ public function __toString() { $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES '; - $values = $this->prepareInsertValues(); + $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields); $query .= implode(', ', $values); // Updating the unique / primary key is not necessary. - unset($insert_fields[$this->keys]); + unset($insert_fields[$this->key]); $update = []; foreach ($insert_fields as $field) { diff --git a/core/lib/Drupal/Core/Database/Driver/pgsql/Insert.php b/core/lib/Drupal/Core/Database/Driver/pgsql/Insert.php index ac43478..f36f509 100644 --- a/core/lib/Drupal/Core/Database/Driver/pgsql/Insert.php +++ b/core/lib/Drupal/Core/Database/Driver/pgsql/Insert.php @@ -128,7 +128,7 @@ public function __toString() { $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES '; - $values = $this->prepareInsertValues(); + $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields); $query .= implode(', ', $values); return $query; diff --git a/core/lib/Drupal/Core/Database/Driver/pgsql/Upsert.php b/core/lib/Drupal/Core/Database/Driver/pgsql/Upsert.php index 3d3f31f..b64869c 100644 --- a/core/lib/Drupal/Core/Database/Driver/pgsql/Upsert.php +++ b/core/lib/Drupal/Core/Database/Driver/pgsql/Upsert.php @@ -32,7 +32,7 @@ public function execute() { $insert_fields_escaped = array_map(function($f) { return $this->connection->escapeField($f); }, $insert_fields); $table = $this->connection->escapeTable($this->table); - $unique_key = $this->connection->escapeField($this->keys); + $unique_key = $this->connection->escapeField($this->key); // We have to execute multiple queries, therefore we wrap everything in a // transaction so that it is atomic where possible. @@ -85,8 +85,8 @@ public function execute() { // WHERE table_name.id IS NULL; $select = $this->connection->select($temp_table, 'temp_table', $this->queryOptions) ->fields('temp_table', $insert_fields); - $select->leftJoin($this->table, 'actual_table', 'actual_table.' . $this->keys . ' = temp_table.' . $this->keys); - $select->isNull('actual_table.' . $this->keys); + $select->leftJoin($this->table, 'actual_table', 'actual_table.' . $this->key . ' = temp_table.' . $this->key); + $select->isNull('actual_table.' . $this->key); $this->connection->insert($this->table, $this->queryOptions) ->from($select) diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Upsert.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Upsert.php index 9287884..d382b18 100644 --- a/core/lib/Drupal/Core/Database/Driver/sqlite/Upsert.php +++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Upsert.php @@ -26,7 +26,7 @@ public function __toString() { $query = $comments . 'INSERT OR REPLACE INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES '; - $values = $this->prepareInsertValues(); + $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields); $query .= implode(', ', $values); return $query; diff --git a/core/lib/Drupal/Core/Database/Query/Insert.php b/core/lib/Drupal/Core/Database/Query/Insert.php index b4ec4ef..045413a 100644 --- a/core/lib/Drupal/Core/Database/Query/Insert.php +++ b/core/lib/Drupal/Core/Database/Query/Insert.php @@ -14,7 +14,9 @@ * * @ingroup database */ -class Insert extends InsertBase { +class Insert extends Query { + + use InsertTrait; /** * A SelectQuery object to fetch the rows that should be inserted. @@ -137,13 +139,13 @@ public function __toString() { /** * Preprocesses and validates the query. * - * @return + * @return bool * TRUE if the validation was successful, FALSE if not. * * @throws \Drupal\Core\Database\Query\FieldsOverlapException * @throws \Drupal\Core\Database\Query\NoFieldsException */ - public function preExecute() { + protected function preExecute() { // Confirm that the user did not try to specify an identical // field and default field. if (array_intersect($this->insertFields, $this->defaultFields)) { diff --git a/core/lib/Drupal/Core/Database/Query/InsertBase.php b/core/lib/Drupal/Core/Database/Query/InsertTrait.php similarity index 85% rename from core/lib/Drupal/Core/Database/Query/InsertBase.php rename to core/lib/Drupal/Core/Database/Query/InsertTrait.php index 57c26f2..551e870 100644 --- a/core/lib/Drupal/Core/Database/Query/InsertBase.php +++ b/core/lib/Drupal/Core/Database/Query/InsertTrait.php @@ -2,17 +2,17 @@ /** * @file - * Contains \Drupal\Core\Database\Query\InsertBase. + * Contains \Drupal\Core\Database\Query\InsertTrait. */ namespace Drupal\Core\Database\Query; /** - * Base class for INSERT and UPSERT queries. + * Provides common functionality for INSERT and UPSERT queries. * * @ingroup database */ -abstract class InsertBase extends Query { +trait InsertTrait { /** * The table on which to insert. @@ -143,21 +143,26 @@ public function useDefaults(array $fields) { } /** - * Prepares the placeholders for values that will be inserted. + * Returns the query placeholders for values that will be inserted. + * + * @param array $nested_insert_values + * A nested array of values to insert. + * @param array $default_fields + * An array of fields that should be set to their database-defined defaults. * * @return array - * An array of insert values. + * An array of insert placeholders. */ - protected function prepareInsertValues() { + protected function getInsertPlaceholderFragment(array $nested_insert_values, array $default_fields) { $max_placeholder = 0; $values = array(); - if ($this->insertValues) { - foreach ($this->insertValues as $insert_values) { + if ($nested_insert_values) { + foreach ($nested_insert_values as $insert_values) { $placeholders = array(); // Default fields aren't really placeholders, but this is the most convenient // way to handle them. - $placeholders = array_pad($placeholders, count($this->defaultFields), 'default'); + $placeholders = array_pad($placeholders, count($default_fields), 'default'); $new_placeholder = $max_placeholder + count($insert_values); for ($i = $max_placeholder; $i < $new_placeholder; ++$i) { @@ -169,7 +174,7 @@ protected function prepareInsertValues() { } else { // If there are no values, then this is a default-only query. We still need to handle that. - $placeholders = array_fill(0, count($this->defaultFields), 'default'); + $placeholders = array_fill(0, count($default_fields), 'default'); $values[] = '(' . implode(', ', $placeholders) . ')'; } diff --git a/core/lib/Drupal/Core/Database/Query/Upsert.php b/core/lib/Drupal/Core/Database/Query/Upsert.php index 8133c19..ccb1aa4 100644 --- a/core/lib/Drupal/Core/Database/Query/Upsert.php +++ b/core/lib/Drupal/Core/Database/Query/Upsert.php @@ -18,17 +18,16 @@ * Insert except the rows will be set to the desired values even if the key * existed before. */ -class Upsert extends InsertBase { +abstract class Upsert extends Query { + + use InsertTrait; /** - * The name of the fields that form a unique or primary key of the table. - * - * @todo Only a single field is supported at the moment. Revisit this decision - * in https://www.drupal.org/node/2547493 + * The unique or primary key of the table. * - * @var array + * @var string */ - protected $keys; + protected $key; /** * Constructs an Upsert object. @@ -47,24 +46,15 @@ public function __construct(Connection $connection, $table, array $options = []) } /** - * Sets the unique fields to be used as conditions for this query. + * Sets the unique / primary key field to be used as condition for this query. * - * @param string|array $fields - * The name of the field(s) that form an unique key. + * @param string $field + * The name of the field to set. * * @return $this */ - public function key($fields) { - $fields = (array) $fields; - - if (count($fields) > 1) { - throw new \InvalidArgumentException('Unique indexes composed of multiple fields are not supported.'); - } - - // @todo We only support unique indexes that are composed of a single field. - // Decide if we can expand support to multiple fields in - // https://www.drupal.org/node/2547493 - $this->keys = reset($fields); + public function key($field) { + $this->key = $field; return $this; } @@ -79,9 +69,9 @@ public function key($fields) { * @throws \Drupal\Core\Database\Query\FieldsOverlapException * @throws \Drupal\Core\Database\Query\NoFieldsException */ - public function preExecute() { + protected function preExecute() { // Confirm that the user set the unique/primary key of the table. - if (!$this->keys) { + if (!$this->key) { throw new NoUniqueFieldException('There is no unique field specified.'); } diff --git a/core/modules/system/src/Tests/Database/UpsertTest.php b/core/modules/system/src/Tests/Database/UpsertTest.php index 47c6a69..57372f6 100644 --- a/core/modules/system/src/Tests/Database/UpsertTest.php +++ b/core/modules/system/src/Tests/Database/UpsertTest.php @@ -18,53 +18,45 @@ class UpsertTest extends DatabaseTestBase { /** - * Confirms that we can merge-insert a record successfully. + * Confirms that we can upsert (update-or-insert) records successfully. */ - public function testMergeInsert() { + public function testUpsert() { $connection = Database::getConnection(); $num_records_before = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField(); - $connection->upsert('test_people') + $upsert = $connection->upsert('test_people') ->key('job') - ->fields(array( - 'job' => 'Presenter', - 'age' => 31, - 'name' => 'Tiffany', - )) - ->execute(); + ->fields(['job', 'age', 'name']); - $num_records_after = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField(); - $this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.'); + // Add a new row. + $upsert->values([ + 'job' => 'Presenter', + 'age' => 31, + 'name' => 'Tiffany', + ]); - $person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch(); - $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.'); - $this->assertEqual($person->age, 31, 'Age set correctly.'); - $this->assertEqual($person->job, 'Presenter', 'Job set correctly.'); - } + // Update an existing row. + $upsert->values([ + 'job' => 'Speaker', + // The initial age was 30. + 'age' => 32, + 'name' => 'Meredith', + ]); - /** - * Confirms that we can merge-update a record successfully. - */ - public function testMergeUpdate() { - $connection = Database::getConnection(); - $num_records_before = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField(); - - $connection->upsert('test_people') - ->key('job') - ->fields(array( - 'job' => 'Speaker', - 'age' => 31, - 'name' => 'Tiffany', - )) - ->execute(); + $upsert->execute(); $num_records_after = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField(); - $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.'); + $this->assertEqual($num_records_before + 1, $num_records_after, 'Rows were inserted and updated properly.'); - $person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch(); - $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.'); + $person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch(); + $this->assertEqual($person->job, 'Presenter', 'Job set correctly.'); $this->assertEqual($person->age, 31, 'Age set correctly.'); - $this->assertEqual($person->job, 'Speaker', 'Job set correctly.'); + $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.'); + + $person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch(); + $this->assertEqual($person->job, 'Speaker', 'Job was not changed.'); + $this->assertEqual($person->age, 32, 'Age updated correctly.'); + $this->assertEqual($person->name, 'Meredith', 'Name was not changed.'); } }