Skip to content

Commit

Permalink
- automatic CS fixing
Browse files Browse the repository at this point in the history
- do not generate empty migrations
  • Loading branch information
wolfy-j committed Oct 21, 2019
1 parent 006bf97 commit 3d1903b
Show file tree
Hide file tree
Showing 18 changed files with 257 additions and 169 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
language: php

dist: trusty
sudo: required

services:
Expand All @@ -23,6 +23,7 @@ install:

script:
- vendor/bin/phpunit --coverage-clover=coverage.xml
- vendor/bin/spiral-cs check src tests

after_success:
- bash <(curl -s https://codecov.io/bash) -f coverage.xml
Expand Down
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
"php": "^7.2",
"cycle/orm": "^1.0",
"cycle/schema-builder": "^1.0",
"spiral/migrations": "^2.0.7"
"spiral/migrations": "^2.0"
},
"require-dev": {
"cycle/annotated": "^1.0",
"phpunit/phpunit": "~7.0",
"mockery/mockery": "^1.1",
"spiral/debug": "^1.3"
"cycle/annotated": "^1.0",
"spiral/debug": "^1.3",
"spiral/code-style": "^1.0"
},
"autoload": {
"psr-4": {
Expand Down
28 changes: 22 additions & 6 deletions src/GenerateMigrations.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Cycle\Migrations;

use Cycle\Schema\GeneratorInterface;
use Cycle\Schema\Registry;
use Spiral\Database\Schema\AbstractTable;
use Spiral\Migrations\Atomizer\Atomizer;
use Spiral\Migrations\Atomizer\Renderer;
use Spiral\Migrations\Atomizer\RendererInterface;
use Spiral\Migrations\Config\MigrationConfig;
use Spiral\Migrations\Migration;
use Spiral\Migrations\RepositoryInterface;
use Spiral\Migrations\Config\MigrationConfig;
use Spiral\Reactor\ClassDeclaration;
use Spiral\Reactor\FileDeclaration;
use Spiral\Reactor\AbstractDeclaration;

/**
* Migration generator creates set of migrations needed to sync database schema with desired state. Each database will
Expand Down Expand Up @@ -69,32 +71,46 @@ public function run(Registry $registry): Registry
$seq = 0;
foreach ($databases as $database => $tables) {
$name = sprintf(
"orm_%s_%s_%s_%s",
'orm_%s_%s_%s_%s',
$database,
str_replace('.', '_', microtime(true)),
++$seq,
md5(microtime(true) . microtime(false))
);

list($class, $file) = $this->generate($name, $database, $tables);
if ($class === null || $file === null) {
// no changes
continue;
}

$this->repository->registerMigration($name, $class, $file->render());
}

return $registry;
}

/**
* @param string $name
* @param string $database
* @param array $tables
* @param string $name
* @param string $database
* @param AbstractTable[] $tables
* @return array [string, FileDeclaration]
*/
protected function generate(string $name, string $database, array $tables): array
{
$atomizer = new Atomizer(new Renderer());

$reasonable = false;
foreach ($tables as $table) {
$atomizer->addTable($table);

if ($table->getComparator()->hasChanges()) {
$reasonable = true;
}
}

if (!$reasonable) {
return [null, null];
}

//Rendering
Expand Down
180 changes: 43 additions & 137 deletions tests/Migrations/BaseTest.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Cycle\Migrations\Tests;

use Cycle\Annotated\Entities;
Expand Down Expand Up @@ -47,8 +50,6 @@

abstract class BaseTest extends TestCase
{
// tests configuration
public static $config;

// currently active driver
public const DRIVER = null;
Expand All @@ -59,6 +60,8 @@ abstract class BaseTest extends TestCase
'safe' => true,
'namespace' => 'Migration',
];
// tests configuration
public static $config;

// cross test driver cache
public static $driverCache = [];
Expand Down Expand Up @@ -86,7 +89,7 @@ abstract class BaseTest extends TestCase
/**
* Init all we need.
*/
public function setUp()
public function setUp(): void
{
parent::setUp();

Expand Down Expand Up @@ -153,7 +156,7 @@ public function setUp()
/**
* Cleanup.
*/
public function tearDown()
public function tearDown(): void
{
$files = new Files();
foreach ($files->getFiles(__DIR__ . '/../files/', '*.php') as $file) {
Expand All @@ -167,38 +170,6 @@ public function tearDown()
$this->dbal = null;
}

protected function migrate(string $directory): array
{
$tokenizer = new Tokenizer(new TokenizerConfig([
'directories' => [$directory],
'exclude' => [],
]));

$locator = $tokenizer->classLocator();

$p = Generator::getDefaultParser();
$r = new Registry($this->dbal);

$schema = (new Compiler())->compile($r, [
new Entities($locator, $p),
new ResetTables(),
new MergeColumns($p),
new GenerateRelations(),
new ValidateEntities(),
new RenderTables(),
new RenderRelations(),
new MergeIndexes($p),
new GenerateTypecast(),
new GenerateMigrations($this->migrator->getRepository(), new MigrationConfig(static::CONFIG))
]);

$tables = [];
foreach ($r as $e) {
$tables[] = $r->getTableSchema($e);
}
return $tables;
}

/**
* Calculates missing parameters for typecasting.
*
Expand Down Expand Up @@ -237,6 +208,38 @@ public function getDriver(): Driver
return static::$driverCache[static::DRIVER] = $this->driver;
}

protected function migrate(string $directory): array
{
$tokenizer = new Tokenizer(new TokenizerConfig([
'directories' => [$directory],
'exclude' => [],
]));

$locator = $tokenizer->classLocator();

$p = Generator::getDefaultParser();
$r = new Registry($this->dbal);

$schema = (new Compiler())->compile($r, [
new Entities($locator, $p),
new ResetTables(),
new MergeColumns($p),
new GenerateRelations(),
new ValidateEntities(),
new RenderTables(),
new RenderRelations(),
new MergeIndexes($p),
new GenerateTypecast(),
new GenerateMigrations($this->migrator->getRepository(), new MigrationConfig(static::CONFIG))
]);

$tables = [];
foreach ($r as $e) {
$tables[] = $r->getTableSchema($e);
}
return $tables;
}

/**
* @return Database
*/
Expand All @@ -248,7 +251,7 @@ protected function getDatabase(): Database
/**
* @param Database|null $database
*/
protected function dropDatabase(Database $database = null)
protected function dropDatabase(Database $database = null): void
{
if (empty($database)) {
return;
Expand All @@ -274,7 +277,7 @@ protected function dropDatabase(Database $database = null)
/**
* For debug purposes only.
*/
protected function enableProfiling()
protected function enableProfiling(): void
{
if (!is_null($this->logger)) {
$this->logger->display();
Expand All @@ -284,14 +287,14 @@ protected function enableProfiling()
/**
* For debug purposes only.
*/
protected function disableProfiling()
protected function disableProfiling(): void
{
if (!is_null($this->logger)) {
$this->logger->hide();
}
}

protected function assertSameAsInDB(AbstractTable $current)
protected function assertSameAsInDB(AbstractTable $current): void
{
$source = $current->getState();
$target = $current->getDriver()->getSchema($current->getName())->getState();
Expand Down Expand Up @@ -454,100 +457,3 @@ protected function makeMessage(string $table, Comparator $comparator)
return "Table '{$table}' not synced, no idea why, add more messages :P";
}
}

class TestLogger implements LoggerInterface
{
use LoggerTrait;

private $display;

private $countWrites;
private $countReads;

public function __construct()
{
$this->countWrites = 0;
$this->countReads = 0;
}

public function countWriteQueries(): int
{
return $this->countWrites;
}

public function countReadQueries(): int
{
return $this->countReads;
}

public function log($level, $message, array $context = [])
{
if (!empty($context['query'])) {
$sql = strtolower($context['query']);
if (
strpos($sql, 'insert') === 0
|| strpos($sql, 'update') === 0
|| strpos($sql, 'delete') === 0
) {
$this->countWrites++;
} else {
if (!$this->isPostgresSystemQuery($sql)) {
$this->countReads++;
}
}
}

if (!$this->display) {
return;
}

if ($level == LogLevel::ERROR) {
echo " \n! \033[31m" . $message . "\033[0m";
} elseif ($level == LogLevel::ALERT) {
echo " \n! \033[35m" . $message . "\033[0m";
} elseif (strpos($message, 'SHOW') === 0) {
echo " \n> \033[34m" . $message . "\033[0m";
} else {
if ($this->isPostgresSystemQuery($message)) {
echo " \n> \033[90m" . $message . "\033[0m";

return;
}

if (strpos($message, 'SELECT') === 0) {
echo " \n> \033[32m" . $message . "\033[0m";
} elseif (strpos($message, 'INSERT') === 0) {
echo " \n> \033[36m" . $message . "\033[0m";
} else {
echo " \n> \033[33m" . $message . "\033[0m";
}
}
}

public function display()
{
$this->display = true;
}

public function hide()
{
$this->display = false;
}

protected function isPostgresSystemQuery(string $query): bool
{
$query = strtolower($query);
if (
strpos($query, 'tc.constraint_name')
|| strpos($query, 'pg_indexes')
|| strpos($query, 'tc.constraint_name')
|| strpos($query, 'pg_constraint')
|| strpos($query, 'information_schema')
|| strpos($query, 'pg_class')
) {
return true;
}

return false;
}
}
5 changes: 4 additions & 1 deletion tests/Migrations/Driver/MySQL/ReflectTest.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Cycle\Migrations\Tests\Driver\MySQL;

class ReflectTest extends \Cycle\Migrations\Tests\ReflectTest
{
const DRIVER = "mysql";
public const DRIVER = 'mysql';
}
Loading

0 comments on commit 3d1903b

Please sign in to comment.