Skip to content

Commit

Permalink
FIX Correctly clear table and reset auto increment
Browse files Browse the repository at this point in the history
  • Loading branch information
GuySartorelli committed Aug 13, 2024
1 parent 7b91207 commit 2a30443
Showing 1 changed file with 4 additions and 18 deletions.
22 changes: 4 additions & 18 deletions src/ORM/Connect/MySQLDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -569,23 +569,9 @@ public function clearTable($table)
// Not simply using "TRUNCATE TABLE \"$table\"" because DELETE is a lot quicker
// than TRUNCATE which is very relevant during unit testing. Using TRUNCATE will lead to an
// approximately 50% increase it the total time of running unit tests.
//
// Using max(ID) to determine if the table should reset its auto-increment, rather than using
// SELECT "AUTO_INCREMENT" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
// after deleting from the table, because in MySQL 8, under certain conditions, notably
// when running behat, sometimes the auto-increment was being reset to 2 for unknown reasons
$self = $this;
$fn = function () use ($self, $table) {
$maxID = $self->query("SELECT MAX(ID) FROM \"$table\"")->value();
$self->query("DELETE FROM \"$table\"");
if ($maxID > 0) {
$self->query("ALTER TABLE \"$table\" AUTO_INCREMENT = 1");
}
};
if ($this->supportsTransactions()) {
$this->withTransaction($fn);
} else {
$fn();
}
$this->query("DELETE FROM \"$table\"");
// Don't check the current AUTO_INCREMENT value first, because table stats are cached from
// MySQL 8.0 (for a full day by default) and will likely be out of date.
$this->query("ALTER TABLE \"$table\" AUTO_INCREMENT = 1")->value();
}
}

0 comments on commit 2a30443

Please sign in to comment.