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



$migrations->Run('01_fix_version_ids_in_documents.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();

$chunk_size = 500;
$offset = 0;

// get the ids of all documents that need their latest_version_id updating
$result = $db->query('SELECT d1.id FROM ERMS_data d1 LEFT JOIN ERMS_data d2 ON d2.id=d1.latest_version_id WHERE d1.latest_version_id!=d1.primary_version_id AND d1.doc_id!=d2.doc_id');
$ids = $result->fetchAllValues();

// paginate results in case there's a lot of documents to change over, with a hard limit.
$hard_loop_stop = 100;
while($hard_loop_stop > 0)
{
	$id_chunk = []; // reset to empty;
	$id_chunk = array_slice($ids, $offset, $chunk_size);

	if (count($id_chunk) == 0)
	{
		break;
	}

	$db->query('UPDATE ERMS_data SET latest_version_id=primary_version_id WHERE id IN in:int:id_chunk', $id_chunk);

	$offset += $chunk_size;
	$hard_loop_stop--;
}







DB_UPDATE_FILE
);


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