Skip to content

Commit

Permalink
Merge pull request #74 from phalcon/feature/#68-option-ignore-ref-schema
Browse files Browse the repository at this point in the history
#68 - Added new option to ignore referenced schema
  • Loading branch information
Jeckerson authored Mar 21, 2020
2 parents d596d4c + 07875f7 commit 9f5edfc
Show file tree
Hide file tree
Showing 7 changed files with 276 additions and 77 deletions.
43 changes: 0 additions & 43 deletions psalm.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -27,76 +27,33 @@
<DeprecatedInterface errorLevel="info" />
<DeprecatedTrait errorLevel="info" />

<InternalMethod errorLevel="info" />
<InternalProperty errorLevel="info" />
<InternalClass errorLevel="info" />

<MissingClosureReturnType errorLevel="info" />
<MissingReturnType errorLevel="info" />
<MissingPropertyType errorLevel="info" />
<InvalidDocblock errorLevel="info" />
<MisplacedRequiredParam errorLevel="info" />

<PropertyNotSetInConstructor errorLevel="info" />
<MissingConstructor errorLevel="info" />
<MissingClosureParamType errorLevel="info" />
<MissingParamType errorLevel="info" />

<RedundantCondition errorLevel="info" />

<DocblockTypeContradiction errorLevel="info" />
<RedundantConditionGivenDocblockType errorLevel="info" />

<UnresolvableInclude errorLevel="info" />

<RawObjectIteration errorLevel="info" />

<InvalidStringClass errorLevel="info" />

<!-- level 4 issues - points to possible deficiencies in logic, higher false-positives -->

<MoreSpecificReturnType errorLevel="info" />
<LessSpecificReturnStatement errorLevel="info" />
<TypeCoercion errorLevel="info" />

<PossiblyFalseArgument errorLevel="info" />
<PossiblyFalseIterator errorLevel="info" />
<PossiblyFalseOperand errorLevel="info" />
<PossiblyFalsePropertyAssignmentValue errorLevel="info" />
<PossiblyFalseReference errorLevel="info" />
<PossiblyInvalidArgument errorLevel="info" />
<PossiblyInvalidArrayAccess errorLevel="info" />
<PossiblyInvalidArrayAssignment errorLevel="info" />
<PossiblyInvalidArrayOffset errorLevel="info" />
<PossiblyInvalidCast errorLevel="info" />
<PossiblyInvalidFunctionCall errorLevel="info" />
<PossiblyInvalidIterator errorLevel="info" />
<PossiblyInvalidMethodCall errorLevel="info" />
<PossiblyInvalidOperand errorLevel="info" />
<PossiblyInvalidPropertyAssignment errorLevel="info" />
<PossiblyInvalidPropertyAssignmentValue errorLevel="info" />
<PossiblyInvalidPropertyFetch errorLevel="info" />
<PossiblyNullArgument errorLevel="info" />
<PossiblyNullArrayAccess errorLevel="info" />
<PossiblyNullArrayAssignment errorLevel="info" />
<PossiblyNullArrayOffset errorLevel="info" />
<PossiblyNullFunctionCall errorLevel="info" />
<PossiblyNullIterator errorLevel="info" />
<PossiblyNullOperand errorLevel="info" />
<PossiblyNullPropertyAssignment errorLevel="info" />
<PossiblyNullPropertyAssignmentValue errorLevel="info" />
<PossiblyNullPropertyFetch errorLevel="info" />
<PossiblyNullReference errorLevel="info" />
<PossiblyUndefinedGlobalVariable errorLevel="info" />
<PossiblyUndefinedVariable errorLevel="info" />
<PossiblyUndefinedArrayOffset errorLevel="info" />
<PossiblyUndefinedMethod errorLevel="info" />
<PossibleRawObjectIteration errorLevel="info" />

<!-- level 6 issues - really bad things -->

<InvalidReturnStatement errorLevel="info" />
<UndefinedInterfaceMethod errorLevel="info" />

<!-- level 8 issues - some fatal errors in PHP -->

Expand Down
23 changes: 12 additions & 11 deletions src/Console/Commands/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,18 @@ public function run(): void
switch ($action) {
case 'generate':
Migrations::generate([
'directory' => $path,
'tableName' => $tableName,
'exportData' => $this->parser->get('data'),
'exportDataFromTables' => $this->exportFromTables($config),
'migrationsDir' => $migrationsDir,
'version' => $this->parser->get('version'),
'force' => $this->parser->has('force'),
'noAutoIncrement' => $this->parser->has('no-auto-increment'),
'config' => $config,
'descr' => $descr,
'verbose' => $this->parser->has('dry'),
'directory' => $path,
'tableName' => $tableName,
'exportData' => $this->parser->get('data'),
'exportDataFromTables' => $this->exportFromTables($config),
'migrationsDir' => $migrationsDir,
'version' => $this->parser->get('version'),
'force' => $this->parser->has('force'),
'noAutoIncrement' => $this->parser->has('no-auto-increment'),
'config' => $config,
'descr' => $descr,
'verbose' => $this->parser->has('dry'),
'skip-ref-schema' => $this->parser->has('skip-ref-schema'),
]);
break;
case 'run':
Expand Down
15 changes: 12 additions & 3 deletions src/Migration/Action/Generate.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,10 @@ public function getIndexes(): Generator
}

/**
* @param bool $skipRefSchema
* @return Generator
*/
public function getReferences(): Generator
public function getReferences(bool $skipRefSchema = false): Generator
{
foreach ($this->references as $constraintName => $reference) {
$referenceColumns = [];
Expand All @@ -300,10 +301,18 @@ public function getReferences(): Generator
foreach ($reference->getReferencedColumns() as $referencedColumn) {
$referencedColumns[] = $this->wrapWithQuotes($referencedColumn);
}

$referencesOptions = [];
$referencedSchema = $reference->getReferencedSchema();
if ($skipRefSchema === false && $referencedSchema !== null) {
$referencesOptions[] = sprintf(
"'referencedSchema' => %s",
$this->wrapWithQuotes($referencedSchema)
);
}

yield $constraintName => [
yield $constraintName => $referencesOptions + [
sprintf("'referencedTable' => %s", $this->wrapWithQuotes($reference->getReferencedTable())),
sprintf("'referencedSchema' => %s", $this->wrapWithQuotes($reference->getReferencedSchema())),
"'columns' => [" . join(',', array_unique($referenceColumns)) . "]",
"'referencedColumns' => [" . join(',', array_unique($referencedColumns)) . "]",
sprintf("'onUpdate' => '%s'", $reference->getOnUpdate()),
Expand Down
7 changes: 5 additions & 2 deletions src/Migrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public static function generate(array $options)
$optionStack->setDefaultOption('descr', null);
$optionStack->setDefaultOption('noAutoIncrement', null);
$optionStack->setDefaultOption('verbose', false);
$optionStack->setDefaultOption('skip-ref-schema', false);

$migrationsDirs = $optionStack->getOption('migrationsDir');
if (is_array($migrationsDirs)) {
Expand Down Expand Up @@ -129,7 +130,8 @@ public static function generate(array $options)
$migrations = ModelMigration::generateAll(
$versionItem,
$optionStack->getOption('exportData'),
$optionStack->getOption('exportDataFromTables') ?: []
$optionStack->getOption('exportDataFromTables') ?: [],
$optionStack->getOption('skip-ref-schema')
);

if (!$optionStack->getOption('verbose')) {
Expand Down Expand Up @@ -161,7 +163,8 @@ public static function generate(array $options)
$versionItem,
$table,
$optionStack->getOption('exportData'),
$optionStack->getOption('exportDataFromTables') ?: []
$optionStack->getOption('exportDataFromTables') ?: [],
$optionStack->getOption('skip-ref-schema')
);
if (!$optionStack->getOption('verbose')) {
$tableFile = $migrationPath . DIRECTORY_SEPARATOR . $table . '.php';
Expand Down
30 changes: 17 additions & 13 deletions src/Mvc/Model/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,20 +155,22 @@ public static function setMigrationPath(string $path): void
*
* @param ItemInterface $version
* @param string $exportData
* @param array $exportDataFromTables
* @param array $exportTables
* @param bool $skipRefSchema
* @return array
* @throws DbException
* @throws UnknownColumnTypeException
*/
public static function generateAll(
ItemInterface $version,
string $exportData = null,
array $exportDataFromTables = []
array $exportTables = [],
bool $skipRefSchema = false
): array {
$classDefinition = [];
$schema = Utils::resolveDbSchema(self::$databaseConfig);

foreach (self::$connection->listTables($schema) as $table) {
$classDefinition[$table] = self::generate($version, $table, $exportData, $exportDataFromTables);
$classDefinition[$table] = self::generate($version, $table, $exportData, $exportTables, $skipRefSchema);
}

return $classDefinition;
Expand All @@ -180,15 +182,17 @@ public static function generateAll(
* @param ItemInterface $version
* @param string $table
* @param mixed $exportData
* @param array $exportDataFromTables
* @param array $exportTables
* @param bool $skipRefSchema
* @return string
* @throws UnknownColumnTypeException
*/
public static function generate(
ItemInterface $version,
string $table,
$exportData = null,
array $exportDataFromTables = []
array $exportTables = [],
bool $skipRefSchema = false
): string {
$snippet = new Snippet();
$adapter = (string)self::$databaseConfig->path('adapter');
Expand Down Expand Up @@ -221,7 +225,7 @@ public static function generate(
* Generate References
*/
$referencesDefinition = [];
foreach ($generateAction->getReferences() as $constraintName => $referenceDefinition) {
foreach ($generateAction->getReferences($skipRefSchema) as $constraintName => $referenceDefinition) {
$referencesDefinition[] = $snippet->getReferenceDefinition($constraintName, $referenceDefinition);
}

Expand Down Expand Up @@ -253,7 +257,7 @@ public static function generate(
// up()
$classData .= $snippet->getMigrationUp();

if ($exportData == 'always' || self::shouldExportDataFromTable($table, $exportDataFromTables)) {
if ($exportData == 'always' || self::shouldExportDataFromTable($table, $exportTables)) {
$classData .= $snippet->getMigrationBatchInsert($table, $generateAction->getQuoteWrappedColumns());
}

Expand All @@ -262,14 +266,14 @@ public static function generate(
// down()
$classData .= $snippet->getMigrationDown();

if ($exportData == 'always' || self::shouldExportDataFromTable($table, $exportDataFromTables)) {
if ($exportData == 'always' || self::shouldExportDataFromTable($table, $exportTables)) {
$classData .= $snippet->getMigrationBatchDelete($table);
}

$classData .= "\n }\n";

// afterCreateTable()
if ($exportData == 'oncreate' || self::shouldExportDataFromTable($table, $exportDataFromTables)) {
if ($exportData == 'oncreate' || self::shouldExportDataFromTable($table, $exportTables)) {
$classData .= $snippet->getMigrationAfterCreateTable($table, $generateAction->getQuoteWrappedColumns());
}

Expand All @@ -281,7 +285,7 @@ public static function generate(
if (
$exportData == 'always' ||
$exportData == 'oncreate' ||
self::shouldExportDataFromTable($table, $exportDataFromTables)
self::shouldExportDataFromTable($table, $exportTables)
) {
$fileHandler = fopen(self::$migrationPath . $version->getVersion() . '/' . $table . '.dat', 'w');
$cursor = self::$connection->query('SELECT * FROM ' . self::$connection->escapeIdentifier($table));
Expand Down Expand Up @@ -313,9 +317,9 @@ public static function generate(
return $classData;
}

public static function shouldExportDataFromTable(string $table, array $exportDataFromTables): bool
public static function shouldExportDataFromTable(string $table, array $exportTables): bool
{
return in_array($table, $exportDataFromTables);
return in_array($table, $exportTables);
}

/**
Expand Down
100 changes: 95 additions & 5 deletions tests/cli/GenerateCest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@

use CliTester;
use Phalcon\Db\Column;
use Phalcon\Db\Reference;

final class GenerateCest
{
/**
* Path to migrations config
*
* @var string
*/
private $configPath = 'tests/_data/cli/migrations.php';

/**
* @param CliTester $I
*/
Expand All @@ -36,9 +44,7 @@ public function tryWithoutDbConfig(CliTester $I): void
*/
public function generateEmptyDb(CliTester $I): void
{
$configPath = 'tests/_data/cli/migrations.php';

$I->runShellCommand('php phalcon-migrations generate --config=' . $configPath);
$I->runShellCommand('php phalcon-migrations generate --config=' . $this->configPath);
$I->seeInShellOutput('Info: Nothing to generate. You should create tables first.');
$I->seeResultCodeIs(0);
}
Expand All @@ -58,10 +64,94 @@ public function generateFirstVersion(CliTester $I): void
],
]);

$configPath = 'tests/_data/cli/migrations.php';
$I->runShellCommand('php phalcon-migrations generate --config=' . $this->configPath);
$I->seeInShellOutput('Success: Version 1.0.0 was successfully generated');
$I->seeResultCodeIs(0);
}

/**
* @param CliTester $I
*/
public function generateWithSkipRefSchema(CliTester $I): void
{
$I->wantToTest('generate with --skip-ref-schema option');

$schema = getenv('MYSQL_TEST_DB_DATABASE');

$this->createFKTables($I);

$I->runShellCommand('php phalcon-migrations generate --config=' . $configPath);
$I->runShellCommand('php phalcon-migrations generate --skip-ref-schema --config=' . $this->configPath);
$I->seeInShellOutput('Success: Version 1.0.0 was successfully generated');
$I->seeResultCodeIs(0);

$content = file_get_contents(codecept_output_dir('1.0.0/cli-skip-ref-schema.php'));

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

/**
* @param CliTester $I
*/
public function generateWithRefSchema(CliTester $I): void
{
$I->wantToTest('generate with referencedSchema');

$schema = getenv('MYSQL_TEST_DB_DATABASE');

$this->createFKTables($I);

$I->runShellCommand('php phalcon-migrations generate --config=' . $this->configPath);
$I->seeInShellOutput('Success: Version 1.0.0 was successfully generated');
$I->seeResultCodeIs(0);

$content = file_get_contents(codecept_output_dir('1.0.0/cli-skip-ref-schema.php'));

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

/**
* @param CliTester $I
*/
protected function createFKTables(CliTester $I): void
{
$schema = getenv('MYSQL_TEST_DB_DATABASE');
$I->getPhalconDb()->createTable('client', $schema, [
'columns' => [
new Column('id', [
'type' => Column::TYPE_INTEGER,
'size' => 11,
'notNull' => true,
'primary' => true,
]),
],
]);

$I->getPhalconDb()->createTable('cli-skip-ref-schema', $schema, [
'columns' => [
new Column('id', [
'type' => Column::TYPE_INTEGER,
'size' => 10,
'notNull' => true,
]),
new Column('clientId', [
'type' => Column::TYPE_INTEGER,
'size' => 11,
'notNull' => true,
]),
],
'references' => [
new Reference(
'fk_client_1',
[
'referencedSchema' => $schema,
'referencedTable' => 'client',
'columns' => ['clientId'],
'referencedColumns' => ['id'],
'onUpdate' => 'NO ACTION',
'onDelete' => 'NO ACTION',
]
),
],
]);
}
}
Loading

0 comments on commit 9f5edfc

Please sign in to comment.