Skip to content

Commit

Permalink
feat(ModuleInstaller): Add method to rename tables in the DB
Browse files Browse the repository at this point in the history
  • Loading branch information
Hipska committed Jul 22, 2024
1 parent 0ede071 commit f91ca34
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
43 changes: 43 additions & 0 deletions setup/moduleinstaller.class.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,47 @@ public static function MoveColumnInDB($sOrigTable, $sOrigColumn, $sDstTable, $sD
CMDBSource::CacheReset($sDstTable);
}

/**
* Rename a table providing:
* - The original name exists
* - The destination name does not exist
*
* @param string $sOrigTable
* @param string $sDstTable
*
* @return void
* @throws CoreException
* @throws CoreUnexpectedValue
* @throws MySQLException
*/
public static function RenameTableInDB(string $sOrigTable, string $sDstTable)
{
if ($sOrigTable == $sDstTable)
{
throw new CoreUnexpectedValue("Origin table and destination table are the same");
}

if (!MetaModel::DBExists(false))
{
// Install from scratch, no migration
return;
}

if (!CMDBSource::IsTable($sOrigTable))
{
SetupLog::Warning(sprintf('Rename table in DB - Origin table %s doesn\'t exist', $sOrigTable));
return;
}

if (CMDBSource::IsTable($sDstTable))
{
SetupLog::Warning(sprintf('Rename table in DB - Destination table %s already exists', $sDstTable));
return;
}

$sQueryRename = sprintf(/** @lang MariaDB */ "RENAME TABLE `%s` TO `%s`;", $sOrigTable, $sDstTable);
CMDBSource::Query($sQueryRename);

CMDBSource::CacheReset($sOrigTable);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,30 @@ public function testMoveColumnInDB_MoveMultipleTable(): void
$this->assertEquals('from table 2', $sFromTable2Data, "Data was not moved as expected");
}

/**
* Test that the table has been renamed
*
* @covers ModuleInstallerAPI::RenameTableInDB
*
* @return void
* @throws \CoreException
* @throws \MySQLException
*/
public function testRenameTableInDB()
{
$sOrigTable = MetaModel::DBGetTable('Person');
$aOrigTableInfo = CMDBSource::GetTableInfo($sOrigTable);
$this->assertNotEmpty($aOrigTableInfo, 'Origin table does not exist');

$sDstTable = static::$sWorkTable;
$this->assertFalse(CMDBSource::IsTable($sDstTable), 'Work table already exists');

ModuleInstallerAPI::RenameTableInDB($sOrigTable, $sDstTable);

$this->assertEquals($aOrigTableInfo, CMDBSource::GetTableInfo($sDstTable), 'Table was not renamed');

// Revert
ModuleInstallerAPI::RenameTableInDB($sDstTable, $sOrigTable);
$this->assertEquals($aOrigTableInfo, CMDBSource::GetTableInfo($sOrigTable));
}
}

0 comments on commit f91ca34

Please sign in to comment.