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.
- 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
- 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
| 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. |
| Comment | File | Size | Author |
|---|---|---|---|
| #46 | interdiff.txt | 451 bytes | amateescu |
| #46 | 2542776-46.patch | 29.74 KB | amateescu |
Comments
Comment #1
dawehnerIt 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.
Comment #2
chx commentedComment #3
chx commentedComment #4
chx commentedComment #5
chx commentedComment #6
chx commentedComment #7
chx commentedComment #8
berdirThis is probably at least major, considering that it is meant to be used to fix a critical?
Comment #9
chx commentedProbably the parent should be postponed and this raised to critical.
Comment #10
martin107 commentedWhile keeping up with this issue - I noticed a couple of small inconsequential nits - might as well fix in public
Comment #11
chx commentedThanks. 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.
Comment #12
martin107 commentedAh 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.
Comment #13
chx commentedSorry 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:
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?
Comment #14
chx commentedBrutally simplified. Nothing is supported beyond INSERT ON CONFLICT REPLACE. No fields, no expressions, nothing.
Comment #15
chx commentedComment #17
amateescu commentedFinally 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.
Comment #18
amateescu commentedHere'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?Comment #19
olli commentedGreat 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?
Note that this deleteMultiple creates the table if it doesn't exist.
Comment #20
chx commented> 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.
Comment #21
amateescu commentedTurns 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:
It's optimized for setMultiple() but I don't see any reason to not use it for set() as well.
Probably so, in a followup :)
@chx:
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.
Comment #22
amateescu commentedI 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.
Comment #23
berdirIs 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 :)
Missing docs but I'm sure you know that ;)
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).
Comment #24
chx commentedMySQL 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/
Comment #25
amateescu commented@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 aexecuteHelper()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:
Without patch:
Comment #27
amateescu commentedFixed the methods copied from Upsert by using the ones from Insert.
Comment #28
amateescu commentedI did a few more drush site-installs on postgres with the patch applied and I get very similar results to HEAD:
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.
Comment #29
amateescu commentedDiscussed 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 :)
Comment #30
chx commentedTwo 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.
Comment #31
amateescu commentedFixed #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).
Comment #32
amateescu commentedI shouldn't post patches in a rush. We need a sign-off from a db maintainer now :)
Comment #33
Crell commentedThis is looking really good, folks. Nice work! Some things to fix, though:
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?
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
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).
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.
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?)
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... :-)
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!
Comment #34
chx commented> 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.
Comment #35
amateescu commentedThanks, Larry, for the quick review!
Yes, I think the same use case for Insert applies here as well.
Nope, the base
Upsert::execute()method (which is inherited by both mysql and sqlite) does the same.string|arraywhen we actually need it.preExecute()for Insert queries so I changed it to protected on both Insert and Upsert.__toString()abstract but we can do so for the class.Comment #36
Crell commentedPHP would beg to differ: http://3v4l.org/g4QHN
Aside from that, I think we're good here.
Comment #37
chx commentedI 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.
Comment #38
amateescu commented:)
Comment #39
Crell commentedAhhh... That would do it, now wouldn't it. :-)
Code's good. We just need the paperwork done and this is commitable. Tagging accordingly.
Comment #40
chx commentedComment #41
chx commentedComment #42
alexpottThis 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"
Not used.
Comment #43
alexpottI see @amateescu answered because of the race conditions - but similarly to the provided solution we just need to lock.
Comment #44
alexpottBeing honest.
Comment #45
amateescu commentedAdded 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 :)
Comment #46
amateescu commentedFixed the use statement.
Comment #47
amateescu commentedLet's be honest with the tags as well :)
Comment #48
alexpottWell let's file the followup for #45 then. After that I think we're done here.
Comment #49
wim leers#45 addressed #42 AFAICT.
#45: it'd be nice if we had a follow-up to point to though.
EDIT: cross-posted with Alex :)
Comment #50
amateescu commentedHere it is: #2549323: Improve the Upsert query implementation for PostgreSQL.
Setting back to RTBC since that was the only feedback left.
Comment #51
alexpottCommitted c010a3a and pushed to 8.0.x. Thanks!
Thanks for adding the beta evaluation to the issue summary.
Comment #52
amateescu commentedDoesn't seem to be pushed yet..
Comment #54
alexpottComment #55
amateescu commentedThanks! Published the change record.