Skip to main content
100%

How to compile an INSERT ... ON DUPLICATE KEY UPDATE with SQL Alchemy with support for a bulk insert.

✓ Published0🌍 Public
Aadima
Last edited Dec 5, 2013
Created on Jul 20, 2016

This example demonstrates a custom SQLAlchemy construct that compiles an `INSERT ... ON DUPLICATE KEY UPDATE` statement for MySQL, enabling efficient bulk upserts. The `Upsert` class extends `sqlalchemy.sql.expression.Insert`, and a `@compiles` decorator registers a MySQL-specific compiler function that transforms the insert into an upsert by appending the `ON DUPLICATE KEY UPDATE` clause with `VALUES()` references. The code detects auto-increment primary keys to use `LAST_INSERT_ID()` for correct ID handling, and it supports both single-row and multi-row parameter sets.

AI-generated description

Similar vizzes