zp / mongodb-migrations

为MongoDB管理的数据库迁移

v4.0.1 2021-11-17 08:24 UTC

README

MIT license Build Status Scrutinizer Code Quality Latest Stable Version Total Downloads

MongoDB迁移

MongoDB迁移库为MongoDB提供管理迁移支持。它从antimattr/mongodb-migrations迁移到doesntmattr组织,以继续维护(见问题16)。

原始作者是@rcatlin和@matthewfitz

它遵循Doctrine Migrations提供的结构和功能。

PHP版本支持

如果您需要php 5.6支持,请使用版本^1.0。版本^3.0需要至少php 7.1。1.x版本仅接收错误修复。

Symfony Bundle

您可以使用Symfony Bundle更容易地集成Symfony。使用那里的安装说明

https://github.com/doesntmattr/mongodb-migrations-bundle

安装

使用Composer安装

# For php 5.6
composer require "doesntmattr/mongodb-migrations=^1.0"

# For php 7.1
composer require "doesntmattr/mongodb-migrations=^3.0"

特性

配置

Doctrine Migrations类似,配置分为两个文件

  • 连接配置(php)
  • 迁移配置(xml或yaml)

示例连接配置 "test_antimattr_mongodb.php"

/**
 * @link https://php.ac.cn/manual/en/mongoclient.construct.php
 */
return [
    'host' => 'localhost', // default is localhost
    'port' => '27017', // default is 27017
    'dbname' => null, // optional, if authentication DB is required
    'user' => null, // optional, if authentication is required
    'password' => null, // optional, if authentication is required
    'options' => [
        'connect' => true // recommended
    ]
];

支持XML或YAML迁移配置文件。

示例XML "test_antimattr_mongodb.xml"

<?xml version="1.0" encoding="UTF-8"?>
<antimattr-migrations xmlns="http://doctrine-project.org/schemas/migrations/configuration"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://doctrine-project.org/schemas/migrations/configuration
                    http://doctrine-project.org/schemas/migrations/configuration.xsd">

    <name>AntiMattr Sandbox Migrations</name>
    <migrations-namespace>AntiMattrMigrationsTest</migrations-namespace>
    <database name="test_antimattr_migrations" />
    <collection name="antimattr_migration_versions_test" />
    <migrations-directory>/path/to/migrations/classes/AntiMattrMigrations</migrations-directory>
    <!-- Script Directory Optional -->
    <migrations-script-directory>/path/to/migrations/script_directory</migrations-script-directory>

</antimattr-migrations>

示例YAML "test_antimattr_mongodb.yml"

---
name: AntiMattr Sandbox Migrations
migrations_namespace: AntiMattrMigrationsTest
database: test_antimattr_migrations
collection_name: antimattr_migration_versions_test
migrations_directory: /path/to/migrations/classes/AntiMattrMigrations
migrations_script_directory: /path/to/migrations/script_directory # optional

控制台命令支持

/demo目录中有一个示例控制台应用程序。

这是如何在您的应用程序中注册命令的方法

require '../../vendor/autoload.php';

error_reporting(E_ALL & ~E_NOTICE);

use AntiMattr\MongoDB\Migrations\Tools\Console\Command as AntiMattr;
use Symfony\Component\Console\Application;

$application = new Application();
$application->addCommands([
    new AntiMattr\ExecuteCommand(),
    new AntiMattr\GenerateCommand(),
    new AntiMattr\MigrateCommand(),
    new AntiMattr\StatusCommand(),
    new AntiMattr\VersionCommand()
]);
$application->run();

注意控制台是可执行的

> cd demo/ConsoleApplication/
> ./console
Console Tool

Usage:
  [options] command [arguments]

Options:
  --help           -h Display this help message.
  --quiet          -q Do not output any message.
  --verbose        -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  --version        -V Display this application version.
  --ansi              Force ANSI output.
  --no-ansi           Disable ANSI output.
  --no-interaction -n Do not ask any interactive question.

Available commands:
  help                          Displays help for a command
  list                          Lists commands
mongodb
  mongodb:migrations:execute    Execute a single migration version up or down manually.
  mongodb:migrations:generate   Generate a blank migration class.
  mongodb:migrations:migrate    Execute a migration to a specified version or the latest available version.
  mongodb:migrations:status     View the status of a set of migrations.
  mongodb:migrations:version    Manually add and delete migration versions from the version table.

生成新的迁移

> ./console mongodb:migrations:generate --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml
Generated new migration class to "Example/Migrations/TestAntiMattr/MongoDB/Version20140822185742.php"

迁移状态

> ./console mongodb:migrations:status --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml

 == Configuration

    >> Name:                                AntiMattr Example Migrations
    >> Database Driver:                     MongoDB
    >> Database Name:                       test_antimattr_migrations
    >> Configuration Source:                demo/ConsoleApplication/config/test_antimattr_mongodb.yml
    >> Version Collection Name:             migration_versions
    >> Migrations Namespace:                Example\Migrations\TestAntiMattr\MongoDB
    >> Migrations Directory:                Example/Migrations/TestAntiMattr/MongoDB
    >> Current Version:                     0
    >> Latest Version:                      2014-08-22 18:57:44 (20140822185744)
    >> Executed Migrations:                 0
    >> Executed Unavailable Migrations:     0
    >> Available Migrations:                3
    >> New Migrations:                      3

迁移所有

这是您在部署过程中将执行的内容。

./console mongodb:migrations:migrate --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml 
                                                                    
                    AntiMattr Example Migrations                    
                                                                    

WARNING! You are about to execute a database migration that could result in data lost. Are you sure you wish to continue? (y/n)y
Migrating up to 20140822185744 from 0

  ++ migrating 20140822185742


     Collection test_a

     metric           before               after                difference           
     ================================================================================
     count            100                  100                  0                   
     size             20452                20452                0                   
     avgObjSize       204.52               204.52               0                   
     storageSize      61440                61440                0                   
     numExtents       2                    2                    0                   
     nindexes         1                    2                    1                   
     lastExtentSize   49152                49152                0                   
     paddingFactor    1                    1                    0                   
     totalIndexSize   8176                 16352                8176                

  ++ migrated (0.03s)

  ++ migrating 20140822185743


  ++ migrated (0s)

  ++ migrating 20140822185744


  ++ migrated (0s)

  ------------------------

  ++ finished in 0.03
  ++ 3 migrations executed

执行单个迁移

./console mongodb:migrations:execute --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml 20140822185742
WARNING! You are about to execute a database migration that could result in data lost. Are you sure you wish to continue? (y/n)y

  ++ migrating 20140822185742


     Collection test_a

     metric           before               after                difference           
     ================================================================================
     count            100                  100                  0                   
     size             20620                20620                0                   
     avgObjSize       206.2                206.2                0                   
     storageSize      61440                61440                0                   
     numExtents       2                    2                    0                   
     nindexes         1                    2                    1                   
     lastExtentSize   49152                49152                0                   
     paddingFactor    1                    1                    0                   
     totalIndexSize   8176                 16352                8176                

  ++ migrated (0.02s)

如果您需要再次运行迁移,可以使用--replay参数。

版本升级或降级

由于某种原因,您的迁移历史记录不同步?您可以在不运行底层迁移的情况下手动添加或删除历史记录中的记录。

您可以删除

./console mongodb:migrations:version --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml --delete 20140822185744

您可以添加

./console mongodb:migrations:version --db-configuration=config/test_antimattr_mongodb.php --configuration=config/test_antimattr_mongodb.yml --add 20140822185744

分析迁移

确定您想要分析的数据集。在迁移运行前后将捕获统计信息。

class Version20140822185742 extends AbstractMigration
{
    public function up(Database $db)
    {
        $testA = $db->selectCollection('test_a');
        $this->analyze($testA);

        // Do the migration
    }

执行JS脚本

首先在迁移配置中确定脚本目录

---
name: AntiMattr Sandbox Migrations
migrations_namespace: AntiMattrMigrationsTest
database: test_antimattr_migrations
collection_name: antimattr_migration_versions_test
migrations_directory: /path/to/migrations/classes/AntiMattrMigrations
migrations_script_directory: /path/to/migrations/script_directory # optional

然后通过AbstractMigration::executeScript()执行脚本

class Version20140822185743 extends AbstractMigration
{
    public function up(Database $db)
    {
        $result = $this->executeScript($db, 'test_script.js');
    }

贡献

PSR标准

有一个git pre-commit钩子,可以修复您贡献的所有代码以符合PSR标准。

您可以使用以下命令安装它

./bin/install.sh 
Copying /antimattr-mongodb-migrations/bin/pre-commit.sh -> /antimattr-mongodb-migrations/bin/../.git/hooks/pre-commit

测试

测试应该通过

$ ./vendor/bin/phpunit

Code Sniffer和Fixer

如果您没有安装git pre-commit钩子,请确保手动运行fixer/sniffer

$ vendor/bin/php-cs-fixer fix src/
$ vendor/bin/php-cs-fixer fix tests/