Retrieve schema to form full tablename and construct sql statements correctly in thirdparty merge service

This commit is contained in:
Julie Lenaerts 2025-05-20 12:38:24 +02:00
parent b04f0a9aa4
commit 246546b313

View File

@ -52,32 +52,33 @@ class ThirdpartyMergeService
}
$tableName = $meta->getTableName();
$schema = $meta->getSchemaName();
$fullTableName = $this->getFullTableName($tableName, $schema);
foreach ($meta->getAssociationMappings() as $assoc) {
if (ThirdParty::class !== $assoc['targetEntity']) {
continue;
}
// phpstan wants boolean for if condition
if (($assoc['type'] & ClassMetadata::TO_ONE) !== 0) {
$joinColumn = $meta->getSingleAssociationJoinColumnName($assoc['fieldName']);
$suffix = (ThirdParty::class === $assoc['sourceEntity']) ? 'chill_3party.' : '';
$queries[] = [
'sql' => "UPDATE {$suffix}{$tableName} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete",
'sql' => "UPDATE {$fullTableName} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete",
'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()],
];
} elseif (ClassMetadata::MANY_TO_MANY === $assoc['type'] && isset($assoc['joinTable'])) {
$joinTable = $assoc['joinTable']['name'];
$prefix = null !== ($assoc['joinTable']['schema'] ?? null) ? $assoc['joinTable']['schema'].'.' : '';
$joinSchema = $assoc['joinTable']['schema'] ?? null;
$fullJoinTable = $this->getFullTableName($joinTable, $joinSchema);
$joinColumn = $assoc['joinTable']['inverseJoinColumns'][0]['name'];
$queries[] = [
'sql' => "UPDATE {$prefix}{$joinTable} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete AND NOT EXISTS (SELECT 1 FROM {$prefix}{$joinTable} WHERE {$joinColumn} = :toKeep)",
'sql' => "UPDATE {$fullJoinTable} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete AND NOT EXISTS (SELECT 1 FROM {$fullJoinTable} WHERE {$joinColumn} = :toKeep)",
'params' => ['toDelete' => $toDelete->getId(), 'toKeep' => $toKeep->getId()],
];
$queries[] = [
'sql' => "DELETE FROM {$joinTable} WHERE {$joinColumn} = :toDelete",
'sql' => "DELETE FROM {$fullJoinTable} WHERE {$joinColumn} = :toDelete",
'params' => ['toDelete' => $toDelete->getId()],
];
}
@ -104,4 +105,27 @@ class ThirdpartyMergeService
],
];
}
// Helper method to retrieve full table name of the different associations
// (e.g. "chill_3party.third_party" or "public.chill_3party.third_party")
//
// If the table name is already schema-qualified, it is returned as-is.
//
// If the table name is not schema-qualified, it is prefixed with the
// schema name of the target entity (e.g. "public.chill_3party.third_party").
//
// If the table name is not schema-qualified and the target entity has no
// schema name, the table name is prefixed with "public".
private function getFullTableName(string $tableName, ?string $schema): string
{
if ($schema !== null) {
return "{$schema}.{$tableName}";
}
if (str_contains($tableName, '.')) {
return $tableName;
}
return "public.{$tableName}";
}
}