doctrine/migrations 数据库迁移
composer require "doctrine/migrations:^2.0"
- 整合至项目
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74#!/usr/bin/env php
require_once __DIR__ . '/vendor/autoload.php';
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\DriverManager;
use Doctrine\Migrations\Configuration\Configuration;
use Doctrine\Migrations\Tools\Console\Command;
use Doctrine\Migrations\Tools\Console\Helper\ConfigurationHelper;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\QuestionHelper;
/**
* # 生成迁移脚本
* php migration.php migrations:generate
* # 执行迁移到指定版本或最新版本
* php migration.php migrations:migrate [first|prev|next|latest|版本号]
* # --dry-run 是空转参数,只显示操作结果,不执行修改
* php migration.php migrations:migrate --dry-run
* # 不执行操作,只写入文件,对于生产环境需要手动验证并执行的场景有用
* php migration.php migrations:migrate --write-sql=file.sql
* # 查看详细信息
* php migration.php status
* # 查看命令列表
* php migration.php list
*/
$dbParams = [
'dbname' => 'test',
'user' => 'root',
'password' => 'root',
'host' => 'localhost',
'driver' => 'pdo_mysql',
];
try {
$connection = DriverManager::getConnection($dbParams);
// 迁移组件
$configuration = new Configuration($connection);
$configuration->setName('test'); // 组件名称
$configuration->setMigrationsNamespace('database\Migrations'); // 迁移类的命名空间
$configuration->setMigrationsTableName('test_migration_versions'); // 迁移组件的表名
$configuration->setMigrationsDirectory('D:\Web\Project\private\database\Migrations'); // 迁移类的文件
$configuration->setAllOrNothing(true); // 是否在单个事务中包装多个迁移
$configuration->setCheckDatabasePlatform(true); // 是否在生成代码的开头添加数据库平台检查
$helperSet = new HelperSet();
$helperSet->set(new QuestionHelper(), 'question');
$helperSet->set(new ConnectionHelper($connection), 'db');
$helperSet->set(new ConfigurationHelper($connection, $configuration));
$cli = new Application('Doctrine Migrations');
$cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
$cli->addCommands([
new Command\DumpSchemaCommand(),
new Command\ExecuteCommand(),
new Command\GenerateCommand(),
new Command\LatestCommand(),
new Command\MigrateCommand(),
new Command\RollupCommand(),
new Command\StatusCommand(),
new Command\VersionCommand()
]);
$cli->run();
} catch (DBALException $e) {
exit($e->getMessage() . PHP_EOL);
} catch (Exception $e) {
exit($e->getMessage() . PHP_EOL);
}