Skip to content

Instantly share code, notes, and snippets.

@jreviews
Created June 10, 2024 14:48
Show Gist options
  • Save jreviews/8ae64cb384808b0ee80c8b5604f855af to your computer and use it in GitHub Desktop.
Save jreviews/8ae64cb384808b0ee80c8b5604f855af to your computer and use it in GitHub Desktop.
WordPress dbDelta mu-plugin patch to avoid unnecessary queries
<?php
/**
* /wp-content/mu-plugins/dbdelta-patch-queries.php
* Patches queries before they are processed by dbDelta to ensure that it doesn't run unnecessary queries
* On some setups, not specifying TINYINT length always causes the query to run a delta,
* so forcing it to length 4 when it's not specified
*/
add_filter('dbdelta_queries', function($queries) {
$patterns = [
'/\b(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT|FLOAT|DOUBLE|DECIMAL|DATE|DATETIME|TIMESTAMP|TIME|YEAR|CHAR|VARCHAR|BINARY|VARBINARY|TINYBLOB|BLOB|MEDIUMBLOB|LONGBLOB|TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|ENUM|SET|GEOMETRY|POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION|JSON)\b(\((\d+)\))?/i'
];
foreach ($queries as &$query) {
// Convert column types to lowercase and standardize TINYINT length
$query = preg_replace_callback($patterns[0], function($matches) {
$type = strtolower($matches[1]);
if ($type === 'tinyint') {
return isset($matches[3]) ? 'tinyint(' . $matches[3] . ')' : 'tinyint(4)';
}
return isset($matches[2]) ? $type . $matches[2] : $type;
}, $query);
// Remove consecutive spaces
while (strpos($query, ' ') !== false) {
$query = str_replace(' ', ' ', $query);
}
// Remove spaces after commas, messing up enums
$query = str_replace(', ', ',', $query);
$query = str_replace('UNSIGNED', 'unsigned', $query);
$query = str_replace('NOT NULL', 'not null', $query);
$query = str_replace('NULL', 'null', $query);
$query = str_replace('DEFAULT', 'default', $query);
}
return $queries;
}, 10, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment