In Rails 8.1, why does upsert_all code ported from PostgreSQL break on MySQL, and which row does MySQL update without unique_by:?
answer
- unique_by: raises ArgumentError on MySQL
- ON DUPLICATE KEY UPDATE, not ON CONFLICT
- any unique index can trigger the update
- returning: only on MariaDB 10.5+
- keep one unique key per upserted row
basics
~20 sMySQL has no conflict target, so the MySQL adapters raise ArgumentError for unique_by: and generate ON DUPLICATE KEY UPDATE. That fires on a clash with the primary key or any unique index, so with two unique indexes MySQL may update a different row than intended.
solid answer
~40 sOn PostgreSQL, `upsert_all(rows, unique_by: [:room_id, :night])` compiles to `ON CONFLICT (room_id, night) DO UPDATE`, naming the index that decides a duplicate. MySQL has no such clause: `supports_insert_conflict_target?` is false, so passing `unique_by:` raises `ArgumentError` ("... does not support :unique_by"), and Rails emits `ON DUPLICATE KEY UPDATE` instead. MySQL applies that update when the new row collides with the primary key or **any** unique index. If `room_nights` has unique indexes on both `(room_id, night)` and `hold_token`, a row whose token matches an existing hold for another room updates that other row. `returning:` also raises on MySQL; only MariaDB 10.5 and later support it. The fix is design: make sure exactly one unique key can collide for the rows you upsert, or upsert per row with a lookup.
go deeper
Recall that MySQL does not accept unique_by: or returning: in Rails bulk upserts.
Explain ON DUPLICATE KEY UPDATE versus ON CONFLICT, and that any unique index can trigger the MySQL update.
Redesign upserted tables so only one unique key can collide, and test bulk writes against the real engine.
Weigh bulk-write speed against correctness when an engine move changes upsert semantics across many jobs.
## The code that worked on PostgreSQL A hotel-reservation app keeps one row per room per night in `room_nights`, holding the price and availability. A nightly job pushes channel-manager rates with a bulk upsert: ```ruby RoomNight.upsert_all(rows, unique_by: [:room_id, :night], returning: [:id]) ``` On PostgreSQL this becomes `INSERT ... ON CONFLICT (room_id, night) DO UPDATE ... RETURNING id`. `unique_by:` tells PostgreSQL which unique index is the conflict target, and every other unique index still raises if violated. (How `insert_all` and `upsert_all` work in general belongs to the bulk-write topic; this answer is about what MySQL changes.) ## What the MySQL adapters do with it | Option | PostgreSQL | MySQL (`mysql2` or `trilogy`) | MariaDB 10.5+ | |---|---|---|---| | `unique_by:` | conflict target in `ON CONFLICT (...)` | `ArgumentError`: does not support `:unique_by` | `ArgumentError` | | no `unique_by:` | primary key is the target | `ON DUPLICATE KEY UPDATE` | `ON DUPLICATE KEY UPDATE` | | `returning:` | supported | `ArgumentError`: does not support `:returning` | supported | The checks live in `ActiveRecord::InsertAll`: it asks the adapter `supports_insert_conflict_target?` (false for MySQL and MariaDB) and `supports_insert_returning?` (true only for MariaDB 10.5 and later). So the ported job fails before any SQL runs, which is the good outcome. ## The dangerous part: any unique key fires Removing `unique_by:` makes the job run, and that is where the real change hides. MySQL's `ON DUPLICATE KEY UPDATE` has no target: if the inserted row would duplicate the value of the **primary key or any unique index**, MySQL updates the existing row that holds that value. Suppose `room_nights` has two unique indexes: 1. `(room_id, night)`, the natural key the job means; 2. `hold_token`, a unique token for a temporary hold. A pushed row for room 12 on 1 March, a night that has no row yet, carries `hold_token: "H-77"`, and that token already belongs to room 15's row for the same night. On PostgreSQL with `unique_by: [:room_id, :night]`, the token clash raises `RecordNotUnique`. On MySQL, the clash on `hold_token` triggers the update, and **room 15's row** receives room 12's rate. When a row collides with different existing rows through different unique indexes, which one MySQL updates is MySQL's rule, and its own documentation warns against relying on it. ## How to make it safe - **One collidable key.** For rows you upsert, make sure only one unique index can collide: leave `hold_token` out of the upserted columns (it is `NULL` for pushed rates), or move holds to their own table. - **Pre-check or split.** If several unique keys are unavoidable, look up existing rows first and use `insert_all` for new ones and `update_all` or per-row updates for existing ones. - **Per-row fallback.** For small batches, `create_or_find_by` per row keeps Active Record's own uniqueness handling. - **No `returning:`.** On MySQL, re-read the rows by their natural key after the upsert if you need ids; on MariaDB 10.5+ `returning:` works. - **Test against MySQL.** A test suite that runs on PostgreSQL proves nothing about this behaviour. ## Testing the behaviour 1. Run the upsert job's tests against MySQL in CI, with the same unique indexes as production. 2. Add a test that upserts a row colliding on the secondary unique key and asserts what happens, so a future index change cannot silently alter the outcome. 3. Assert on row contents after the upsert, not on the method's return value, since MySQL returns no rows. ## Other differences worth naming - `insert_all` (skip duplicates) compiles to `ON DUPLICATE KEY UPDATE <column>=<column>`, a no-op update, so it also skips rows that collide on **any** unique index. - MySQL reports an upsert that updated a row differently from one that inserted, so "rows affected" counts do not equal the number of input rows.
- Why does insert_all on MySQL skip a row that collides on an unrelated unique index, when on PostgreSQL the same call would not?On MySQL, Rails compiles the skip behaviour to `ON DUPLICATE KEY UPDATE <col>=<col>`, a no-op update that MySQL applies on a collision with any unique key. On PostgreSQL it compiles to `ON CONFLICT ... DO NOTHING`, and `unique_by:` can name the one index that should count.
- How do you get ids back from a bulk upsert in a Rails app on MySQL?You cannot ask for them: `returning:` raises `ArgumentError` because MySQL lacks `INSERT ... RETURNING` (MariaDB 10.5+ has it). Re-select the rows by their natural key after the upsert, for example `RoomNight.where(room_id: ids, night: nights)`.
- Expects unique_by: to work on MySQL like on PostgreSQL
- Thinks ON DUPLICATE KEY UPDATE only checks the primary key
- Removes unique_by: and assumes the semantics stayed the same
- Relies on returning: ids from upsert_all on MySQL
- Trusts a PostgreSQL test run to cover MySQL upsert behaviour