MDL-58593 database: More efficiently track issued key names
This commit is contained in:
@@ -1074,8 +1074,11 @@ abstract class sql_generator {
|
||||
// along all the request life, but never to return cached results
|
||||
// We need this because sql statements are created before executing
|
||||
// them, hence names doesn't exist "physically" yet in DB, so we need
|
||||
// to known which ones have been used
|
||||
static $used_names = array();
|
||||
// to known which ones have been used.
|
||||
// We track all the keys used, and the previous counters to make subsequent creates faster.
|
||||
// This may happen a lot with things like bulk backups or restores.
|
||||
static $usednames = array();
|
||||
static $previouscounters = array();
|
||||
|
||||
// Use standard naming. See http://docs.moodle.org/en/XMLDB_key_and_index_naming
|
||||
$tablearr = explode ('_', $tablename);
|
||||
@@ -1094,17 +1097,26 @@ abstract class sql_generator {
|
||||
$maxlengthwithoutsuffix = $this->names_max_length - strlen($suffix) - ($suffix ? 1 : 0);
|
||||
$namewithsuffix = substr($name, 0, $maxlengthwithoutsuffix) . ($suffix ? ('_' . $suffix) : '');
|
||||
|
||||
// If the calculated name is in the cache, or if we detect it by introspecting the DB let's modify if
|
||||
$counter = 1;
|
||||
while (in_array($namewithsuffix, $used_names) || $this->isNameInUse($namewithsuffix, $suffix, $tablename)) {
|
||||
if (isset($previouscounters[$name])) {
|
||||
// If we have a counter stored, we will need to modify the key to the next counter location.
|
||||
$counter = $previouscounters[$name] + 1;
|
||||
$namewithsuffix = substr($name, 0, $maxlengthwithoutsuffix - strlen($counter)) .
|
||||
$counter . ($suffix ? ('_' . $suffix) : '');
|
||||
} else {
|
||||
$counter = 1;
|
||||
}
|
||||
|
||||
// If the calculated name is in the cache, or if we detect it by introspecting the DB let's modify it.
|
||||
while (isset($usednames[$namewithsuffix]) || $this->isNameInUse($namewithsuffix, $suffix, $tablename)) {
|
||||
// Now iterate until not used name is found, incrementing the counter
|
||||
$counter++;
|
||||
$namewithsuffix = substr($name, 0, $maxlengthwithoutsuffix - strlen($counter)) .
|
||||
$counter . ($suffix ? ('_' . $suffix) : '');
|
||||
}
|
||||
|
||||
// Add the name to the cache
|
||||
$used_names[] = $namewithsuffix;
|
||||
// Add the name to the cache. Using key look with isset because it is much faster than in_array.
|
||||
$usednames[$namewithsuffix] = true;
|
||||
$previouscounters[$name] = $counter;
|
||||
|
||||
// Quote it if necessary (reserved words)
|
||||
$namewithsuffix = $this->getEncQuoted($namewithsuffix);
|
||||
|
||||
Reference in New Issue
Block a user