Commit 483a01fd authored by Jean-Baptiste Oellers's avatar Jean-Baptiste Oellers
Browse files

Ajout doctrine migration

parent bdb6afea
Loading
Loading
Loading
Loading
+2 −1
Original line number Diff line number Diff line
@@ -34,7 +34,8 @@
    "unicaen/signature": "1.0.1",
    "ext-gettext": "*",
    "ext-fileinfo": "*",
    "symfony/filesystem": "^7.1"
    "symfony/filesystem": "^7.1",
    "doctrine/migrations": "^3.8"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
+242 −1
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@
        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
        "This file is @generated automatically"
    ],
    "content-hash": "1089a2503a3732bfab8da81732beeefc",
    "content-hash": "a2dad03a44b64d39b4341e4142674037",
    "packages": [
        {
            "name": "apereo/phpcas",
@@ -1411,6 +1411,109 @@
            ],
            "time": "2024-02-05T11:35:39+00:00"
        },
        {
            "name": "doctrine/migrations",
            "version": "3.8.2",
            "source": {
                "type": "git",
                "url": "https://github.com/doctrine/migrations.git",
                "reference": "5007eb1168691225ac305fe16856755c20860842"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/doctrine/migrations/zipball/5007eb1168691225ac305fe16856755c20860842",
                "reference": "5007eb1168691225ac305fe16856755c20860842",
                "shasum": ""
            },
            "require": {
                "composer-runtime-api": "^2",
                "doctrine/dbal": "^3.6 || ^4",
                "doctrine/deprecations": "^0.5.3 || ^1",
                "doctrine/event-manager": "^1.2 || ^2.0",
                "php": "^8.1",
                "psr/log": "^1.1.3 || ^2 || ^3",
                "symfony/console": "^5.4 || ^6.0 || ^7.0",
                "symfony/stopwatch": "^5.4 || ^6.0 || ^7.0",
                "symfony/var-exporter": "^6.2 || ^7.0"
            },
            "conflict": {
                "doctrine/orm": "<2.12 || >=4"
            },
            "require-dev": {
                "doctrine/coding-standard": "^12",
                "doctrine/orm": "^2.13 || ^3",
                "doctrine/persistence": "^2 || ^3",
                "doctrine/sql-formatter": "^1.0",
                "ext-pdo_sqlite": "*",
                "fig/log-test": "^1",
                "phpstan/phpstan": "^1.10",
                "phpstan/phpstan-deprecation-rules": "^1.1",
                "phpstan/phpstan-phpunit": "^1.3",
                "phpstan/phpstan-strict-rules": "^1.4",
                "phpstan/phpstan-symfony": "^1.3",
                "phpunit/phpunit": "^10.3",
                "symfony/cache": "^5.4 || ^6.0 || ^7.0",
                "symfony/process": "^5.4 || ^6.0 || ^7.0",
                "symfony/yaml": "^5.4 || ^6.0 || ^7.0"
            },
            "suggest": {
                "doctrine/sql-formatter": "Allows to generate formatted SQL with the diff command.",
                "symfony/yaml": "Allows the use of yaml for migration configuration files."
            },
            "bin": [
                "bin/doctrine-migrations"
            ],
            "type": "library",
            "autoload": {
                "psr-4": {
                    "Doctrine\\Migrations\\": "src"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Benjamin Eberlei",
                    "email": "kontakt@beberlei.de"
                },
                {
                    "name": "Jonathan Wage",
                    "email": "jonwage@gmail.com"
                },
                {
                    "name": "Michael Simonson",
                    "email": "contact@mikesimonson.com"
                }
            ],
            "description": "PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easily deploying changes to it. It is a very easy to use and a powerful tool.",
            "homepage": "https://www.doctrine-project.org/projects/migrations.html",
            "keywords": [
                "database",
                "dbal",
                "migrations"
            ],
            "support": {
                "issues": "https://github.com/doctrine/migrations/issues",
                "source": "https://github.com/doctrine/migrations/tree/3.8.2"
            },
            "funding": [
                {
                    "url": "https://www.doctrine-project.org/sponsorship.html",
                    "type": "custom"
                },
                {
                    "url": "https://www.patreon.com/phpdoctrine",
                    "type": "patreon"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fmigrations",
                    "type": "tidelift"
                }
            ],
            "time": "2024-10-10T21:35:27+00:00"
        },
        {
            "name": "doctrine/orm",
            "version": "2.19.6",
@@ -8598,6 +8701,68 @@
            ],
            "time": "2024-04-18T09:32:20+00:00"
        },
        {
            "name": "symfony/stopwatch",
            "version": "v7.2.2",
            "source": {
                "type": "git",
                "url": "https://github.com/symfony/stopwatch.git",
                "reference": "e46690d5b9d7164a6d061cab1e8d46141b9f49df"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/symfony/stopwatch/zipball/e46690d5b9d7164a6d061cab1e8d46141b9f49df",
                "reference": "e46690d5b9d7164a6d061cab1e8d46141b9f49df",
                "shasum": ""
            },
            "require": {
                "php": ">=8.2",
                "symfony/service-contracts": "^2.5|^3"
            },
            "type": "library",
            "autoload": {
                "psr-4": {
                    "Symfony\\Component\\Stopwatch\\": ""
                },
                "exclude-from-classmap": [
                    "/Tests/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Fabien Potencier",
                    "email": "fabien@symfony.com"
                },
                {
                    "name": "Symfony Community",
                    "homepage": "https://symfony.com/contributors"
                }
            ],
            "description": "Provides a way to profile code",
            "homepage": "https://symfony.com",
            "support": {
                "source": "https://github.com/symfony/stopwatch/tree/v7.2.2"
            },
            "funding": [
                {
                    "url": "https://symfony.com/sponsor",
                    "type": "custom"
                },
                {
                    "url": "https://github.com/fabpot",
                    "type": "github"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
                    "type": "tidelift"
                }
            ],
            "time": "2024-12-18T14:28:33+00:00"
        },
        {
            "name": "symfony/string",
            "version": "v7.1.2",
@@ -8685,6 +8850,82 @@
            ],
            "time": "2024-06-28T09:27:18+00:00"
        },
        {
            "name": "symfony/var-exporter",
            "version": "v7.2.0",
            "source": {
                "type": "git",
                "url": "https://github.com/symfony/var-exporter.git",
                "reference": "1a6a89f95a46af0f142874c9d650a6358d13070d"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/symfony/var-exporter/zipball/1a6a89f95a46af0f142874c9d650a6358d13070d",
                "reference": "1a6a89f95a46af0f142874c9d650a6358d13070d",
                "shasum": ""
            },
            "require": {
                "php": ">=8.2"
            },
            "require-dev": {
                "symfony/property-access": "^6.4|^7.0",
                "symfony/serializer": "^6.4|^7.0",
                "symfony/var-dumper": "^6.4|^7.0"
            },
            "type": "library",
            "autoload": {
                "psr-4": {
                    "Symfony\\Component\\VarExporter\\": ""
                },
                "exclude-from-classmap": [
                    "/Tests/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Nicolas Grekas",
                    "email": "p@tchwork.com"
                },
                {
                    "name": "Symfony Community",
                    "homepage": "https://symfony.com/contributors"
                }
            ],
            "description": "Allows exporting any serializable PHP data structure to plain PHP code",
            "homepage": "https://symfony.com",
            "keywords": [
                "clone",
                "construct",
                "export",
                "hydrate",
                "instantiate",
                "lazy-loading",
                "proxy",
                "serialize"
            ],
            "support": {
                "source": "https://github.com/symfony/var-exporter/tree/v7.2.0"
            },
            "funding": [
                {
                    "url": "https://symfony.com/sponsor",
                    "type": "custom"
                },
                {
                    "url": "https://github.com/fabpot",
                    "type": "github"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
                    "type": "tidelift"
                }
            ],
            "time": "2024-10-18T07:58:17+00:00"
        },
        {
            "name": "symfony/yaml",
            "version": "v4.4.45",
+27 −1
Original line number Diff line number Diff line
@@ -403,7 +403,25 @@ return array(
                    'quarter'  =>        'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'second'  =>         'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'year'  =>           'Oro\ORM\Query\AST\Functions\SimpleFunction',
                ]
                ],
                'schema_assets_filter' => static function ($asset): bool {
                    // Pour éviter que la commande suivante ne supprime la table doctrine_migration_versions
                    // php vendor/bin/doctrine-module orm:schema-tool:update --dump-sql --complete
                    // Voir aussi https://github.com/doctrine/DoctrineBundle/pull/935

                    // On ne "cache" la table doctrine_migration_versions que pour la commande
                    // doctrine-module orm:schema-tool:update
                    // parce que sinon, si les commandes de doctrine migration ne voient plus cette table
                    // alors elles essaient de la recréer à chaque fois et elles échouent car la table existe déjà.
                    if (!isset($_SERVER['argv'])
                        || !is_array($_SERVER['argv'])
                        || !in_array('vendor/bin/doctrine-module', $_SERVER['argv'], true)
                        || !in_array('orm:schema-tool:update', $_SERVER['argv'], true)) {
                        return true;
                    }

                    return $asset !== "doctrine_migration_versions";
                },
            ),
        ),

@@ -417,5 +435,13 @@ return array(
                ),
            ),
        ),

        'eventmanager' => array(
            'orm_default' => array(
                'subscribers' => array(
                    Oscar\ORM\FixPostgreSQLDefaultSchemaListener::class,
                ),
            ),
        ),
    ),
);
+102 −0
Original line number Diff line number Diff line
# Doctrine migration

Ce document à destination des développeurs illustre l'utilisation de doctrine migration. La documentation officielle du projet est ici : https://www.doctrine-project.org/projects/doctrine-migrations/en/3.8/reference/introduction.html

## Créer une nouvelle migration

Pour créer une nouvelle migration "vide", la commande est la suivante :

```bash
vendor/bin/doctrine-migrations generate
```

Cela va créer un nouveau fichier de migration php "vide" dans ```module/Oscar/src/Oscar/Migrations```. Il ne restera plus qu'à compléter les méthodes ```up``` et ```down```. La première (```up```) contient les scripts amenant la base de données vers son nouvel état tandis que ```down``` contient les scripts permettant d'annuler une migration (rollback) et ainsi ramener la base de données dans l'état précédent l'application de la migration. Un rollback via ce genre de système/script n'est pas toujours possible par exemple lorsqu'il y a suppression de données (suppression d'une colonne). Dans ce cas, pour réaliser un rollback il faudra restaurer une sauvegarde (snapshot, dump) de la BDD qu'il faut bien penser à réaliser avant chaque mise-à-jour/migration de la BDD.

## Créer une nouvelle migration automatiquement en comparant les annotations des entités avec l'état de la BDD

Doctrine peut alimenter automatiquement le contenu d'une migration en comparant l'état de la base de données avec celui du code (annotations des entités) via la commande suivante :

```bash
vendor/bin/doctrine-migrations diff
```

Cette commande va créer un nouveau fichier de migration php dans ```module/Oscar/src/Oscar/Migrations```.

Toutefois [un bug](https://github.com/doctrine/migrations/issues/441) dans ```doctrine/dbal``` fait que cette commande génère en première ligne du script ```down``` la ligne ```CREATE SCHEMA public```
```php
public function down(Schema $schema): void
{
    // this down() migration is auto-generated, please modify it to your needs
    $this->addSql('CREATE SCHEMA public');
    // ...
```
Un fix a donc été ajouté (création du Subscriber ```FixPostgreSQLDefaultSchemaListener.php```) pour éviter que cette instruction ne soit générée.

## Connaître l'état des migrations

Deux commandes permettent de connaître l'état des migrations :

```bash
vendor/bin/doctrine-migrations migrations:list

+----------------------------------------+--------------+---------------------+----------------+-------------+
| Migration Versions                                                                           |             |
+----------------------------------------+--------------+---------------------+----------------+-------------+
| Migration                              | Status       | Migrated At         | Execution Time | Description |
+----------------------------------------+--------------+---------------------+----------------+-------------+
| Oscar\Migrations\Version20241209100502 | migrated     | 2024-12-09 11:10:53 | 0.018s         |             |
| Oscar\Migrations\Version20241209101055 | migrated     | 2024-12-09 11:12:41 | 0.001s         |             |
| Oscar\Migrations\Version20241209101244 | not migrated |                     |                |             |
+----------------------------------------+--------------+---------------------+----------------+-------------+
```

Et

```bash
vendor/bin/doctrine-migrations status

+----------------------+----------------------+------------------------------------------------------------------------+
| Configuration                                                                                                        |
+----------------------+----------------------+------------------------------------------------------------------------+
| Storage              | Type                 | Doctrine\Migrations\Metadata\Storage\TableMetadataStorageConfiguration |
|                      | Table Name           | doctrine_migration_versions                                            |
|                      | Column Name          | version                                                                |
|----------------------------------------------------------------------------------------------------------------------|
| Database             | Driver               | Doctrine\DBAL\Driver\PDO\PgSQL\Driver                                  |
|                      | Name                 | oscar                                                                  |
|----------------------------------------------------------------------------------------------------------------------|
| Versions             | Previous             | Oscar\Migrations\Version20241209100502                                 |
|                      | Current              | Oscar\Migrations\Version20241209101055                                 |
|                      | Next                 | Oscar\Migrations\Version20241209101244                                 |
|                      | Latest               | Oscar\Migrations\Version20241209101244                                 |
|----------------------------------------------------------------------------------------------------------------------|
| Migrations           | Executed             | 2                                                                      |
|                      | Executed Unavailable | 0                                                                      |
|                      | Available            | 3                                                                      |
|                      | New                  | 1                                                                      |
|----------------------------------------------------------------------------------------------------------------------|
| Migration Namespaces | Oscar\Migrations     | /home/oellers241/src/oscar/module/Oscar/src/Oscar/Migrations           |
+----------------------+----------------------+------------------------------------------------------------------------+
```

Cette commande est pratique pour connaître le nom de la migration précédente ```Versions > Previous``` et ainsi effectuer une rollback en "migrant" la BDD vers cette migration :

```bash
vendor/bin/doctrine-migrations migrate Oscar\Migrations\Version20241209100502
```

## Exécuter les migrations en attente

Pour effectuer toutes les migrations non encore réalisées, la commande est la suivante :

```bash
vendor/bin/doctrine-migrations migrate --no-interaction
```

## Annuler une migration

Pour annuler une migration, il faut trouver le nom de la migration précédente, par exemple en utilisant la commande ```status``` ou bien en allant voir directement dans le répertoire des fichiers php de migrations. Ensuite il faut utiliser la commande ```migrate``` en lui indiquant vers quelle migration il faut faire évoluer la BDD :

```bash
vendor/bin/doctrine-migrations migrate Oscar\Migrations\Version20241209100502
```

migrations.php

0 → 100644
+22 −0
Original line number Diff line number Diff line
<?php

return [
    'table_storage' => [
        'table_name' => 'doctrine_migration_versions',
        'version_column_name' => 'version',
        'version_column_length' => 191,
        'executed_at_column_name' => 'executed_at',
        'execution_time_column_name' => 'execution_time',
    ],

    'migrations_paths' => [
        'Oscar\Migrations' => './module/Oscar/src/Oscar/Migrations',
    ],

    'all_or_nothing' => true,
    'transactional' => true,
    'check_database_platform' => true,
    'organize_migrations' => 'none',
    'connection' => null,
    'em' => null,
];
Loading