antonkomarev/php-db-migration-validator

验证PHP数据库迁移文件

1.0.2 2022-01-16 00:23 UTC

This package is auto-updated.

Last update: 2024-09-16 15:01:18 UTC


README

php-db-migration-validator

Discord Releases License

简介

在现代PHP框架(如Symfony和Laravel)中,迁移通常有updown方法。在迁移定义的up方法中,您必须编写只有在运行迁移向前执行时才被调用的代码,而在down——只有在回滚迁移时才被调用的代码。使数据库迁移不可逆是标准做法。迁移应该是向后兼容的,并且只能向前。

在Laravel中,缺失或空的down方法不会阻止在执行php artisan migrate:rollback CLI命令时回滚迁移。数据库的状态将不会改变,但迁移将从已应用的迁移注册表中删除,并且下一次执行php artisan migrate将再次调用up方法。为了防止这种行为,所有迁移都应该有将抛出异常的down方法,仅此而已。

PHP DB Migration Validator检查所有迁移文件是否满足此要求。您可以将它添加到服务器的git钩子中,以防止迁移回滚,或者将其添加到CI的验证步骤中。

安装

通过Composer引入包。

php composer require antonkomarev/php-db-migration-validator

用法

验证迁移不可逆

验证文件

php vendor/bin/php-db-migration-validator --rule=irreversible migrations/file.php

验证多个文件

php vendor/bin/php-db-migration-validator --rule=irreversible migrations/file.php migrations/file2.php

通过通配符验证多个文件

php vendor/bin/php-db-migration-validator --rule=irreversible migrations/2022_*

验证目录中的文件

php vendor/bin/php-db-migration-validator --rule=irreversible migrations/

验证多个目录中的文件

php vendor/bin/php-db-migration-validator --rule=irreversible app/migrations/ vendor/migrations/

CI自动化

将验证所有贡献作为持续集成的一部分自动执行是使用此工具的可能方法之一。

GitHub Action

在应用程序存储库中创建文件.github/workflows/db-migration-validation.yaml

name: DB Migration Validation

on:
    push:

jobs:
    db-migration-validation:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v2
            - uses: shivammathur/setup-php@v2
              with:
                  php-version: 8.1
                  extensions: tokenizer
                  coverage: none
            - name: Install PHP DB Migration Validator dependency
              run: composer global require antonkomarev/php-db-migration-validator --no-interaction
            - name: Ensure all database migrations are irreversible
              run: php-db-migration-validator --rule=irreversible ./database/migrations

命令用法说明

$ php vendor/bin/php-db-migration-validator --help
PHP DB Migration Validator
--------------------------
by Anton Komarev <anton@komarev.com>

Usage: php-db-migration-validator --rule=<rule> <path>

  The following commands are available:

    help  Shows this usage instructions.

  Options:

    --rules=<rule>   Validates the database migration(s) in the specified <path>.
                     Exits with code 1 on validation errors, 2 on other errors and 0 on success.
                     Available rules (at least one should be specified):
                     - irreversible — ensure if migration file has `down` method and this method throws an Exception.

许可证

支持项目

如果您想支持PHP DB Migration Validator的开发,那么请考虑赞助我。非常感谢!

关于CyberCog

CyberCog是一个爱好者的社交团体。研究产品与软件开发中的最佳解决方案是我们的热情。

CyberCog