Is there an elegant way to do an INSERT ... ON DUPLICATE KEY UPDATE in SQLAlchemy? I mean something with a syntax similar to inserter.insert().execute(list_of_dictionaries) ?
Is there an elegant way to do an INSERT … ON DUPLICATE KEY UPDATE
Share
ON DUPLICATE KEY UPDATEpost version-1.2 for MySQLThis functionality is now built into SQLAlchemy for MySQL only. somada141’s answer below has the best solution:
https://stackoverflow.com/a/48373874/319066
ON DUPLICATE KEY UPDATEin the SQL statementIf you want the generated SQL to actually include
ON DUPLICATE KEY UPDATE, the simplest way involves using a@compilesdecorator.The code (linked from a good thread on the subject on reddit) for an example can be found on github:
But note that in this approach, you have to manually create the append_string. You could probably change the append_string function so that it automatically changes the insert string into an insert with ‘ON DUPLICATE KEY UPDATE’ string, but I’m not going to do that here due to laziness.
ON DUPLICATE KEY UPDATEfunctionality within the ORMSQLAlchemy does not provide an interface to
ON DUPLICATE KEY UPDATEorMERGEor any other similar functionality in its ORM layer. Nevertheless, it has thesession.merge()function that can replicate the functionality only if the key in question is a primary key.session.merge(ModelObject)first checks if a row with the same primary key value exists by sending aSELECTquery (or by looking it up locally). If it does, it sets a flag somewhere indicating that ModelObject is in the database already, and that SQLAlchemy should use anUPDATEquery. Note that merge is quite a bit more complicated than this, but it replicates the functionality well with primary keys.But what if you want
ON DUPLICATE KEY UPDATEfunctionality with a non-primary key (for example, another unique key)? Unfortunately, SQLAlchemy doesn’t have any such function. Instead, you have to create something that resembles Django’sget_or_create(). Another StackOverflow answer covers it, and I’ll just paste a modified, working version of it here for convenience.