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



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

/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();

$users_resource = $db->query('SELECT id, username FROM users');
while ($user = $users_resource->fetchArray())
{
	$username = $user['username'];

	// MySQL needs special characters double escaping for LIKE clauses
	if ($db->type() === 'mysql')
		$username = str_replace('\\', '\\\\', $username);

	$discussion_resource = $db->query('SELECT id, txt FROM discussions WHERE txt LIKE %like:username%', '@' . $username);
	while ($discussion = $discussion_resource->fetchArray())
	{
		$txt = $discussion['txt'];
		$txt = str_replace('@' . $user['username'], '@[' . $user['id'] . ']', $txt);
		$db->query('UPDATE discussions SET txt = str:txt WHERE id eq:int:id', $txt, $discussion['id']);
	}
}

DB_UPDATE_FILE
);


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