Search code examples
mysqlamazon-web-servicespdodatabase-replicationlast-insert-id

Will PDO's LastInsertID Break AWS Replication?


Does the PDO lastinsertid function use MySQL's last_insert_id function?

I'm particularly interested in replication with AWS and per the AWS manual using some MySQL functions break replication:

Other common situations that can cause replication errors include the following:...Using unsafe nondeterministic queries

The mysql manual states that the functions I'm using aren't actually unsafe though:

Nondeterministic functions not considered unsafe

I plan to rewrite my now() usages but am not sure how I can avoid the last_insert_id since PDO, not I, am querying that. I can't do a separate select because it is likely an insert was run in parallel and I'll get back the wrong id.


Solution

  • MySQL's LAST_INSERT_ID() function, the various bindings (like PDO's) and the underlying functionality are deterministic. You can use them with confidence.

    For example this is deterministic and will work everywhere.

      INSERT INTO master (address, town) VALUES('150 Broadway', 'New York');
      INSERT INTO detail (master_id, item) VALUES (LAST_INSERT_ID(), 'pepperoni pizza');
    

    This is not. This is the sort of thing you're warned against.

      INSERT INTO master (address, town) VALUES('150 Broadway', 'New York');
      SELECT @id := MAX(master_id) FROM master;   /* bad bad bad */
      INSERT INTO detail (master_id, item) VALUES (@id + 1 'pepperoni pizza');