Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Several improvements and fixes #1

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 42 additions & 14 deletions Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,24 @@

namespace ZendDbMigrations;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;

class Module implements
AutoloaderProviderInterface,
ConfigProviderInterface,
ConsoleUsageProviderInterface,
ConsoleBannerProviderInterface
ConsoleUsageProviderInterface
{

public function onBootstrap($e)
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
Expand All @@ -46,17 +46,45 @@ public function getAutoloaderConfig()
),
);
}

public function getConsoleBanner(Console $console){
return 'DB Migrations Module';

public function getServiceConfig()
{
return array(
'factories' => array(
'ZendDbMigrations\Model\MigrationVersionTable' => function ($sm) {
/** @var $sm */
$tableGateway = $sm->get('MigrationVersionTableGateway');
$table = new Model\MigrationVersionTable($tableGateway);
return $table;
},
'MigrationVersionTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\MigrationVersion());
return new TableGateway(Library\Migration::MIGRATION_TABLE, $dbAdapter, null, $resultSetPrototype);
},
),
);
}

public function getConsoleUsage(Console $console){
//description command
public function getConsoleUsage(Console $console)
{
return array(
'db_migrations_version' => 'Get current migration version',
'db_migrations_migrate [<version>]' => 'Execute migrate',
'db_migrations_generate' => 'Generate new migration class'
'Migrations',

'migration version' => 'Get current migration version',

'migration list [--all]' => 'List available migrations',
array('--all', 'Include applied migrations'),

'migration migrate [<version>]' => 'Execute migrate',
array(
'--force',
'Force apply migration even if it\'s older than the last migrated. Works only with <version> explicitly set.'
),
array('--down', 'Force apply down migration. Works only with --force flag set.'),

'migration generate' => 'Generate new migration class'
);
}
}
34 changes: 21 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
ZendDbMigrations
============

## Try new module based on this fork [ZfSimpleMigrations](https://github.com/vgarvardt/ZfSimpleMigrations).
## Fork is abandoned due to original module author not responding to issues and requests.

Установка
-------------
Добавьте в composer.json проекта в секцию require
Expand All @@ -18,9 +21,10 @@ php composer.phar update
Список добавляемых консольных комманд

``` bash
db_migrations_version - возвращает номер текущей версии
db_migrations_migrate [<version>] - выполнить или откатить миграцию, номер версии необязательный параметр
db_migrations_generate - Сгенерировать каркас класса миграции
migration version - возвращает номер текущей версии
migration list [--all] - выводит список доступных миграций
migration migrate [<version>] [--force] [--down] - выполнить или откатить миграцию, номер версии необязательный параметр
migration generate - Сгенерировать каркас класса миграции
```

Все миграции по умолчанию будут хранится в каталоге
Expand All @@ -39,22 +43,26 @@ namespace ZendDbMigrations\Migrations;
use ZendDbMigrations\Library\AbstractMigration;
use Zend\Db\Metadata\MetadataInterface;

class Version20121112230913 extends AbstractMigration {

public function up(MetadataInterface $schema){
class Version20121112230913 extends AbstractMigration
{
public static $description = "Migration description";

public function up(MetadataInterface $schema)
{
//$this->addSql(/*Sql instruction*/);
}

public function down(MetadataInterface $schema){

public function down(MetadataInterface $schema)
{
//$this->addSql(/*Sql instruction*/);
}
}
```

выполнить миграцию можно двумя способами
запустив команду db_migrations_migrate без параметров
или с указанием версии
db_migrations_migrate 20121112230913
Version20121112230913 - здесь 20121112230913 будет версией миграции
* запустив команду migration migrate без параметров
* или с указанием версии
* `migration migrate 20121112230913`
* `Version20121112230913` - здесь `20121112230913` будет версией миграции

http://vadim-knyzev.blogspot.com/
http://vadim-knyzev.blogspot.com/
5 changes: 5 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
"name": "Vadim Knyzev",
"email": "[email protected]",
"homepage": "http://vadim-knyzev.blogspot.com/"
},
{
"name": "Vladimir Garvardt",
"email": "[email protected]",
"homepage": "http://www.linkedin.com/in/vgarvardt/"
}
],
"require": {
Expand Down
34 changes: 22 additions & 12 deletions config/module.config.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,43 @@
'console' => array(
'router' => array(
'routes' => array(
'db_migrations_version' => array(
'type' => 'simple',
'migration-version' => array(
'type' => 'simple',
'options' => array(
'route' => 'db_migrations_version [--env=]',
'route' => 'migration version [--env=]',
'defaults' => array(
'controller' => 'ZendDbMigrations\Controller\Migrate',
'action' => 'version'
'action' => 'version'
)
)
),
'db_migrations_migrate' => array(
'type' => 'simple',
'migration-list' => array(
'type' => 'simple',
'options' => array(
'route' => 'db_migrations_migrate [<version>] [--env=]',
'route' => 'migration list [--env=] [--all]',
'defaults' => array(
'controller' => 'ZendDbMigrations\Controller\Migrate',
'action' => 'migrate'
'action' => 'list'
)
)
),
'db_migrations_generate' => array(
'type' => 'simple',
'migration-migrate' => array(
'type' => 'simple',
'options' => array(
'route' => 'db_migrations_generate [--env=]',
'route' => 'migration migrate [<version>] [--env=] [--force] [--down]',
'defaults' => array(
'controller' => 'ZendDbMigrations\Controller\Migrate',
'action' => 'generateMigrationClass'
'action' => 'migrate'
)
)
),
'migration-generate' => array(
'type' => 'simple',
'options' => array(
'route' => 'migration generate [--env=]',
'defaults' => array(
'controller' => 'ZendDbMigrations\Controller\Migrate',
'action' => 'generateMigrationClass'
)
)
)
Expand Down
110 changes: 70 additions & 40 deletions src/ZendDbMigrations/Controller/MigrateController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
namespace ZendDbMigrations\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Mvc\MvcEvent;
use Zend\Console\Request as ConsoleRequest;
use ZendDbMigrations\Library\Migration;
use ZendDbMigrations\Library\MigrationException;
Expand All @@ -23,67 +23,97 @@
class MigrateController extends AbstractActionController
{
/**
* Создать объект класса миграций
* @return \Migrations\Library\Migration
* @var \ZendDbMigrations\Library\Migration
*/
protected function getMigration(){
protected $migration;
/**
* @var \ZendDbMigrations\Model\MigrationVersionTable
*/
protected $migrationVersionTable;
/**
* @var OutputWriter
*/
protected $output;

public function onDispatch(MvcEvent $e)
{
if (!$this->getRequest() instanceof ConsoleRequest) {
throw new \RuntimeException('You can only use this action from a console!');
}

/** @var $adapter \Zend\Db\Adapter\Adapter */
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$config = $this->getServiceLocator()->get('Configuration');

$console = $this->getServiceLocator()->get('console');

$output = null;

if($config['migrations']['show_log'])
{
$output = new OutputWriter(function($message) use($console) {
$console->write($message . "\n");
});

if ($config['migrations']['show_log']) {
$this->output = new OutputWriter(function ($message) use ($console) {
$console->write($message . "\n");
});
}

return new Migration($adapter, $config['migrations']['dir'], $config['migrations']['namespace'], $output);

$this->migrationVersionTable = $this->getServiceLocator()->get('ZendDbMigrations\Model\MigrationVersionTable');
$this->migration = new Migration($adapter, $config['migrations'], $this->migrationVersionTable, $this->output);

return parent::onDispatch($e);
}

/**
* Получить текущую версию миграции
* @return integer
*/
public function versionAction(){
$migration = $this->getMigration();

return sprintf("Current version %s\n", $migration->getCurrentVersion());
public function versionAction()
{
return sprintf("Current version %s\n", $this->migrationVersionTable->getCurrentVersion());
}

public function listAction()
{
$migrations = $this->migration->getMigrationClasses($this->getRequest()->getParam('all'));
$list = array();
foreach ($migrations as $m) {
$list[] = sprintf("%s %s - %s", $m['applied'] ? '-' : '+', $m['version'], $m['description']);
}
return (empty($list) ? 'No migrations to execute.' : implode("\n", $list)) . "\n";
}

/**
* Мигрировать
*/
public function migrateAction(){
$migration = $this->getMigration();

public function migrateAction()
{
$version = $this->getRequest()->getParam('version');

if(is_null($version) && $migration->getCurrentVersion() >= $migration->getMaxMigrationNumber($migration->getMigrationClasses()))

$migrations = $this->migration->getMigrationClasses();
$currentMigrationVersion = $this->migrationVersionTable->getCurrentVersion();
$force = $this->getRequest()->getParam('force');

if (is_null($version) && $force) {
return "Can't force migrate without migration version explicitly set.";
}
if (!$force && is_null($version) && $currentMigrationVersion >= $this->migration->getMaxMigrationNumber($migrations)) {
return "No migrations to execute.\n";

try{
$migration->migrate($version);
return "Migrations executed!\n";
}
catch (MigrationException $e) {
return "ZendDbMigrations\Library\MigrationException\n" . $e->getMessage() . "\n";

try {
$this->migration->migrate($version, $force, $this->getRequest()->getParam('down'));
return "Migrations executed!\n";
} catch (MigrationException $e) {
return "ZendDbMigrations\\Library\\MigrationException\n" . $e->getMessage() . "\n";
}
}

/**
* Сгенерировать каркасный класс для новой миграции
*/
public function generateMigrationClassAction(){
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
public function generateMigrationClassAction()
{
$config = $this->getServiceLocator()->get('Configuration');

$generator = new GeneratorMigrationClass($config['migrations']['dir'], $config['migrations']['namespace']);
$className = $generator->generate();
return sprintf("Generated class %s\n", $className);
$classPath = $generator->generate();

return sprintf("Generated class %s\n", realpath($classPath));
}
}
}
12 changes: 0 additions & 12 deletions src/ZendDbMigrations/Library/AbstractMigration.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,6 @@ public function getDownSql(){

return $this->sql;
}

/**
* Выполнить миграцию
* @param MetadataInterface $schema
*/
abstract public function up(MetadataInterface $schema);

/**
* Откатить миграцию
* @param MetadataInterface $schema
*/
abstract public function down(MetadataInterface $schema);
}

?>
Loading