From 1580e7fae8e99ba9f28c181bcf7400595ef5dba6 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Tue, 13 Aug 2024 16:31:48 +1200 Subject: [PATCH] FIX Run ANALYZE TABLE before fetching table stats --- src/ORM/Connect/MySQLDatabase.php | 35 +++++++++++++------------------ 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/src/ORM/Connect/MySQLDatabase.php b/src/ORM/Connect/MySQLDatabase.php index 8e9e0585184..50f1c8d3de9 100644 --- a/src/ORM/Connect/MySQLDatabase.php +++ b/src/ORM/Connect/MySQLDatabase.php @@ -566,26 +566,21 @@ public function random() */ 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\""); + + // Check if resetting the auto-increment is needed + + // First run ANALYZE TABLE to reset table stats which are cached for 24 hours by + // default in MySQL 8 + $this->query("ANALYZE TABLE \"$table\""); + + $autoIncrement = $this->preparedQuery( + 'SELECT "AUTO_INCREMENT" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?', + [ $this->getSelectedDatabase(), $table] + )->value(); + + if ($autoIncrement > 1) { + $this->query("ALTER TABLE \"$table\" AUTO_INCREMENT = 1"); } } }