Skip to content

Commit

Permalink
Refactor migrations to exclude ORM usage, resolving errors caused by …
Browse files Browse the repository at this point in the history
…evolving Entity structures (#37)

Updated the migration approach to avoid using the ORM, as it was leading to issues when Entity structures were modified. Specifically, when the ORM was used to select data from the database, it triggered errors if a column was missing, yet this column was intended to be added in a subsequent migration. This change ensures more robust and error-free migrations.
  • Loading branch information
samihsoylu authored Dec 14, 2023
1 parent c1c4336 commit 66c11f9
Showing 1 changed file with 1 addition and 45 deletions.
46 changes: 1 addition & 45 deletions private/lib/Database/Migration/Version20210627094934.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,18 @@

namespace App\Database\Migration;

use App\Database\Database;
use App\Database\Model\Category;
use App\Database\Repository\CategoryRepository;
use App\Database\Repository\UserRepository;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20210627094934 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}

public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE categories ADD sortOrder INT NOT NULL');
$this->addSql('ALTER TABLE categories ADD sortOrder INT NOT NULL DEFAULT 0;');
}

public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE categories DROP sortOrder');
}

public function postUp(Schema $schema): void
{
$database = Database::getInstance();
$cache = $database->getEntityManager()->getConfiguration()->getMetadataCache();
if ($cache !== null) {
$cache->clear();
}

$this->setOrderForExistingCategories();
}

private function setOrderForExistingCategories(): void
{
$userRepository = new UserRepository();
$users = $userRepository->getAll();

$categoryRepository = new CategoryRepository();

foreach ($users as $user) {
$categories = $categoryRepository->findByUser($user);

// Sort categories by id in ASC order
usort($categories, static fn (Category $a, Category $b) => (int)($a->getId() > $b->getId()));

for ($i = 0; $i < count($categories); $i++) {
$category = $categories[$i];
$category->setSortOrder($i + 1);

$categoryRepository->queue($category);
}
}

$categoryRepository->save();
}
}

0 comments on commit 66c11f9

Please sign in to comment.