Doctrine2 migrations migrate down and migrate from browser and not command line

I am using Doctrine2 migrations. I need some answers about my doubt, I canno find a good solution in documentations

I use:

  doctrine migrations:diff // generate migrations files
  doctrine migrations:migrate // migrates up to new version
  1. How Can I migrate down? specifying the previous version did not work ( nothing to update it says f.e. doctrine migrations:migrate Version20120211163332 it says

    Migrating up to Version20120211163332 from 20120309112058
    
    [Doctrine\DBAL\Migrations\MigrationException]  
    Could not find any migrations to execute.      
    

    But it's not up it should be down! you can see also on versions in response

  2. If I have to make some DB update, is it possible to add some SQL Queries in additions ( alter some datas related to other) ? I have not tried still since the down is not working :((

  3. Is there any way to use the migrate command in a browser nutshell ? I have sw in a shared hosting without console access so I need this feature, instead of copying queries one by one :D in phpMyAdmin


Solution 1:

You can optionally manually specify the version you wish to migrate to:

 php doctrine.php migrations:migrate YYYYMMDDHHMMSS

or execute a migration up/down

php doctrine.php migrations:execute YYYYMMDDHHMMSS  --down
php doctrine.php migrations:execute YYYYMMDDHHMMSS  --up

You can found YYYYMMDDHHMMSS using:

php doctrine.php migrations:status
>> Current Version:           2012-12-20 23:38:47 (20121220233847)
>> Latest Version:            2012-12-20 23:38:47 (20121220233847)

Solution 2:

I saw this doc on Symfony's website : http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html#usage

There is doctrine:migrations:execute that allows you to execute a single migration version up or down manually... but never tried, sorry.

Hope this helps !

Keep us posted.

Solution 3:

If you want to migrate 1 step down, you can use this syntax:

./doctrine migrations:migrate prev

To go to the first migration:

./doctrine migrations:migrate first

To go to the next migration:

./doctrine migrations:migrate next

Source: https://www.doctrine-project.org/projects/doctrine-migrations/en/1.8/reference/managing_migrations.html#managing-migrations

Solution 4:

Here is how you can run migrations from browser:

composer.json

{
    "require": {
        "doctrine/dbal": "*",
        "doctrine/migrations": "dev-master"
    },
    "minimum-stability": "dev",
    "autoload": {
        "psr-0": {"": "src/"}
    }
}

src/Acme/Migrations/Version1.php

<?php # src/Acme/Migrations/Version1.php
namespace Acme\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Class Version1
 *
 * Notice that file and class names MUST be Version*.php
 *
 * @package Acme\Migrations
 */
class Version1 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $users = $schema->createTable('users');
        $users->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
        $users->addColumn('username', 'string', array('length' => 128));
        $users->addColumn('password', 'string', array('length' => 128));
        $users->setPrimaryKey(array('id'));

        // You can also add any queries
        // $this->addSql('CREATE TABLE addresses (id INT NOT NULL, street VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB');
    }

    public function down(Schema $schema)
    {
        $schema->dropTable('users');

        //$this->addSql('DROP TABLE addresses');
    }

    // Use this functions to prepare your migrations
    //public function preUp(Schema $schema) {}
    //public function postUp(Schema $schema) {}
    //public function preDown(Schema $schema) {}
    //public function postDown(Schema $schema) {}
}

index.php

<?php # index.php
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Migrations\Configuration\Configuration;
use Doctrine\DBAL\Migrations\Migration;
use Doctrine\DBAL\Migrations\OutputWriter;

require_once 'vendor/autoload.php';

$nl = PHP_SAPI == 'cli' ? PHP_EOL : '<br>'; // Optional will be used for output

$to = null; // Optional integer - migrate to version, if null - will migrate to latest available version
#region Optional get argument
$index = PHP_SAPI == 'cli' ? 1 : 'to';
$arguments = PHP_SAPI == 'cli' ? $argv : $_REQUEST;
$to = isset($arguments[$index]) && filter_var($arguments[$index], FILTER_VALIDATE_INT) ? intval($arguments[$index]) : null;
#endregion

#region Doctrine Connection
// Silex: $app['db']
// Symfony controller: $this->get('database_connection')
$db = DriverManager::getConnection(array(
    'dbname' => 'doctine_migrations',
    'user' => 'root',
    'password' => 'root',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
    'charset' => 'utf8',
    'driverOptions' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
    )
));
#endregion

#region Config
$config = new Configuration($db /*, new OutputWriter(function ($message) { echo $message . PHP_EOL; })*/); // OutputWriter is optional and by default do nothing, accepts closure for writing logs

//$config->setName('My Migrations'); // Optional name for your migrations
$config->setMigrationsTableName('version'); // Table name that will store migrations log (will be created automatically, default name is: doctrine_migration_versions)
$config->setMigrationsNamespace('Acme\\Migrations'); // Namespace of your migration classes, do not forget escape slashes, do not add last slash
$config->setMigrationsDirectory('src/Acme/Migrations'); // Directory where your migrations are located
$config->registerMigrationsFromDirectory($config->getMigrationsDirectory()); // Load your migrations
#endregion

$migration = new Migration($config); // Create Migration based on provided configuration

$versions = $migration->getSql($to); // Retrieve SQL queries that should be run to migrate you schema to $to version, if $to == null - schema will be migrated to latest version

#region Some dummy output
foreach ($versions as $version => $queries) {
    echo 'VERSION: ' . $version . $nl;
    echo '----------------------------------------------' . $nl . $nl;

    foreach ($queries as $query) {
        echo $query . $nl . $nl;
    }

    echo $nl . $nl;
}
#endregion

try {
    $migration->migrate($to); // Execute migration!
    echo 'DONE' . $nl;
} catch (Exception $ex) {
    echo 'ERROR: ' . $ex->getMessage() . $nl;
}

Now you can:

Run it from console:

php index.php - will migrate to lates version

php index.php 2 - will migrate to version 2 (if current version is bigger - it will migrate down

Run from web browser:

http://localhost/index.php and http://localhost/index.php?to=2 will do the same.

Solution 5:

In my case it looks like below:

Reverting changes:

php bin/console doctrine:migrations:execute "VendorName\ProjectName\Account\Migrations\Version20201002092643" --down

Processing migration:

php bin/console doctrine:migrations:execute "VendorName\ProjectName\Account\Migrations\Version20201002092643" --up

or just

php bin/console doctrine:migrations:execute "VendorName\ProjectName\Account\Migrations\Version20201002092643"

and my Symfony configuration for migrations looks as below:

doctrine_migrations:
    migrations_paths:
        # namespace is arbitrary but should be different from App\Migrations
        # as migrations classes should NOT be autoloaded
        'DoctrineMigrations': '%kernel.project_dir%/migrations'
        'VendorName\ProjectName\Account\Migrations': '%kernel.project_dir%/component/account/migrations'