/**
  * Cleanup orphaned records in the _versions table
  *
  * @param string $baseTable base table to use as authoritative source of records
  * @param string $childTable Sub-table to clean orphans from
  */
 protected function cleanupVersionedOrphans($baseTable, $childTable)
 {
     // Skip if child table doesn't exist
     if (!DB::get_schema()->hasTable($childTable)) {
         return;
     }
     // Skip if tables are the same
     if ($childTable === $baseTable) {
         return;
     }
     // Select all orphaned version records
     $orphanedQuery = SQLSelect::create()->selectField("\"{$childTable}\".\"ID\"")->setFrom("\"{$childTable}\"");
     // If we have a parent table limit orphaned records
     // to only those that exist in this
     if (DB::get_schema()->hasTable($baseTable)) {
         $orphanedQuery->addLeftJoin($baseTable, "\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\"\n\t\t\t\t\tAND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\"")->addWhere("\"{$baseTable}\".\"ID\" IS NULL");
     }
     $count = $orphanedQuery->count();
     if ($count > 0) {
         DB::alteration_message("Removing {$count} orphaned versioned records", "deleted");
         $ids = $orphanedQuery->execute()->column();
         foreach ($ids as $id) {
             DB::prepared_query("DELETE FROM \"{$childTable}\" WHERE \"ID\" = ?", array($id));
         }
     }
 }