refactor: Replace custom queries with dbDeleteOrphans(). (#7862)

* Replace custom queries with dbDeleteOrphans().
Generalize dbDeleteOrphans() a bit more.  Allow for multiple tables and custom key pairs.

* fix whitespace
This commit is contained in:
Tony Murray
2017-12-06 16:44:23 -06:00
committed by Neil Lathwood
parent daa0773f48
commit 8ab0b2bffd
4 changed files with 34 additions and 17 deletions

View File

@@ -298,22 +298,44 @@ function dbDelete($table, $where = null, $parameters = array())
/**
* Delete orphaned entries from a table that no longer have a parent in parent_table
* Format of parents array is as follows table.table_key_column<.target_key_column>
*
* @param string $parent_table
* @param string $child_table
* @param string $id_column
* @param string $target_table The table to delete entries from
* @param array $parents an array of parent tables to check.
* @return bool|int
*/
function dbDeleteOrphans($parent_table, $child_table, $id_column)
function dbDeleteOrphans($target_table, $parents)
{
global $database_link;
$time_start = microtime(true);
$sql = "DELETE C FROM `$child_table` C";
$sql .= " LEFT JOIN `$parent_table` P USING (`$id_column`)";
$sql .= " WHERE P.`$id_column` IS NULL";
if (empty($parents)) {
// don't delete all entries if parents is missing
return false;
}
$result = dbQuery($sql, array());
$target_table = mres($target_table);
$sql = "DELETE T FROM `$target_table` T";
$where = array();
foreach ((array)$parents as $parent) {
$parent_parts = explode('.', mres($parent));
if (count($parent_parts) == 2) {
list($parent_table, $parent_column) = $parent_parts;
$target_column = $parent_column;
} elseif (count($parent_parts) == 3) {
list($parent_table, $parent_column, $target_column) = $parent_parts;
} else {
// invalid input
return false;
}
$sql .= " LEFT JOIN `$parent_table` ON `$parent_table`.`$parent_column` = T.`$target_column`";
$where[] = " `$parent_table`.`$parent_column` IS NULL";
}
$query = "$sql WHERE" . implode(' AND', $where);
$result = dbQuery($query, array());
recordDbStatistic('delete', $time_start);
if ($result) {