<?php
$_db_migration_to = '24.04'; // 7.3 RC
if (!isset($migrations) || !is_object($migrations))
	die("This file cannot be executed directly");
$migrations->CheckValid($_db_migration_to);
//===========================================================================================



$migrations->Run('01_remove_orphan_reports.php', <<<'DB_UPDATE_FILE'
<?php

$db = $migrations->GetDb();

// Gets the ids of the projects currently in the database.
$res = $db->query("SELECT id FROM hd_project");
$existing_project_ids = $res->fetchAllValues();

if (count($existing_project_ids) == 0)
	$existing_project_ids = array(-1);

// Ids of the reports belonging to non-existing (already deleted) projects.
$orphan_report_ids = $db->query("SELECT id FROM hd_report WHERE project_id NOT IN in:int:project_ids", $existing_project_ids);

while (list($orphan_report_id) = $orphan_report_ids->fetchRow())
{	// Delete the orphan project and any data associated with it.
	$db->query("DELETE FROM hd_report WHERE id=int:id", $orphan_report_id);
	$db->query("DELETE FROM hd_report_data WHERE report_id=int:id", $orphan_report_id);
	$db->query("DELETE FROM hd_report_custom_data WHERE report_id=int:id", $orphan_report_id);
}

DB_UPDATE_FILE
);


$migrations->Run('02_remove_orphan_drafts.php', <<<'DB_UPDATE_FILE'
<?php

$db = $migrations->GetDb();

// Gets the ids of the projects currently in the database.
$res = $db->query("SELECT id FROM hd_project");
$existing_project_ids = $res->fetchAllValues();

if (count($existing_project_ids) == 0)
	$existing_project_ids = array(-1);

// Delete all orphan draft issues (Draft issues left in the database after the parent project was deleted).
$db->query("DELETE FROM hd_issue_draft WHERE project_id NOT IN in:int:project_ids", $existing_project_ids);

DB_UPDATE_FILE
);


//===========================================================================================
$migrations->SetVersion('24.04');
