8ctopus / nano-migrations
自动化数据库迁移
2.0.1
2023-12-28 11:23 UTC
Requires
- php: >=8.0
- psr/log: ^1.1.4|^2.0|^3.0
Requires (Dev)
- 8ctopus/apix-log: ^3
- clue/commander: ^1.4
- friendsofphp/php-cs-fixer: ^3.4
- nunomaduro/collision: ^7.5
- phpmd/phpmd: ^2.11
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.0|^10.0
This package is auto-updated.
Last update: 2024-08-26 14:39:25 UTC
README
一个轻量级的数据库迁移包
迁移用于管理数据库模式随时间的变化。迁移背后的理念是使数据库模式在应用程序演变过程中更容易维护和演进。此包使得在不使用框架的小项目中处理迁移变得简单。
演示
-
克隆仓库
-
运行
composer install
-
创建迁移文件
touch demo/migrations.txt
-
启动 Docker Desktop 并运行
docker-compose up &
-
进行迁移
php demo/index.php migrate [<count:int>]
-
回滚
php demo/index.php rollback <count:int>
安装
composer require 8ctopus/nano-migrations
如果您使用的是 php PDO
,则需要扩展 AbstractPDOMigration
类。扩展此类需要实现 up
和 down
迁移方法以及潜在的安全性检查。请参考示例目录。
use Oct8pus\Migration\AbstractPDOMigration; final class Migration extends AbstractPDOMigration { protected function up1() : string { return <<<'SQL' CREATE TABLE user ( email TEXT NOT NULL, password TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) SQL; } protected function down1() : string { return <<<'SQL' DROP TABLE IF EXISTS user SQL; } protected function up2() : string { ... } protected function down2() : string { ... } /** * Safety check * * @param array $methods * * @return self * * @throws MigrationException */ protected function safetyCheck(array $methods) : self { $stdin = fopen('php://stdin', 'r', false); if ($stdin === false) { throw new MigrationException('fopen'); } $this->logger?->info('migrations to run:'); foreach ($methods as $method) { $this->logger?->info("- {$method}"); } $this->logger?->warning('Confirm action (y/n): '); $input = trim(fgets($stdin)); fclose($stdin); if ($input === 'y') { return $this; } throw new MigrationException('safety check abort'); } }
对于其他数据库引擎,扩展 AbstractMigration
类并实现
up
和down
方法- 数据库连接
- 数据库查询
清洁代码
composer fix(-risky)
phpstan
composer phpstan
phpmd
composer phpmd