This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
Migrations Documentation
=================
The Doctrine Migrations documentation is a reference guide to everything you need
to know about the migrations project.
Getting Help
------------
If this documentation is not helping to answer questions you have about
Doctrine Migrations don't panic. You can get help from different sources:
- The `Doctrine Mailing List <https://groups.google.com/group/doctrine-user>`_
- Slack chat room `#migrations <https://www.doctrine-project.org/slack>`_
- Report a bug on `GitHub <https://github.com/doctrine/migrations/issues>`_.
- On `StackOverflow <https://stackoverflow.com/questions/tagged/doctrine-migrations>`_
Getting Started
---------------
The best way to get started is with the :doc:`Introduction <introduction>` section.
Use the sidebar to browse other documentation for the Doctrine PHP Migrations project.

View File

@@ -0,0 +1,113 @@
Custom Integration
==================
For up to date code take a look at `the doctrine migrations command line integration <https://github.com/doctrine/migrations/blob/master/bin/doctrine-migrations.php>`_.
None the less the main steps required to make a functional integration are presented below.
Installation
~~~~~~~~~~~~
First you need to require Doctrine Migrations as a dependency of your code
.. code-block:: sh
composer require doctrine/migrations
Then you have to require the composer autoloader to use the classes from the `Doctrine\DBAL\Migrations`
namespace in your project:
.. code-block:: php
$autoloadFiles = array(
__DIR__ . '/../vendor/autoload.php',
__DIR__ . '/../../../autoload.php'
);
$autoloader = false;
foreach ($autoloadFiles as $autoloadFile) {
if (file_exists($autoloadFile)) {
require_once $autoloadFile;
$autoloader = true;
}
}
if (!$autoloader) {
die('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}
Now the above autoloader is able to load a class like the following:
.. code-block:: bash
/path/to/migrations/lib/Doctrine/DBAL/Migrations/Migrations/Migration.php
Register Console Commands
~~~~~~~~~~~~~~~~~~~~~~~~~
Now that we have setup the autoloaders we are ready to add the migration console
commands to our `Doctrine Command Line Interface <http://doctrine-orm.readthedocs.org/en/latest/reference/tools.html#adding-own-commands>`_:
.. code-block:: php
// ...
$cli->addCommands(array(
// Migrations Commands
new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\LatestCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand()
));
Register Console helpers
~~~~~~~~~~~~~~~~~~~~~~~~
Additionally you have to make sure the 'db' and 'dialog' Helpers are added to your Symfony
Console HelperSet in a cli-config.php file.
This file can be either in the directory you are calling the console tool from or in as config subfolder.
.. code-block:: php
$db = \Doctrine\DBAL\DriverManager::getConnection($params);
// or
$em = \Doctrine\ORM\EntityManager::create($params);
$db = $em->getConnection();
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($db),
'question' => new \Symfony\Component\Console\Helper\QuestionHelper(),
));
return $helperset;
Note that the db helper is not required as you might want to pass the connection information
from the command line directly.
You will see that you have a few new commands when you execute the following command:
.. code-block:: bash
$ ./doctrine list migrations
Doctrine Command Line Interface version 1.2.1
Usage:
[options] command [arguments]
Options:
--help -h Display this help message.
--quiet -q Do not output any message.
--verbose -v Increase verbosity of messages.
--version -V Display this program version.
--color -c Force ANSI color output.
--no-interaction -n Do not ask any interactive question.
Available commands for the "migrations" namespace:
:diff Generate a migration by comparing your current database to your mapping information.
:execute Execute a single migration version up or down manually.
:generate Generate a blank migration class.
:migrate Execute a migration to a specified version or the latest available version.
:status View the status of a set of migrations.
:version Manually add and delete migration versions from the version table.

View File

@@ -0,0 +1,20 @@
Custom Configuration
====================
The ``AbstractCommand::setMigrationConfiguration()`` method allows you to set your own configuration.
This allows you to to build doctrine migration integration into your application or framework with
code that would looks like the following:
.. code-block:: php
use Doctrine\DBAL\Migrations\Configuration\Configuration;
$configuration = new Configuration();
$configuration->setMigrationsTableName(...);
$configuration->setMigrationsDirectory(...);
$configuration->setMigrationsNamespace(...);
$configuration->registerMigrationsFromDirectory(...);
// My command that extends Doctrine\DBAL\Migrations\Tools\Console\Command\AbstractCommand
$command->setMigrationConfiguration($configuration);

View File

@@ -0,0 +1,78 @@
Migrations Events
=================
The migrations library emits a series of events during the migration process.
- ``onMigrationsMigrating``: fired immediately before starting to execute
versions. This does not fire if there are no versions to be executed.
- ``onMigrationsVersionExecuting``: fired before a single version
executes.
- ``onMigrationsVersionExecuted``: fired after a single version executes.
- ``onMigrationsVersionSkipped``: fired when a single version is skipped.
- ``onMigrationsMigrated``: fired when all versions have been executed.
All of these events are emitted via the connection's event manager. Here's an
example event subscriber that listens for all possible migrations events.
.. code-block:: php
<?php
use Doctrine\Common\EventSubscriber;
use Doctrine\DBAL\Migrations\Event\MigrationsEventArgs;
use Doctrine\DBAL\Migrations\Event\MigrationsVersionEventArgs;
class MigrationsListener implements EventSubscriber
{
public function getSubscribedEvents()
{
return [
Events::onMigrationsMigrating,
Events::onMigrationsMigrated,
Events::onMigrationsVersionExecuting,
Events::onMigrationsVersionExecuted,
Events::onMigrationsVersionSkipped,
];
}
public function onMigrationsMigrating(MigrationsEventArgs $args)
{
// ...
}
public function onMigrationsMigrated(MigrationsEventArgs $args)
{
// ...
}
public function onMigrationsVersionExecuting(MigrationsVersionEventArgs $args)
{
// ...
}
public function onMigrationsVersionExecuted(MigrationsVersionEventArgs $args)
{
// ...
}
public function onMigrationsVersionSkipped(MigrationsVersionEventArgs $args)
{
// ...
}
}
To hook a migrations event subscriber into a connection, use its event manager.
This might go in the ``cli-config.php`` file or somewhere in a frameworks
container or dependency injection configuration.
.. code-block:: php
<?php
use Doctrine\DBAL\DriverManager;
$conn = DriverManager::getConnection([
// ...
]);
$conn->getEventManager()->addEventSubscriber(new MigrationsListener());
// rest of the cli set up...

View File

@@ -0,0 +1,194 @@
Generating Migrations
=====================
Migrations can be created for you if you're using the Doctrine 2 ORM or the DBAL
`Schema Representation <http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/schema-representation.html>`_.
Empty migration classes can also be created.
Favor the tools described here over manually created migration files as the library
has some :doc:`requirements around migration version numbers <version_numbers>`.
Using the ORM
-------------
If you are using the Doctrine 2 ORM you can easily generate a migration class
by modifying your mapping information and running the diff task to compare it
to your current database schema.
If you are using the sandbox you can modify the provided `yaml/Entities.User.dcm.yml`
and add a new column:
.. code-block:: yaml
Entities\User:
# ...
fields:
# ...
test:
type: string
length: 255
# ...
Be sure that you add the property to the `Entities/User.php` file:
.. code-block:: php
namespace Entities;
/** @Entity @Table(name="users") */
class User
{
/**
* @var string $test
*/
private $test;
// ...
}
Now if you run the diff task you will get a nicely generated migration with the
changes required to update your database!
.. code-block:: bash
$ ./doctrine migrations:diff
Generated new migration class to "/path/to/migrations/DoctrineMigrations/Version20100416130459.php" from schema differences.
The migration class that is generated contains the SQL statements required to
update your database:
.. code-block:: php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20100416130459 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->addSql('ALTER TABLE users ADD test VARCHAR(255) NOT NULL');
}
public function down(Schema $schema)
{
$this->addSql('ALTER TABLE users DROP test');
}
}
The SQL generated here is the exact same SQL that would be executed if you were
using the `orm:schema-tool` task and the `--update` option. This just allows you to
capture that SQL and maybe tweak it or add to it and trigger the deployment
later across multiple database servers.
Without the ORM
---------------
Internally the diff command generates a ``Doctrine\DBAL\Schema\Schema`` object
from your entity's metadata using an implementation of
``Doctrine\DBAL\Migrations\Provider\SchemaProvider``. To use the Schema representation
directly, without the ORM, you must implement this interface yourself.
.. code-block:: php
<?php
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Migrations\Provider\SchemaProvider;
final class CustomSchemaProvider implements SchemaProvider
{
/**
* The schema provider only has one method: `createSchema`. This should
* return an Schema object that represents the state to which you'd like
* to migrate your database.
* {@inheritdoc}
*/
public function createSchema()
{
$schema = new Schema();
$table = $schema->createTable('foo');
$table->addColumn('id', 'integer', array(
'autoincrement' => true,
));
$table->setPrimaryKey(array('id'));
return $schema;
}
}
The ``StubSchemaProvider`` provided with the migrations library is another option.
It simply takes a schema object to its constructor and returns it from ``createSchema``.
.. code-block:: php
<?php
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Migrations\Provider\StubSchemaProvider;
$schema = new Schema();
$table = $schema->createTable('foo');
$table->addColumn('id', 'integer', array(
'autoincrement' => true,
));
$table->setPrimaryKey(array('id'));
$provider = new StubSchemaProvider($schema);
$provider->createSchema() === $schema; // true
By default the ``doctrine-migrations`` command line tool will only add the diff
command if the ORM is present. Without the ORM, you'll have to add the diff command
to your `console application <http://symfony.com/doc/current/components/console/introduction.html>`_
manually, passing in your schema provider implementation to the diff command's constructor.
.. code-block:: php
<?php
use Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand;
$schemaProvider = new CustomSchemaProvider();
/** @var Symfony\Component\Console\Application */
$app->add(new DiffCommand($schemaProvider));
// ...
$app->run();
With the custom provider in place the diff command will compare the current database
state to the one provided. If there's a mismatch, the differences will be put
into the generated migration just like the ORM examples above.
Ignoring Custom Tables
----------------------
If you have custom tables which are not managed by doctrine you might face the situation
that with every diff task you are executing you get the remove statements for those tables
added to the migration class.
Therefore you can configure doctrine with a schema filter.
.. code-block:: php
$connection->getConfiguration()->setFilterSchemaAssetsExpression("~^(?!t_)~");
With this expression all tables prefixed with t_ will ignored by the schema tool.
If you use the DoctrineBundle with Symfony2 you can set the schema_filter option
in your configuration. You can find more information in the documentation of the
DoctrineMigationsBundle.
Creating Empty Migrations
-------------------------
Use the ``migrations:generate`` command to create an empty migration class.
.. code-block:: bash
$ ./doctrine migrations:generate
Generated new migration class to /path/to/migrations/DoctrineMigrations/Version20180107080000.php

View File

@@ -0,0 +1,41 @@
Input - Output Customization
============================
Behind the scenes Doctrine Migration uses ``\Symfony\Component\Console\Input\ArgvInput``
to capture and parse values from ``$_SERVER['argv']``.
You can customize the input like the following:
.. code-block:: php
require 'vendor/autoload.php'
$input = new \Symfony\Component\Console\Input\ArgvInput;
$input->setArgument('verbose', true);
return $input;
And the output similarly:
.. code-block:: php
require 'vendor/autoload.php'
// This is what Doctrine Migrations uses by default
$output = new \Symfony\Component\Console\Output\ConsoleOutput;
// Enable styling for HTML tags, which would otherwise throw errors
$htmlTags = array('p', 'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'b', 'i', 'strong', 'em', 'hr', 'br');
foreach ($htmlTags as $tag) {
$output->setStyle($tag); // Each tag gets default styling
}
return $output;
If you are using the phar it is still possible to customize the input and output but you
need to require the autoloader that's in the phar.
.. code-block:: php
require 'phar://migrations.phar/vendor/autoload.php';

View File

@@ -0,0 +1,114 @@
.. index::
single: Installation
Installation
============
You have two options, you can either use composer to install doctrine migrations or you can use the standalone Phar package.
Composer
~~~~~~~~
Install it with composer:
.. code-block:: sh
composer require doctrine/migrations
PHP Binary / PHAR
~~~~~~~~~~~~~~~~~
You can download the Migrations PHP Binary, which is a standalone PHAR package
file with all the required dependencies. You can drop that single file onto any server
and start using the Doctrine Migrations.
To register a system command for the migrations you can create a simple batch
script, for example on a \*nix Environment creating a `/usr/local/bin/doctrine-migrations`:
.. code-block:: bash
#!/bin/sh
php /path/to/doctrine-migrations.phar "$@"
You could now go and use the migrations like:
.. code-block:: bash
[shell]
myshell> doctrine-migrations
Because the PHAR file is standalone it does not rely on the Symfony Console 'db' Helper,
but you have to pass a `--db-configuration` parameter that points to a PHP file
which returns the parameters for `Doctrine\DBAL\DriverManager::getConnection($dbParams)`.
If you don't specify this option Doctrine Migrations will look for a `migrations-db.php`
file returning that parameters in your current directory and only throw an error if
that is not found.
Configuration
-------------
The last thing you need to do is to configure your migrations. You can do so
by using the *--configuration* option to manually specify the path
to a configuration file. If you don't specify any configuration file the tasks will
look for a file named *migrations.xml* or *migrations.yml* at the root of
your command line. For the upcoming examples you can use a *migrations.xml*
file like the following:
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-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>Doctrine Sandbox Migrations</name>
<migrations-namespace>DoctrineMigrations</migrations-namespace>
<table name="doctrine_migration_versions" />
<migrations-directory>/path/to/migrations/classes/DoctrineMigrations</migrations-directory>
</doctrine-migrations>
Of course you could do the same thing with a *migrations.yml* file:
.. code-block:: yaml
name: Doctrine Sandbox Migrations
migrations_namespace: DoctrineMigrations
table_name: doctrine_migration_versions
migrations_directory: /path/to/migrations/classes/DoctrineMigrations
With the above example, the migrations tool will search the ``migrations_directory``
recursively for files that begin with ``Version`` followed one to 255 characters
and a ``.php`` suffix. ``Version.{1,255}\.php`` is the regular expression that's
used.
Everything after ``Version`` will be treated as the actual version in
the database. Take the file name ``VersionSomeVersion.php``, ``SomeVersion`` would
be the version *number* stored in the migrations database table. Since versions
are ordered, doctrine :doc:`generates </reference/generating_migrations>` version
numbers with a date time like ``Version20150505120000.php``. This ensures that
the migrations are executed in the correct order.
While you *can* use custom filenames, it's probably a good idea to the Doctrine
:doc:`generate migration files </reference/generating_migrations>` for you.
And if you want to specify each migration manually in YAML you can:
.. code-block:: yaml
table_name: doctrine_migration_versions
migrations_directory: /path/to/migrations/classes/DoctrineMigrations
migrations:
migration1:
version: 20100704000000
class: DoctrineMigrations\NewMigration
If you specify your own migration classes (like `DoctrineMigrations\NewMigration` in the previous
example) you will need an autoloader unless all those classes begin with the prefix Version*,
for example path/to/migrations/classes/VersionNewMigration.php.

View File

@@ -0,0 +1,14 @@
Integrations
============
If you want to start quickly, there are integrations for a lot of frameworks already:
* `symfony 2 <https://packagist.org/packages/doctrine/doctrine-migrations-bundle>`_
* `ZF2 <https://packagist.org/packages/doctrine/doctrine-orm-module>`_
* `laravel <https://packagist.org/packages/laravel-doctrine/migrations>`_
* `Silex <https://packagist.org/packages/kurl/silex-doctrine-migrations-provider>`_
* `Silex <https://packagist.org/packages/dbtlr/silex-doctrine-migrations>`_
* `nette <https://packagist.org/packages/zenify/doctrine-migrations>`_
Don't hesitate to make a `Pull Request <https://github.com/doctrine/migrations>`_
if you want to add your integration to this list.

View File

@@ -0,0 +1,202 @@
.. index::
single: Introduction
Introduction
============
The Doctrine Migrations 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 powerful tool.
In order to use migrations you need to do some setup first.
Installation
------------
There are two ways to use the Doctrine Migrations project. Either as a supplement
to your already existing Doctrine DBAL (+ ORM) setup or as a standalone "PHP Binary"
(also known as PHAR).
Use as Supplement
~~~~~~~~~~~~~~~~~
To use the Migrations as supplement you have to get the sources from the GitHub
repository, either by downloading them, checking them out as SVN external or as Git Submodule.
Then you have to setup the class loader to load the classes for the `Doctrine\DBAL\Migrations`
namespace in your project:
.. code-block:: php
require_once '/path/to/migrations/lib/vendor/doctrine-common/Doctrine/Common/ClassLoader';
use Doctrine\Common\ClassLoader;
$classLoader = new ClassLoader('Doctrine\DBAL\Migrations', '/path/to/migrations/lib');
$classLoader->register();
Now the above autoloader is able to load a class like the following:
.. code-block:: bash
/path/to/migrations/lib/Doctrine/DBAL/Migrations/Migrations/Migration.php
Register Console Commands
~~~~~~~~~~~~~~~~~~~~~~~~~
Now that we have setup the autoloaders we are ready to add the migration console
commands to our `Doctrine Command Line Interface <http://doctrine-orm.readthedocs.org/en/latest/reference/tools.html#adding-own-commands>`_:
.. code-block:: php
// ...
$cli->addCommands(array(
// ...
// Migrations Commands
new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(),
new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand()
));
Additionally you have to make sure the 'db' and 'dialog' Helpers are added to your Symfony
Console HelperSet.
.. code-block:: php
$db = \Doctrine\DBAL\DriverManager::getConnection($params);
// or
$em = \Doctrine\ORM\EntityManager::create($params);
$db = $em->getConnection();
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($db),
'dialog' => new \Symfony\Component\Console\Helper\QuestionHelper(),
));
You will see that you have a few new commands when you execute the following command:
.. code-block:: bash
$ ./doctrine list migrations
Doctrine Command Line Interface version 2.0.0BETA3-DEV
Usage:
[options] command [arguments]
Options:
--help -h Display this help message.
--quiet -q Do not output any message.
--verbose -v Increase verbosity of messages.
--version -V Display this program version.
--color -c Force ANSI color output.
--no-interaction -n Do not ask any interactive question.
Available commands for the "migrations" namespace:
:diff Generate a migration by comparing your current database to your mapping information.
:execute Execute a single migration version up or down manually.
:generate Generate a blank migration class.
:migrate Execute a migration to a specified version or the latest available version.
:status View the status of a set of migrations.
:version Manually add and delete migration versions from the version table.
PHP Binary / PHAR
~~~~~~~~~~~~~~~~~
You can download the Migrations PHP Binary, which is a standalone PHAR package
file with all the required dependencies. You can drop that single file onto any server
and start using the Doctrine Migrations.
To register a system command for the migrations you can create a simple batch
script, for example on a \*nix Environment creating a `/usr/local/bin/doctrine-migrations`:
.. code-block:: bash
#!/bin/sh
php /path/to/doctrine-migrations.phar "$@"
You could now go and use the migrations like:
.. code-block:: bash
[shell]
myshell> doctrine-migrations
Because the PHAR file is standalone it does not rely on the Symfony Console 'db' Helper,
but you have to pass a `--db-configuration` parameter that points to a PHP file
which returns the parameters for `Doctrine\DBAL\DriverManager::getConnection($dbParams)`.
If you don't specify this option Doctrine Migrations will look for a `migrations-db.php`
file returning that parameters in your current directory and only throw an error if
that is not found.
Configuration
-------------
The last thing you need to do is to configure your migrations. You can do so
by using the *--configuration* option to manually specify the path
to a configuration file. If you don't specify any configuration file the tasks will
look for a file named *migrations.xml* or *migrations.yml* at the root of
your command line. For the upcoming examples you can use a *migrations.xml*
file like the following:
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-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>Doctrine Sandbox Migrations</name>
<migrations-namespace>DoctrineMigrations</migrations-namespace>
<table name="doctrine_migration_versions" />
<migrations-directory>/path/to/migrations/classes/DoctrineMigrations</migrations-directory>
</doctrine-migrations>
Of course you could do the same thing with a *configuration.yml* file:
.. code-block:: yaml
name: Doctrine Sandbox Migrations
migrations_namespace: DoctrineMigrations
table_name: doctrine_migration_versions
migrations_directory: /path/to/migrations/classes/DoctrineMigrations
With the above example, the migrations tool will search the ``migrations_directory``
recursively for files that begin with ``Version`` followed one to 255 characters
and a ``.php`` suffix. ``Version.{1,255}\.php`` is the regular expression that's
used.
Everything after ``Version`` will be treated as the actual version in
the database. Take the file name ``VersionSomeVersion.php``, ``SomeVersion`` would
be the version *number* stored in the migrations database table. Since versions
are ordered, doctrine :doc:`generates </reference/generating_migrations>` version
numbers with a date time like ``Version20150505120000.php``. This ensures that
the migrations are executed in the correct order.
While you *can* use custom filenames, it's probably a good idea to let Doctrine
:doc:`generate migration files </reference/generating_migrations>` for you.
And if you want to specify each migration manually in YAML you can:
.. code-block:: yaml
table_name: doctrine_migration_versions
migrations_directory: /path/to/migrations/classes/DoctrineMigrations
migrations:
migration1:
version: 20100704000000
class: DoctrineMigrations\NewMigration
If you specify your own migration classes (like `DoctrineMigrations\NewMigration` in the previous
example) you will need an autoloader unless all those classes begin with the prefix Version*,
for example path/to/migrations/classes/VersionNewMigration.php.

View File

@@ -0,0 +1,250 @@
.. index::
single: Managing Migrations
Managing Migrations
===================
Now that we have a new migration class present, lets run the status task to see
if it is there:
.. code-block:: bash
$ ./doctrine migrations:status
== Configuration
>> Name: Doctrine Sandbox Migrations
>> Database Driver: pdo_mysql
>> Database Name: testdb
>> Configuration Source: /Users/jwage/Sites/doctrine2git/tools/sandbox/migrations.xml
>> Version Table Name: doctrine_migration_versions
>> Migrations Namespace: DoctrineMigrations
>> Migrations Directory: /Users/jwage/Sites/doctrine2git/tools/sandbox/DoctrineMigrations
>> Current Version: 2010-04-16 13:04:22 (20100416130422)
>> Latest Version: 2010-04-16 13:04:22 (20100416130422)
>> Executed Migrations: 0
>> Available Migrations: 1
>> New Migrations: 1
== Migration Versions
>> 2010-04-16 13:04:01 (20100416130401) not migrated
As you can see we have a new version present and it is ready to be executed. The
problem is it does not have anything in it so nothing would be executed! Let's
add some code to it and add a new table:
.. code-block:: php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20100416130401 extends AbstractMigration
{
public function up(Schema $schema)
{
$table = $schema->createTable('users');
$table->addColumn('username', 'string');
$table->addColumn('password', 'string');
}
public function down(Schema $schema)
{
$schema->dropTable('users');
}
}
Now we are ready to give it a test! First lets just do a dry-run to make sure
it produces the SQL we expect:
.. code-block:: bash
$ ./doctrine migrations:migrate --dry-run
Are you sure you wish to continue?
y
Executing dry run of migration up to 20100416130452 from 0
>> migrating 20100416130452
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
Everything looks good so we can remove the *--dry-run* option and actually execute
the migration:
.. code-block:: bash
$ ./doctrine migrations:migrate
Are you sure you wish to continue?
y
Migrating up to 20100416130452 from 0
>> migrating 20100416130452
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
>> migrated
Alternately, if you wish to run the migrations in an unattended mode, we can add the *--no--interaction* option and then
execute the migrations without any extra prompting from Doctrine.
.. code-block:: bash
$ ./doctrine migrations:migrate --no-interaction
Migrating up to 20100416130452 from 0
>> migrating 20100416130452
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
>> migrated
By checking the status again after using either method you will see everything is updated:
.. code-block:: bash
$ ./doctrine migrations:status
== Configuration
>> Name: Doctrine Sandbox Migrations
>> Database Driver: pdo_mysql
>> Database Name: testdb
>> Configuration Source: /Users/jwage/Sites/doctrine2git/tools/sandbox/migrations.xml
>> Version Table Name: doctrine_migration_versions
>> Migrations Namespace: DoctrineMigrations
>> Migrations Directory: /Users/jwage/Sites/doctrine2git/tools/sandbox/DoctrineMigrations
>> Current Version: 2010-04-16 13:04:52 (20100416130452)
>> Latest Version: 2010-04-16 13:04:52 (20100416130452)
>> Executed Migrations: 1
>> Available Migrations: 1
>> New Migrations: 0
== Migration Versions
>> 2010-04-16 13:04:01 (20100416130452) migrated
Reverting Migrations
--------------------
You maybe noticed in the last example that we defined a *down()* method which
drops the users table that we created. This method allows us to easily revert
changes the schema has been migrated to. The *migrate* command takes a *version*
argument which you can use to roll back your schema to a specific version of
your migrations:
.. code-block:: bash
$ ./doctrine migrations:migrate first
Are you sure you wish to continue?
y
Migrating down to 0 from 20100416130422
-- reverting 20100416130422
-> DROP TABLE addresses
-- reverted
-- reverting 20100416130401
-> DROP TABLE users
-- reverted
Now our database is back to where we originally started. Give it a check with
the status command:
.. code-block:: bash
$ ./doctrine migrations:status
== Configuration
>> Name: Doctrine Sandbox Migrations
>> Database Driver: pdo_mysql
>> Database Name: testdb
>> Configuration Source: /Users/jwage/Sites/doctrine2git/tools/sandbox/migrations.xml
>> Version Table Name: doctrine_migration_versions
>> Migrations Namespace: DoctrineMigrations
>> Migrations Directory: /Users/jwage/Sites/doctrine2git/tools/sandbox/DoctrineMigrations
>> Current Version: 0
>> Latest Version: 2010-04-16 13:04:22 (20100416130422)
>> Executed Migrations: 0
>> Available Migrations: 2
>> New Migrations: 2
== Migration Versions
>> 2010-04-16 13:04:01 (20100416130401) not migrated
>> 2010-04-16 13:04:22 (20100416130422) not migrated
Aliases
-------
There are some shortcut for convenience (first, prev, next, latest).
So that you don't have to know the name of the migration.
You can just call
.. code-block:: bash
$ ./doctrine migrations:migrate prev
Writing Migration SQL Files
---------------------------
You can optionally choose to not execute a migration directly on a database and
instead output all the SQL statements to a file. This is possible by using the
*--write-sql* option of the *migrate* command:
.. code-block:: bash
$ ./doctrine migrations:migrate --write-sql
Executing dry run of migration up to 20100416130422 from 0
>> migrating 20100416130401
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
>> migrating 20100416130422
-> CREATE TABLE addresses (id INT NOT NULL, street VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB
Writing migration file to "/path/to/sandbox/doctrine_migration_20100416130405.sql"
Now if you have a look at the *doctrine_migration_20100416130405.sql* file you will see the would be
executed SQL outputted in a nice format:
.. code-block:: bash
# Doctrine Migration File Generated on 2010-04-16 13:04:05
# Migrating from 0 to 20100416130422
# Version 20100416130401
CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB;
# Version 20100416130422
CREATE TABLE addresses (id INT NOT NULL, street VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
.. _managing-versions-table:
Managing the Version Table
--------------------------
Sometimes you may need to manually change something in the database table which
manages the versions for some migrations. For this you can use the version task.
You can easily add a version like this:
.. code-block:: bash
$ ./doctrine migrations:version YYYYMMDDHHMMSS --add
Or you can delete that version:
.. code-block:: bash
$ ./doctrine migrations:version YYYYMMDDHHMMSS --delete
The command does not execute any migrations code, it simply adds the specified
version to the database.

View File

@@ -0,0 +1,89 @@
Migration Classes
=================
As now everything is setup and configured you are ready to start writing
migration classes. You can easily generate your first migration class with the
following command:
.. code-block:: bash
$ ./doctrine migrations:generate
Generated new migration class to "/path/to/migrations/classes/DoctrineMigrations/Version20100416130401.php"
Have a look and you will see a new class at the above location that looks like
the following:
.. code-block:: php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20100416130401 extends AbstractMigration
{
public function up(Schema $schema)
{
}
public function down(Schema $schema)
{
}
}
You can now use the *addSql()* method within the up and down method.
Internally the addSql call are passed to the `dbal executeQuery method`_.
This means that you can use the power of the prepared statement easilly and that you don't need to copy paste the same
query with different parameters. You can just pass those differents parameters to the addSql method as parameters.
.. code-block:: php
public function up(Schema $schema)
{
$users = array(
array('name' => 'mike', 'id' => 1),
array('name' => 'jwage', 'id' => 2),
array('name' => 'ocramius', 'id' => 3),
);
foreach ($users as $user) {
$this->addSql('UPDATE user SET happy = true WHERE name = :name AND id = :id', $user);
}
}
For more infos on `how the doctrine dbal executeQuery method works go tho the doctrine dbal documentation`_.
Additionally, there is also the preUp, postUp and preDown, postDown method, that are respectivelly called before and
after the up and down method are called.
First you need to generate a new migration class:
.. code-block:: bash
$ ./doctrine migrations:generate
Generated new migration class to "/path/to/migrations/DoctrineMigrations/Version20100416130422.php"
This newly generated migration class is the place where you can add your own
custom SQL queries:
.. code-block:: php
namespace DoctrineMigrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
class Version20100416130422 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->addSql('CREATE TABLE addresses (id INT NOT NULL, street VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB');
}
public function down(Schema $schema)
{
$this->addSql('DROP TABLE addresses');
}
}

View File

@@ -0,0 +1,76 @@
Version Numbers
===============
When :doc:`Generating Migrations <generating_migrations>` the newly created
classes are generated with the name ``Version{date}`` with ``{date}`` having a
``YmdHis`` `format <http://php.net/manual/en/function.date.php>`_. This format
is important as it allows the migrations to be correctly ordered.
Starting with version 1.5 when loading migration classes, Doctrine Migrations
does a ``sort($versions, SORT_STRING)`` on version numbers. This can cause
problems with custom version numbers:
.. code-block:: php
<?php
$versions = [
'Version1',
'Version2',
// ...
'Version10',
];
sort($versions, SORT_STRING);
var_dump($versions);
/*
array(3) {
[0] =>
string(8) "Version1"
[1] =>
string(9) "Version10"
[2] =>
string(8) "Version2"
}
*/
The custom version numbers above end up out of order which may cause damage
to a database.
It's **strongly recommended** that the ``Version{date}`` migration class name
format is kept to and that the various :doc:`tools for generating migrations <generating_migrations>`
be used.
Should some custom migration numbers be necessary, keeping the version number
the same length as the date format (14 total characters) and padding it to the
left with zeros should work.
.. code-block:: php
<?php
$versions = [
'Version00000000000001',
'Version00000000000002',
// ...
'Version00000000000010',
'Version20180107070000', // generated version
];
sort($versions, SORT_STRING);
var_dump($versions);
/*
array(4) {
[0] =>
string(21) "Version00000000000001"
[1] =>
string(21) "Version00000000000002"
[2] =>
string(21) "Version00000000000010"
[3] =>
string(21) "Version20180107070000"
}
*/
Please note that migrating to this new, zero-padded format may require
:ref:`manual version table intervention <managing-versions-table>` if the
versions have previously been applied.

View File

@@ -0,0 +1,14 @@
.. toctree::
:depth: 3
reference/introduction
reference/installation
reference/integration
reference/building_framework_specific_integration
reference/migration_classes
reference/managing_migrations
reference/generating_migrations
reference/custom_configuration
reference/input_output_customization
reference/events
reference/version_numbers