Enforce unique constraint on relation activity storedobject

This commit is contained in:
LenaertsJ 2024-12-05 12:37:39 +00:00 committed by Julien Fastré
parent 486ad3bb41
commit b0f1cf272f
3 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,5 @@
kind: Fixed
body: Enforce unique contraint on activity storedobject
time: 2024-12-05T13:37:02.635977414+01:00
custom:
Issue: "337"

View File

@ -84,6 +84,11 @@ class Activity implements AccompanyingPeriodLinkedWithSocialIssuesEntityInterfac
*/
#[Assert\Valid(traverse: true)]
#[ORM\ManyToMany(targetEntity: StoredObject::class, cascade: ['persist'])]
#[ORM\JoinTable(
name: 'activity_storedobject',
joinColumns: new ORM\JoinColumn(name: 'activity_id', referencedColumnName: 'id', nullable: false),
inverseJoinColumns: new ORM\InverseJoinColumn(name: 'storedobject_id', referencedColumnName: 'id', unique: true, nullable: false)
)]
private Collection $documents;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TIME_MUTABLE, nullable: true)]

View File

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\Migrations\Activity;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20241202173942 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add a unique constraint on the storedobject linked to an activity';
}
public function up(Schema $schema): void
{
$this->addSql(
'WITH duplicate_activities AS (
SELECT storedobject_id, array_agg(activity_id ORDER BY activity_id DESC) AS activities
FROM activity_storedobject
GROUP BY storedobject_id
HAVING count(*) > 1
)
DELETE FROM activity_storedobject
WHERE activity_id IN (
SELECT unnest(activities[2:]) -- Keep the highest ID, delete the rest
FROM duplicate_activities
);'
);
$this->addSql('CREATE UNIQUE INDEX unique_storedobject_id ON activity_storedobject (storedobject_id)');
}
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX IF EXISTS unique_storedobject_id');
}
}