Problem/Motivation

Currently we implement a subset of the ANSI SQL:2003 MERGE command but another subset is desirable, one that SQLite implements with INSERT ON CONFLICT REPLACE, MySQL implements with REPLACE or INSERT ON DUPLICATE KEY. We do not intend this to be too general and will strongly recommend to use only on tables with a primary key and no other unique keys.

Proposed resolution

Add a lock free, multiple value allowing MERGE subset. Tentative name: Upsert.

This is the query we would like to build:

INSERT INTO {table} (f1,f2,f3) VALUES (v1,v2,v3),(v4,v5,v6) ON DUPLICATE KEY UPDATE SET f1=VALUES(f1), f2=VALUES(f2), f3=VALUES(f3)

This is what the cache and similar needs. Basically this in a query. This class is not intend to be a full builder for INSERT ON DUPLICATE KEY. It's a query builder specifically for this one query and nothing else.

  1. We do not want to support INSERT ... SELECT here: in MySQL 5.6.4 and later, INSERT ... SELECT ON DUPLICATE KEY UPDATE statements are flagged as unsafe for statement-based replication. With this change, such statements produce a warning in the log when using statement-based mode
  2. We do not want to support all sorts of UPDATE expressions since SQLite only has ON CONFLICT REPLACE. Also note we do not need them, we have Merge for that.

Remaining tasks

User interface changes

API changes

Data model changes

Reference: https://www.drupal.org/core/beta-changes
Issue category Task because we are adding a new database class (but it's not a feature) .
Issue priority Critical because this is necessary for a critical.
Prioritized changes It's gateway to a critical.

Comments

dawehner’s picture

+++ b/core/lib/Drupal/Core/Database/Connection.php
@@ -786,6 +786,21 @@ public function merge($table, array $options = array()) {
+  /**
+   * Prepares and returns an UPSERT query object.
+   *

It would be great to point to some documentation explaining what UPSERT results into. At least personally I wasn't aware of it existence before this issue.

chx’s picture

Issue summary: View changes
chx’s picture

Issue summary: View changes
chx’s picture

Issue summary: View changes
Status: Active » Needs review
StatusFileSize
new20.86 KB
chx’s picture

Issue summary: View changes
chx’s picture

Issue summary: View changes
chx’s picture

Issue summary: View changes
berdir’s picture

Priority: Normal » Major

This is probably at least major, considering that it is meant to be used to fix a critical?

chx’s picture

Probably the parent should be postponed and this raised to critical.

martin107’s picture

StatusFileSize
new21.18 KB
new3.44 KB

While keeping up with this issue - I noticed a couple of small inconsequential nits - might as well fix in public

chx’s picture

Thanks. Please read the issue summary / code about updateValues() the current doxygen on $fields is incorrect. It's a list of fields to set to the same values as being inserted.

martin107’s picture

StatusFileSize
new21.08 KB
new1.19 KB

Ah thanks ... I missed that.

1) Changed parameter name from $fields to $values.
2) Added comments describing with the property Upsert::updateValues.
3) Corrected the updateValues() annotation..

Please let me know if there is anything to add ... and I will jump on it.

chx’s picture

Sorry but that's still not correct. I know it's confusing but the issue summary has a writeup on how these method names happened and what's the logic behind naming them and how the logic from different places created a confusing mess. The original was more correct:

-   * A list of fields to update to the same value as they would be on INSERT.
+   * Specifies an array of values used to update the database.

it is a list of fields. If you specify [f1,f2,f3] you get INSERT ... ON DUPLICATE KEY SET f1=VALUES(f1),f2=VALUES(f2),f3=VALUES(3). It is not an array of literal values. That one goes into updateFields. Did I mention the naming is a colossal mess?

chx’s picture

Issue summary: View changes
StatusFileSize
new12.61 KB

Brutally simplified. Nothing is supported beyond INSERT ON CONFLICT REPLACE. No fields, no expressions, nothing.

chx’s picture

Issue summary: View changes

Status: Needs review » Needs work

The last submitted patch, 14: 2542776_14.patch, failed testing.

amateescu’s picture

Assigned: Unassigned » amateescu
Status: Needs work » Needs review
StatusFileSize
new15.83 KB
new5.87 KB

Finally started to continue the work on this :) The vast simplification from #14 makes very much sense indeed!

The first thing we need for the Postgres implementation is to make specifying the unique key of the table mandatory. This also helps in the MySQL implementation because we shouldn't add the unique field to the list of fields to update.

amateescu’s picture

Issue tags: +sqlite, +PostgreSQL
StatusFileSize
new19.4 KB
new5.4 KB

Here's the Postgres implementation.

The sqlite syntax (ON CONFLICT REPLACE) is 99% similar to mysql (ON DUPLICATE KEY UPDATE), so maybe we should just move the mysql implementation up a level as helper methods?

olli’s picture

Great work! Is this upsert() only for setMultiple() or also for set()? I see that DatabaseCacheTagsChecksum::invalidateTags() executes a merge in a loop - could we use upsert() there too?

+++ b/core/lib/Drupal/Core/Cache/DatabaseBackend.php
@@ -234,34 +234,20 @@ public function setMultiple(array $items) {
-      // Delete all items first so we can do one insert. Rather than multiple
-      // merge queries.
-      $this->deleteMultiple(array_keys($items));

Note that this deleteMultiple creates the table if it doesn't exist.

chx’s picture

> The sqlite syntax (ON CONFLICT REPLACE) is 99% similar to mysql (ON DUPLICATE KEY UPDATE), so maybe we should just move the mysql implementation up a level as helper methods?

As you wish: I carried this issue as far as I wanted, it's all yours now. Note: the DatabaseBackend change probably doesn't belong in this issue.

amateescu’s picture

StatusFileSize
new20.58 KB
new1.18 KB

Turns out we had a bug in \Drupal\Core\Database\Driver\pgsql\Schema::queryTableInformation(), which didn't take temporary tables into account. Small fix, big win :)

@olli:

Is this upsert() only for setMultiple() or also for set()?

It's optimized for setMultiple() but I don't see any reason to not use it for set() as well.

I see that DatabaseCacheTagsChecksum::invalidateTags() executes a merge in a loop - could we use upsert() there too?

Probably so, in a followup :)

@chx:

Note: the DatabaseBackend change probably doesn't belong in this issue.

You're right, I'm only keeping it here because it allows us to test on a real table with various column types (e.g. bytea for Postgres). It should be removed from the patch when we have passing tests on all three db drivers.

amateescu’s picture

StatusFileSize
new22.7 KB
new3.05 KB

I was wrong about the SQLite syntax. What I said above applies only to CREATE TABLE queries. For INSERT queries the syntax is simply INSERT OR REPLACE ....

That makes it harder to put the entire __toString() method from the mysql implementation in the parent class, so here's a patch that copies and updates the relevant parts for SQLite.

There is some code that prepares the placeholders which is copied all over the place though, maybe it makes sense to move just that to a InsertBase class. I'll try that in the next patch, for now let's see if this passes on all three engines.

berdir’s picture

  1. +++ b/core/lib/Drupal/Core/Cache/DatabaseBackend.php
    @@ -234,34 +234,20 @@ public function setMultiple(array $items) {
    +      // Only pass the values since the order of $fields matches the order of
    +      // the insert fields. This is a performance optimization to avoid
    +      // unnecessary loops within the method.
    +      $query->values(array_values($fields));
    

    Is that kind of micro-optimization really worth it? And if it is, then why not build it like this in the first place? ;)

    But I guess we can fight about that in the deadlock issue :)

  2. +++ b/core/lib/Drupal/Core/Database/Driver/mysql/Upsert.php
    @@ -0,0 +1,89 @@
    +
    +class Upsert extends QueryUpsert {
    

    Missing docs but I'm sure you know that ;)

  3. +++ b/core/lib/Drupal/Core/Database/Query/Upsert.php
    @@ -0,0 +1,202 @@
    + * Often, this will be the primary key. On such a table this class works like
    + * Insert except the rows will be set to the desired values even if the key
    + * existed before.
    + */
    +class Upsert extends Query {
    

    I guess extending from insert would expose methods that we don't want to have here? Is there enough shared code that to make a trait worthwile?

    Also, is there a reason to not add an interface, other than other such classes not having one either (usually existing bad code isn't an excuse).

chx’s picture

MySQL and SQLite execute() are the same, move to parent? __toString surely differs but execute() looks like the same.

Also, the PostgreSQL solution does not look performant -- perhaps a pgsql.cache.backend.database service should be used in the parent with an even less generic solution? And/or since we went 9.1 use CTEs? http://www.the-art-of-web.com/sql/upsert/

amateescu’s picture

StatusFileSize
new31.66 KB
new22.71 KB

@Berdir:
#23.1: Yeah, let's discuss that in the other issue. Like I said, the change to DatabaseBackend will be removed from the final patch here.

#23.2: Fixed.

#23.3: Yes, we don't want from() from Insert, but otherwise there is *a lot* of code that we reuse, so I introduced an InsertBase class for it.

@chx:
#24.1: Moved execute() to a executeHelper() on the parent class.

#24.2: According to http://www.xzilla.net/blog/2011/Mar/Upserting-via-Writeable-CTE.html and http://stackoverflow.com/a/8702291/1499564, a postgres implementation using CTEs is prone to race conditions, so I implemented the "Bulk upsert with lock" solution from http://stackoverflow.com/a/17267423/1499564. It's not that slow too, I tested by timing a drush site-install:

With patch:

16,40s user
 0,78s system
   57% cpu
30,013 total

Without patch:

16,86s user
 0,63s system
   59% cpu
29,485 total

Status: Needs review » Needs work

The last submitted patch, 25: 2542776-25.patch, failed testing.

amateescu’s picture

Assigned: amateescu » Unassigned
Status: Needs work » Needs review
StatusFileSize
new31.85 KB
new1.29 KB

Fixed the methods copied from Upsert by using the ones from Insert.

amateescu’s picture

I did a few more drush site-installs on postgres with the patch applied and I get very similar results to HEAD:

drush sis-pg  14,79s user 0,78s system 55% cpu 28,149 total
drush sis-pg  16,83s user 0,79s system 57% cpu 30,551 total
drush sis-pg  14,77s user 0,86s system 55% cpu 28,093 total

So I'm pretty sure the pgsql upsert code is not slower than the current "delete everything then insert" implementation of the database cache backed, which is already faster than doing multiple merges in a loop.

amateescu’s picture

StatusFileSize
new31.49 KB
new2.81 KB

Discussed a bit with @chx and we both agree to not introduce a generic UPSERT implementation in the parent class and let/force each driver to do their own thing.

Edit: Also, this patch is ready for final reviews now :)

chx’s picture

Two more things:

a) as the postgresql example shows, it's better to not throw an exception in __toString, just document the thing. if any drivers doesnt override execute but doesnt do __toString the fatal error of running an empty query is enough
b) change key to an array. For now, handle one element arrays, file a todo issue to handle more than one. For now throw an excepton if more than one element is in key. Future proofing and all that. If we want, we can remove the unset($insert_fields[$this->key]); microoptimization and throw an exception only in pgsql since mysql and sqlite doesnt need key really and then file an issue to make it work in pgsql only. W/E.

amateescu’s picture

StatusFileSize
new29.84 KB
new6.92 KB

Fixed #30 a) and b). I also removed the change to the cache db backend since this patch is ready for final reviews and we have multiple testbot results which confirm that it's working as expected.

Opened #2547493: Add support for unique / primary key constraints composed of multiple fields for Upsert queries for #30 b).

amateescu’s picture

Assigned: Unassigned » Crell
Issue tags: +Needs subsystem maintainer review
StatusFileSize
new29.9 KB
new1002 bytes

I shouldn't post patches in a rush. We need a sign-off from a db maintainer now :)

Crell’s picture

Status: Needs review » Needs work

This is looking really good, folks. Nice work! Some things to fix, though:

  1. +++ b/core/lib/Drupal/Core/Database/Driver/pgsql/Upsert.php
    @@ -0,0 +1,111 @@
    +    // Re-initialize the values array so that we can re-use this query.
    +    $this->insertValues = array();
    

    Insert queries are reusable to allow for batch import multi-insert statements. (Queue up 20 values() clauses, execute, queue up 20 more, etc.) Is that a valid use case for upserts? I'm wary about them being reusable. Is there a use case for that?

    This is in the Postgres implementation only, so that would seem to create an inconsistency between drivers, no?

  2. +++ b/core/lib/Drupal/Core/Database/Query/InsertBase.php
    @@ -0,0 +1,179 @@
    +/**
    + * Base class for INSERT and UPSERT queries.
    + *
    + * @ingroup database
    + */
    +abstract class InsertBase extends Query {
    

    There's no real is-a relationship between InsertBase and Insert/Upsert. Insert and Upsert are not specializations of InsertBase. It's just for code sharing, really. But it has no 3rd party dependencies.

    That means it's a much better example of a trait than a base class. Let's convert it into a trait (InsertTrait?), and then use it in both Insert and Upsert.

    See:

    http://www.garfieldtech.com/blog/beyond-abstract

  3. +++ b/core/lib/Drupal/Core/Database/Query/InsertBase.php
    @@ -0,0 +1,179 @@
    +  /**
    +   * Prepares the placeholders for values that will be inserted.
    +   *
    +   * @return array
    +   *   An array of insert values.
    +   */
    +  protected function prepareInsertValues() {
    

    If we're breaking this logic out to a separate method, my knee-jerk pedant would suggest making it non-stateful. That is, it only uses two properties from $this: insertValues and defaultValues. And it doesn't modify either.

    So instead, let's pass those in as parameters and let __toString() pass those values in.

    Also, "prepare" doesn't tell me anything about what's going on here. What is it returning? It's returning the "values" portion of the query, no? Then it can probably be named getInsertPlaceholderFragment() (or osmething like that).

  4. +++ b/core/lib/Drupal/Core/Database/Query/Upsert.php
    @@ -0,0 +1,140 @@
    +  /**
    +   * Sets the unique fields to be used as conditions for this query.
    +   *
    +   * @param string|array $fields
    +   *   The name of the field(s) that form an unique key.
    +   *
    +   * @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.');
    +    }
    

    I'm skeptical about this. Why allow an array only to then disallow it? We can add the array/string mangling later just as easily, and telling people they can throw an array, oh wait JUST KIDDING! seems kind of rude. :-)

    Just allow the string only for now and call it a day. If we decide to add multi-key support later we can restore this handling.

  5. +++ b/core/lib/Drupal/Core/Database/Query/Upsert.php
    @@ -0,0 +1,140 @@
    +  public function preExecute() {
    

    Why does this need to be public? Are we calling it externally? (SelectQuery's preExecute() is public to support D7's half-arsed render caching, but I don't think it's needed for any other queries, is it?)

  6. +++ b/core/lib/Drupal/Core/Database/Query/Upsert.php
    @@ -0,0 +1,140 @@
    +  public function __toString() {
    +    // There is no generic cross-database way to implement UPSERT queries, each
    +    // driver must implement their own logic.
    +  }
    

    If that's the case, we can/should make this class abstract and declare this method abstract. That way PHP enforces this for us.

    And yes, I know I just recommended making something abstract instead of a trait. I'm scared, too... :-)

  7. +++ b/core/modules/system/src/Tests/Database/UpsertTest.php
    @@ -0,0 +1,70 @@
    +  public function testMergeInsert() {
    +    $connection = Database::getConnection();
    +    $num_records_before = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
    +
    +    $connection->upsert('test_people')
    +      ->key('job')
    +      ->fields(array(
    +        'job' => 'Presenter',
    +        'age' => 31,
    +        'name' => 'Tiffany',
    +      ))
    +      ->execute();
    +
    +    $num_records_after = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
    +    $this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
    +
    +    $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.');
    +  }
    +
    +  /**
    +   * 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();
    +
    +    $num_records_after = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
    +    $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
    +
    +    $person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
    +    $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
    +    $this->assertEqual($person->age, 31, 'Age set correctly.');
    +    $this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
    +  }
    

    These tests look awfully similar... Isn't the DB getting reset between test methods? (I've not looked at DatabaseTestBase in a long time.)

Also, I am absolutely in LOVE with the quality of the comments in the (rather hairy and not at all obvious) Postgres code here. Rock on!

chx’s picture

> Why allow an array only to then disallow it?

This was my idea and the point was to future proof it. However, the implementation slightly differs from my idea because I would've allowed only arrays to pass in. It did not occur to me we can just do string now and string|array later. If we are OK with that let's just do string for now.

> Why does this need to be public?

Because it was public on Insert, I think.

> class abstract and declare this method abstract.

class yes, __toString can't be abstract. PHP.

amateescu’s picture

Assigned: Crell » Unassigned
Status: Needs work » Needs review
Issue tags: -Needs subsystem maintainer review
StatusFileSize
new30 KB
new13.46 KB

Thanks, Larry, for the quick review!

  1. Insert queries are reusable to allow for batch import multi-insert statements. (Queue up 20 values() clauses, execute, queue up 20 more, etc.) Is that a valid use case for upserts?

    Yes, I think the same use case for Insert applies here as well.

    This is in the Postgres implementation only, so that would seem to create an inconsistency between drivers, no?

    Nope, the base Upsert::execute() method (which is inherited by both mysql and sqlite) does the same.

  2. Sure thing, converted to a trait.
  3. Changed the method to be non-stateful and renamed according to your suggestion :)
  4. Yes, let's go back to strings only and change to string|array when we actually need it.
  5. I can't find any outside usage of preExecute() for Insert queries so I changed it to protected on both Insert and Upsert.
  6. Like @chx mentioned above, we can't make __toString() abstract but we can do so for the class.
  7. Updated the tests with a better scenario where we actually use the update-or-insert functionality in the same query :)
Crell’s picture

PHP would beg to differ: http://3v4l.org/g4QHN

Aside from that, I think we're good here.

chx’s picture

StatusFileSize
new1.05 KB
new29.74 KB

I didn't look closely when amateescu got an error for abstract __toString; it turns out the problem is that Query already has an abstract __toString and you can't inherit abstract functions.

amateescu’s picture

StatusFileSize
new29.78 KB
new448 bytes

:)

Crell’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: +Needs change record, +Needs beta evaluation

Ahhh... That would do it, now wouldn't it. :-)

Code's good. We just need the paperwork done and this is commitable. Tagging accordingly.

chx’s picture

Issue summary: View changes
chx’s picture

Issue tags: -Needs beta evaluation
alexpott’s picture

Status: Reviewed & tested by the community » Needs work

This is really nice work. I've run the tests on postgres and sqlite - it's working nicely.

Given that the minimum postgres version is '9.1.2'; can't we use the single statement method described in http://www.the-art-of-web.com/sql/upsert/?

Also still "Needs change record"

+++ b/core/modules/system/src/Tests/Database/UpsertTest.php
@@ -0,0 +1,62 @@
+use Drupal\Core\Database\Query\Upsert;

Not used.

alexpott’s picture

I see @amateescu answered because of the race conditions - but similarly to the provided solution we just need to lock.

alexpott’s picture

Issue summary: View changes
Priority: Major » Critical

Being honest.

amateescu’s picture

Status: Needs work » Needs review
Issue tags: -Needs change record

Added a CR draft: https://www.drupal.org/node/2549311

Regarding the Postgres implementation, both chx and myself didn't consider writing another implementation a high priority task. The one from the current patch works and it's not slower than HEAD, and we can always improve it in a followup :)

amateescu’s picture

StatusFileSize
new29.74 KB
new451 bytes

Fixed the use statement.

amateescu’s picture

Issue tags: +Performance, +scalability

Let's be honest with the tags as well :)

alexpott’s picture

Well let's file the followup for #45 then. After that I think we're done here.

wim leers’s picture

Status: Needs review » Needs work

#45 addressed #42 AFAICT.

#45: it'd be nice if we had a follow-up to point to though.

EDIT: cross-posted with Alex :)

amateescu’s picture

Status: Needs work » Reviewed & tested by the community

Here it is: #2549323: Improve the Upsert query implementation for PostgreSQL.

Setting back to RTBC since that was the only feedback left.

alexpott’s picture

Status: Reviewed & tested by the community » Fixed

Committed c010a3a and pushed to 8.0.x. Thanks!

Thanks for adding the beta evaluation to the issue summary.

amateescu’s picture

Status: Fixed » Reviewed & tested by the community

Doesn't seem to be pushed yet..

  • alexpott committed c010a3a on 8.0.x
    Issue #2542776 by amateescu, chx, martin107, Crell: Add an Upsert class
    
alexpott’s picture

Status: Reviewed & tested by the community » Fixed
amateescu’s picture

Thanks! Published the change record.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.