Question : InnoDB engine reuses auto_increment IDs !!

I've run into a problem with the InnoDB engine: it loses track of the next number for auto_increment columns after server restart. And that may cause IDs of deleted rows to be reassigned to new rows.

This is really a problem for my web application: some tables have references to other tables. And if deleted IDs get reused for new records, then those references suddenly point to other records with new data instead of to the deleted rows. This is very confusing and can lead to big, big problems with database consistency.

Every table in my database has a primary key column named "ID", which is defined as auto_increment. And I relied on the assumption that that would ensure unique primary keys for all database records.

I've read that MyISAM does not suffer from this, but that engine misses some features that I need, like eg. row-level locking and transactions.

How can I prevent losing track of the highest new autonumber value after server restarts, so that IDs of deleted rows don't get reassigned?

Answer : InnoDB engine reuses auto_increment IDs !!

I don't know how a web application would know if the db was restarted except if you store something like the pid of the mysql instance on disk every time you access the page.

OK, now that I think of it, why not do this: Every time you run the application, save the last_insert_id() to a local file.

Before you run an insert, check that file and compare it to the next auto_increment number

SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE
      TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'whatever'

Then, if the local file has the same or greater, set auto_increment to one more than the greater number. If not, don't worry.
Random Solutions  
 
programming4us programming4us