Julien Fastré 4be6c09d4d
Add unique constraints to prevent person_documnt and accompanyingcourse_document with duplicated object_id
This change ensures `object_id` uniqueness within `person_document` and `accompanyingcourse_document` tables. It includes migration scripts and entity annotations to enforce these constraints. This helps maintain data integrity and consistency across the database.
2024-11-19 10:50:46 +01:00

42 lines
1.4 KiB
PHP

<?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\DocStore;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20241118151618 extends AbstractMigration
{
public function getDescription(): string
{
return 'Force no duplicated object_id within person_document and accompanyingcourse_document';
}
public function up(Schema $schema): void
{
$this->addSql(<<<'SQL'
WITH ranked AS (
SELECT id, rank() OVER (PARTITION BY object_id ORDER BY id ASC) FROM chill_doc.accompanyingcourse_document
)
DELETE FROM chill_doc.accompanyingcourse_document WHERE id IN (SELECT id FROM ranked where "rank" <> 1)
SQL);
$this->addSql('CREATE UNIQUE INDEX acc_course_document_unique_stored_object ON chill_doc.accompanyingcourse_document (object_id)');
$this->addSql('CREATE UNIQUE INDEX person_document_unique_stored_object ON chill_doc.person_document (object_id)');
}
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX acc_course_document_unique_stored_object');
$this->addSql('DROP INDEX person_document_unique_stored_object');
}
}