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

Add Dump command for new backend #698

Merged
merged 4 commits into from
Mar 19, 2024
Merged
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
123 changes: 123 additions & 0 deletions src/Command/DumpCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);

/**
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations\Command;

use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Database\Connection;
use Cake\Datasource\ConnectionManager;
use Migrations\Config\ConfigInterface;
use Migrations\Migration\ManagerFactory;
use Migrations\TableFinderTrait;

/**
* Dump command class.
* A "dump" is a snapshot of a database at a given point in time. It is stored in a
* .lock file in the same folder as migrations files.
*/
class DumpCommand extends Command
{
use TableFinderTrait;

protected string $connection;

/**
* The default name added to the application command list
*
* @return string
*/
public static function defaultName(): string
{
return 'migrations dump';
}

/**
* Configure the option parser
*
* @param \Cake\Console\ConsoleOptionParser $parser The option parser to configure
* @return \Cake\Console\ConsoleOptionParser
*/
public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser->setDescription([
'Dumps the current scheam of the database to be used while baking a diff',
'',
'<info>migrations dump -c secondary</info>',
])->addOption('plugin', [
'short' => 'p',
'help' => 'The plugin to dump migrations for',
])->addOption('connection', [
'short' => 'c',
'help' => 'The datasource connection to use',
'default' => 'default',
])->addOption('source', [
'short' => 's',
'help' => 'The folder under src/Config that migrations are in',
'default' => ConfigInterface::DEFAULT_MIGRATION_FOLDER,
]);

return $parser;
}

/**
* Execute the command.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return int|null The exit code or null for success
*/
public function execute(Arguments $args, ConsoleIo $io): ?int
{
$factory = new ManagerFactory([
'plugin' => $args->getOption('plugin'),
'source' => $args->getOption('source'),
'connection' => $args->getOption('connection'),
]);
$config = $factory->createConfig();
$path = $config->getMigrationPaths()[0];
$connectionName = (string)$config->getConnection();
$connection = ConnectionManager::get($connectionName);
assert($connection instanceof Connection);

$collection = $connection->getSchemaCollection();
$options = [
'require-table' => false,
'plugin' => $args->getOption('plugin'),
];
// The connection property is used by the trait methods.
$this->connection = $connectionName;
$tables = $this->getTablesToBake($collection, $options);

$dump = [];
if ($tables) {
foreach ($tables as $table) {
$schema = $collection->describe($table);
$dump[$table] = $schema;
}
}

$filePath = $path . DS . 'schema-dump-' . $connectionName . '.lock';
$io->out("<info>Writing dump file `{$filePath}`...</info>");
if (file_put_contents($filePath, serialize($dump))) {
$io->out("<info>Dump file `{$filePath}` was successfully written</info>");

return self::CODE_SUCCESS;
}
$io->out("<error>An error occurred while writing dump file `{$filePath}`</error>");

Check warning on line 119 in src/Command/DumpCommand.php

View check run for this annotation

Codecov / codecov/patch

src/Command/DumpCommand.php#L119

Added line #L119 was not covered by tests

return self::CODE_ERROR;

Check warning on line 121 in src/Command/DumpCommand.php

View check run for this annotation

Codecov / codecov/patch

src/Command/DumpCommand.php#L121

Added line #L121 was not covered by tests
}
}
92 changes: 8 additions & 84 deletions src/Command/MigrateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,11 @@
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Console\Exception\StopException;
use Cake\Core\Plugin;
use Cake\Datasource\ConnectionManager;
use Cake\Event\EventDispatcherTrait;
use Cake\Utility\Inflector;
use DateTime;
use Exception;
use Migrations\Config\Config;
use Migrations\Config\ConfigInterface;
use Migrations\Migration\Manager;
use Migrations\Migration\ManagerFactory;
use Throwable;

/**
Expand Down Expand Up @@ -92,83 +87,6 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar
return $parser;
}

/**
* Generate a configuration object for the migrations operation.
*
* @param \Cake\Console\Arguments $args The console arguments
* @return \Migrations\Config\Config The generated config instance.
*/
protected function getConfig(Arguments $args): Config
{
$folder = (string)$args->getOption('source');

// Get the filepath for migrations and seeds(not implemented yet)
$dir = ROOT . DS . 'config' . DS . $folder;
if (defined('CONFIG')) {
$dir = CONFIG . $folder;
}
$plugin = $args->getOption('plugin');
if ($plugin && is_string($plugin)) {
$dir = Plugin::path($plugin) . 'config' . DS . $folder;
}

// Get the phinxlog table name. Plugins have separate migration history.
// The names and separate table history is something we could change in the future.
$table = 'phinxlog';
if ($plugin && is_string($plugin)) {
$prefix = Inflector::underscore($plugin) . '_';
$prefix = str_replace(['\\', '/', '.'], '_', $prefix);
$table = $prefix . $table;
}
$templatePath = dirname(__DIR__) . DS . 'templates' . DS;
$connectionName = (string)$args->getOption('connection');

// TODO this all needs to go away. But first Environment and Manager need to work
// with Cake's ConnectionManager.
$connectionConfig = ConnectionManager::getConfig($connectionName);
if (!$connectionConfig) {
throw new StopException("Could not find connection `{$connectionName}`");
}

/** @var array<string, string> $connectionConfig */
$adapter = $connectionConfig['scheme'] ?? null;
$adapterConfig = [
'adapter' => $adapter,
'connection' => $connectionName,
'database' => $connectionConfig['database'],
'migration_table' => $table,
'dryrun' => $args->getOption('dry-run'),
];

$configData = [
'paths' => [
'migrations' => $dir,
],
'templates' => [
'file' => $templatePath . 'Phinx/create.php.template',
],
'migration_base_class' => 'Migrations\AbstractMigration',
'environment' => $adapterConfig,
// TODO do we want to support the DI container in migrations?
];

return new Config($configData);
}

/**
* Get the migration manager for the current CLI options and application configuration.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The command io.
* @return \Migrations\Migration\Manager
*/
protected function getManager(Arguments $args, ConsoleIo $io): Manager
{
$config = $this->getConfig($args);

return new Manager($config, $io);
}

/**
* Execute the command.
*
Expand Down Expand Up @@ -201,7 +119,13 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int
$date = $args->getOption('date');
$fake = (bool)$args->getOption('fake');

$manager = $this->getManager($args, $io);
$factory = new ManagerFactory([
'plugin' => $args->getOption('plugin'),
'source' => $args->getOption('source'),
'connection' => $args->getOption('connection'),
'dry-run' => $args->getOption('dry-run'),
]);
$manager = $factory->createManager($io);
$config = $manager->getConfig();

$versionOrder = $config->getVersionOrder();
Expand Down
94 changes: 10 additions & 84 deletions src/Command/StatusCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,8 @@
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Console\Exception\StopException;
use Cake\Core\Plugin;
use Cake\Datasource\ConnectionManager;
use Cake\Utility\Inflector;
use Migrations\Config\Config;
use Migrations\Config\ConfigInterface;
use Migrations\Migration\Manager;
use Migrations\Migration\ManagerFactory;

/**
* Status command for built in backend
Expand Down Expand Up @@ -89,83 +84,6 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar
return $parser;
}

/**
* Generate a configuration object for the migrations operation.
*
* @param \Cake\Console\Arguments $args The console arguments
* @return \Migrations\Config\Config The generated config instance.
*/
protected function getConfig(Arguments $args): Config
{
$folder = (string)$args->getOption('source');

// Get the filepath for migrations and seeds(not implemented yet)
$dir = ROOT . '/config/' . $folder;
if (defined('CONFIG')) {
$dir = CONFIG . $folder;
}
$plugin = $args->getOption('plugin');
if ($plugin && is_string($plugin)) {
$dir = Plugin::path($plugin) . 'config/' . $folder;
}

// Get the phinxlog table name. Plugins have separate migration history.
// The names and separate table history is something we could change in the future.
$table = 'phinxlog';
if ($plugin && is_string($plugin)) {
$prefix = Inflector::underscore($plugin) . '_';
$prefix = str_replace(['\\', '/', '.'], '_', $prefix);
$table = $prefix . $table;
}
$templatePath = dirname(__DIR__) . DS . 'templates' . DS;
$connectionName = (string)$args->getOption('connection');

// TODO this all needs to go away. But first Environment and Manager need to work
// with Cake's ConnectionManager.
$connectionConfig = ConnectionManager::getConfig($connectionName);
if (!$connectionConfig) {
throw new StopException("Could not find connection `{$connectionName}`");
}

/** @var array<string, string> $connectionConfig */
$adapter = $connectionConfig['scheme'] ?? null;
$adapterConfig = [
'adapter' => $adapter,
'connection' => $connectionName,
'database' => $connectionConfig['database'],
'migration_table' => $table,
'dryrun' => $args->getOption('dry-run'),
];

$configData = [
'paths' => [
'migrations' => $dir,
],
'templates' => [
'file' => $templatePath . 'Phinx/create.php.template',
],
'migration_base_class' => 'Migrations\AbstractMigration',
'environment' => $adapterConfig,
// TODO do we want to support the DI container in migrations?
];

return new Config($configData);
}

/**
* Get the migration manager for the current CLI options and application configuration.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The command io.
* @return \Migrations\Migration\Manager
*/
protected function getManager(Arguments $args, ConsoleIo $io): Manager
{
$config = $this->getConfig($args);

return new Manager($config, $io);
}

/**
* Execute the command.
*
Expand All @@ -177,7 +95,15 @@ public function execute(Arguments $args, ConsoleIo $io): ?int
{
/** @var string|null $format */
$format = $args->getOption('format');
$migrations = $this->getManager($args, $io)->printStatus($format);

$factory = new ManagerFactory([
'plugin' => $args->getOption('plugin'),
'source' => $args->getOption('source'),
'connection' => $args->getOption('connection'),
'dry-run' => $args->getOption('dry-run'),
]);
$manager = $factory->createManager($io);
$migrations = $manager->printStatus($format);

switch ($format) {
case 'json':
Expand Down
2 changes: 1 addition & 1 deletion src/Config/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public function getSeedBaseClassName(bool $dropNamespace = true): string
*/
public function getConnection(): string|false
{
return $this->values['connection'] ?? false;
return $this->values['environment']['connection'] ?? false;
}

/**
Expand Down
Loading
Loading