Skip to content

Commit

Permalink
Merge pull request #75 from phalcon/feature/#11-option-skip-foreign-c…
Browse files Browse the repository at this point in the history
…hecks

#11 - Added new option to skip foreign checks
  • Loading branch information
Jeckerson authored Mar 22, 2020
2 parents 9f5edfc + 630c8e2 commit 9ac61ce
Show file tree
Hide file tree
Showing 12 changed files with 210 additions and 33 deletions.
8 changes: 4 additions & 4 deletions phalcon-migrations
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ try {
$command = new Migration($parser);
$command->run();
} catch (CommandsException $commandsException) {
echo Color::error($commandsException->getMessage());
echo Color::error($commandsException->getMessage(), 'Exception Error: ');
exit(1);
} catch (RuntimeException $runtimeException) {
echo Color::error($runtimeException->getMessage());
echo Color::error($runtimeException->getMessage(), 'Runtime Error: ');
exit(1);
} catch (DbException $dbException) {
echo Color::error($dbException->getMessage());
echo Color::error($dbException->getMessage(), 'DB Error: ');
exit(1);
}
} catch (Throwable $e) {
fwrite(STDERR, 'FATAL ERROR: ' . $e->getMessage() . PHP_EOL);
echo Color::fatal($e->getMessage());
exit(1);
}
24 changes: 22 additions & 2 deletions src/Console/Color.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,12 @@ public static function head(string $msg): string
*
* @static
* @param string $msg
* @param string $prefix
* @return string
*/
public static function error(string $msg): string
public static function error(string $msg, string $prefix = 'Error: '): string
{
$msg = 'Error: ' . $msg;
$msg = $prefix . $msg;
$space = self::tabSpaces($msg);
$out = static::colorize(str_pad(' ', $space), Color::FG_WHITE, Color::AT_BOLD, Color::BG_RED) . PHP_EOL;
$out .= static::colorize(' ' . $msg . ' ', Color::FG_WHITE, Color::AT_BOLD, Color::BG_RED) . PHP_EOL;
Expand All @@ -187,6 +188,25 @@ public static function error(string $msg): string
return $out;
}

/**
* Color style for fatal error messages.
*
* @static
* @param string $msg
* @param string $prefix
* @return string
*/
public static function fatal(string $msg, string $prefix = 'Fatal Error: '): string
{
$msg = $prefix . $msg;
$space = self::tabSpaces($msg);
$out = static::colorize(str_pad(' ', $space), Color::FG_LIGHT_GRAY, Color::AT_BOLD, Color::BG_RED) . PHP_EOL;
$out .= static::colorize(' ' . $msg . ' ', Color::FG_LIGHT_GRAY, Color::AT_BOLD, Color::BG_RED) . PHP_EOL;
$out .= static::colorize(str_pad(' ', $space), Color::FG_LIGHT_GRAY, Color::AT_BOLD, Color::BG_RED) . PHP_EOL;

return $out;
}

/**
* Color style for success messages.
*
Expand Down
31 changes: 15 additions & 16 deletions src/Console/Commands/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@
namespace Phalcon\Migrations\Console\Commands;

use Phalcon\Config;
use Phalcon\Cop\Parser;
use Phalcon\Migrations\Console\Color;
use Phalcon\Migrations\Migrations;
use Phalcon\Migrations\Script\ScriptException;
use Phalcon\Mvc\Model\Exception;
use Phalcon\Config\Adapter\Ini as IniConfig;
use Phalcon\Config\Adapter\Json as JsonConfig;
use Phalcon\Config\Adapter\Yaml as YamlConfig;
use Phalcon\Cop\Parser;
use Phalcon\Migrations\Console\Color;
use Phalcon\Migrations\Migrations;

/**
* Migration Command
Expand Down Expand Up @@ -69,8 +67,8 @@ public function getPossibleParams(): array

/**
* @throws CommandsException
* @throws ScriptException
* @throws Exception
* @throws \Phalcon\Db\Exception
* @throws \Exception
*/
public function run(): void
{
Expand Down Expand Up @@ -146,15 +144,16 @@ public function run(): void
break;
case 'run':
Migrations::run([
'directory' => $path,
'tableName' => $tableName,
'migrationsDir' => $migrationsDir,
'force' => $this->parser->has('force'),
'tsBased' => $migrationsTsBased,
'config' => $config,
'version' => $this->parser->get('version'),
'migrationsInDb' => $migrationsInDb,
'verbose' => $this->parser->has('verbose'),
'directory' => $path,
'tableName' => $tableName,
'migrationsDir' => $migrationsDir,
'force' => $this->parser->has('force'),
'tsBased' => $migrationsTsBased,
'config' => $config,
'version' => $this->parser->get('version'),
'migrationsInDb' => $migrationsInDb,
'verbose' => $this->parser->has('verbose'),
'skip-foreign-checks' => $this->parser->has('skip-foreign-checks'),
]);
break;
case 'list':
Expand Down
4 changes: 2 additions & 2 deletions src/Migration/Action/Generate.php
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,13 @@ public function getReferences(bool $skipRefSchema = false): Generator
);
}

yield $constraintName => $referencesOptions + [
yield $constraintName => array_merge($referencesOptions, [
sprintf("'referencedTable' => %s", $this->wrapWithQuotes($reference->getReferencedTable())),
"'columns' => [" . join(',', array_unique($referenceColumns)) . "]",
"'referencedColumns' => [" . join(',', array_unique($referencedColumns)) . "]",
sprintf("'onUpdate' => '%s'", $reference->getOnUpdate()),
sprintf("'onDelete' => '%s'", $reference->getOnDelete()),
];
]);
}
}

Expand Down
18 changes: 16 additions & 2 deletions src/Migrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Phalcon\Migrations\Version\IncrementalItem;
use Phalcon\Migrations\Version\ItemCollection as VersionCollection;
use Phalcon\Migrations\Version\TimestampedItem;
use SplFileInfo;

class Migrations
{
Expand Down Expand Up @@ -191,13 +192,15 @@ public static function generate(array $options)
* @param array $options
* @throws DbException
* @throws RuntimeException
* @throws Exception
*/
public static function run(array $options)
{
$optionStack = new OptionStack();
$listTables = new ListTablesIterator();
$optionStack->setOptions($options);
$optionStack->setDefaultOption('verbose', false);
$optionStack->setDefaultOption('skip-foreign-checks', false);

// Define versioning type to be used
if (!empty($options['tsBased']) || $optionStack->getOption('tsBased')) {
Expand Down Expand Up @@ -355,12 +358,18 @@ public static function run(array $options)
$migrationStartTime = date('Y-m-d H:i:s');

if ($optionStack->getOption('tableName') === '@') {
/** @var SplFileInfo $fileInfo */
foreach ($iterator as $fileInfo) {
if (!$fileInfo->isFile() || 0 !== strcasecmp($fileInfo->getExtension(), 'php')) {
continue;
}

ModelMigration::migrate($fileInfo->getBasename('.php'), $initialVersion, $versionItem);
ModelMigration::migrate(
$fileInfo->getBasename('.php'),
$initialVersion,
$versionItem,
$optionStack->getOption('skip-foreign-checks')
);
}
} else {
if (!empty($prefix)) {
Expand All @@ -369,7 +378,12 @@ public static function run(array $options)

$tables = explode(',', $optionStack->getOption('tableName'));
foreach ($tables as $tableName) {
ModelMigration::migrate($tableName, $initialVersion, $versionItem);
ModelMigration::migrate(
$tableName,
$initialVersion,
$versionItem,
$optionStack->getOption('skip-foreign-checks')
);
}
}

Expand Down
12 changes: 11 additions & 1 deletion src/Mvc/Model/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,14 @@ public static function shouldExportDataFromTable(string $table, array $exportTab
* @param string $tableName
* @param ItemInterface|null $fromVersion
* @param ItemInterface|null $toVersion
* @param bool $skipForeignChecks
* @throws Exception
*/
public static function migrate(
string $tableName,
ItemInterface $fromVersion = null,
ItemInterface $toVersion = null
ItemInterface $toVersion = null,
bool $skipForeignChecks = false
): void {
$fromVersion = $fromVersion ?: VersionCollection::createItem($fromVersion);
$toVersion = $toVersion ?: VersionCollection::createItem($toVersion);
Expand All @@ -342,6 +344,10 @@ public static function migrate(
return; // nothing to do
}

if ($skipForeignChecks === true) {
self::$connection->execute('SET FOREIGN_KEY_CHECKS=0');
}

if ($fromVersion->getStamp() < $toVersion->getStamp()) {
$toMigration = self::createClass($toVersion, $tableName);

Expand Down Expand Up @@ -378,6 +384,10 @@ public static function migrate(
$toMigration->morph();
}
}

if ($skipForeignChecks === true) {
self::$connection->execute('SET FOREIGN_KEY_CHECKS=1');
}
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/Version/IncrementalItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ public static function between($initialVersion, $finalVersion, $versions)
foreach ($versions as $version) {
/** @var ItemInterface $version */
if (
($version->getStamp() >= $initialVersion->getStamp())
&& ($version->getStamp() <= $finalVersion->getStamp())
$version->getStamp() >= $initialVersion->getStamp() &&
$version->getStamp() <= $finalVersion->getStamp()
) {
$betweenVersions[] = $version;
}
Expand All @@ -149,7 +149,7 @@ public static function between($initialVersion, $finalVersion, $versions)
* @param ItemInterface[] $versions
* @return array ItemInterface[]
*/
public static function sortAsc($versions)
public static function sortAsc(array $versions): array
{
$sortData = [];
foreach ($versions as $version) {
Expand Down
16 changes: 16 additions & 0 deletions tests/_support/Helper/Mysql.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,23 @@ public function _initialize()

public function _before(TestInterface $test)
{
$this->setForeignKeys();
foreach ($this->getPhalconDb()->listTables() as $table) {
$this->getPhalconDb()->dropTable($table);
}

$this->setForeignKeys(true);
}

public function _after(TestInterface $test)
{
$this->setForeignKeys();
foreach ($this->getPhalconDb()->listTables() as $table) {
$this->getPhalconDb()->dropTable($table);
}

$this->setForeignKeys(true);

/**
* Reset filename or DB connection
*/
Expand Down Expand Up @@ -123,4 +129,14 @@ public function batchInsert(string $table, array $columns, array $rows)

$this->getPhalconDb()->execute($query);
}

/**
* Executes 'SET FOREIGN_KEY_CHECKS' query
*
* @param bool $enabled
*/
protected function setForeignKeys(bool $enabled = false): void
{
$this->getPhalconDb()->execute('SET FOREIGN_KEY_CHECKS=' . intval($enabled));
}
}
2 changes: 2 additions & 0 deletions tests/cli/GenerateCest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ public function generateWithSkipRefSchema(CliTester $I): void
$content = file_get_contents(codecept_output_dir('1.0.0/cli-skip-ref-schema.php'));

$I->assertFalse(strpos($content, "'referencedSchema' => '$schema',"));
$I->assertNotFalse(strpos($content, "'referencedTable' => 'client',"));
}

/**
Expand All @@ -107,6 +108,7 @@ public function generateWithRefSchema(CliTester $I): void
$content = file_get_contents(codecept_output_dir('1.0.0/cli-skip-ref-schema.php'));

$I->assertNotFalse(strpos($content, "'referencedSchema' => '$schema',"));
$I->assertNotFalse(strpos($content, "'referencedTable' => 'client',"));
}

/**
Expand Down
Loading

0 comments on commit 9ac61ce

Please sign in to comment.