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

[8.x] Schema Dump #32275

Merged
merged 27 commits into from Apr 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
80 changes: 80 additions & 0 deletions src/Illuminate/Database/Console/DumpCommand.php
@@ -0,0 +1,80 @@
<?php

namespace Illuminate\Database\Console;

use Illuminate\Console\Command;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Connection;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\Events\SchemaDumped;
use Illuminate\Filesystem\Filesystem;

class DumpCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'schema:dump
{--database= : The database connection to use}
{--path= : The path where the schema dump file should be stored}
{--prune : Delete all existing migration files}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Dump the given database schema';

/**
* Execute the console command.
*
* @return int
*/
public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)
{
$this->schemaState(
$connection = $connections->connection($database = $this->input->getOption('database'))
)->dump($path = $this->path($connection));

$dispatcher->dispatch(new SchemaDumped($connection, $path));

$this->info('Database schema dumped successfully.');

if ($this->option('prune')) {
(new Filesystem)->deleteDirectory(
database_path('migrations'), $preserve = false
);

$this->info('Migrations pruned successfully.');
}
}

/**
* Create a schema state instance for the given connection.
*
* @param \Illuminate\Database\Connection $connection
* @return mixed
*/
protected function schemaState(Connection $connection)
{
return $connection->getSchemaState()
->handleOutputUsing(function ($type, $buffer) {
$this->output->write($buffer);
});
}

/**
* Get the path that the dump should be written to.
*
* @param \Illuminate\Database\Connection $connection
*/
protected function path(Connection $connection)
{
return tap($this->option('path') ?: database_path('schema/'.$connection->getName().'-schema.sql'), function ($path) {
(new Filesystem)->ensureDirectoryExists(dirname($path));
});
}
}
74 changes: 73 additions & 1 deletion src/Illuminate/Database/Console/Migrations/MigrateCommand.php
Expand Up @@ -3,7 +3,11 @@
namespace Illuminate\Database\Console\Migrations;

use Illuminate\Console\ConfirmableTrait;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Events\SchemaLoaded;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Database\SqlServerConnection;

class MigrateCommand extends BaseCommand
{
Expand All @@ -18,6 +22,7 @@ class MigrateCommand extends BaseCommand
{--force : Force the operation to run when in production}
{--path=* : The path(s) to the migrations files to be executed}
{--realpath : Indicate any provided migration file paths are pre-resolved absolute paths}
{--schema-path= : The path to a schema dump file}
{--pretend : Dump the SQL queries that would be run}
{--seed : Indicates if the seed task should be re-run}
{--step : Force the migrations to be run so they can be rolled back individually}';
Expand All @@ -36,17 +41,26 @@ class MigrateCommand extends BaseCommand
*/
protected $migrator;

/**
* The event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $dispatcher;

/**
* Create a new migration command instance.
*
* @param \Illuminate\Database\Migrations\Migrator $migrator
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
* @return void
*/
public function __construct(Migrator $migrator)
public function __construct(Migrator $migrator, Dispatcher $dispatcher)
{
parent::__construct();

$this->migrator = $migrator;
$this->dispatcher = $dispatcher;
}

/**
Expand Down Expand Up @@ -95,5 +109,63 @@ protected function prepareDatabase()
'--database' => $this->option('database'),
]));
}

if (! $this->migrator->hasRunAnyMigrations() && ! $this->option('pretend')) {
$this->loadSchemaState();
}
}

/**
* Load the schema state to seed the initial database schema structure.
*
* @return void
*/
protected function loadSchemaState()
{
$connection = $this->migrator->resolveConnection($this->option('database'));

// First, we will make sure that the connection supports schema loading and that
// the schema file exists before we proceed any further. If not, we will just
// continue with the standard migration operation as normal without errors.
if ($connection instanceof SQLiteConnection ||
$connection instanceof SqlServerConnection ||
! file_exists($path = $this->schemaPath($connection))) {
return;
}

$this->line('<info>Loading stored database schema:</info> '.$path);

$startTime = microtime(true);

// Since the schema file will create the "migrations" table and reload it to its
// proper state, we need to delete it here so we don't get an error that this
// table already exists when the stored database schema file gets executed.
$this->migrator->deleteRepository();

$connection->getSchemaState()->handleOutputUsing(function ($type, $buffer) {
$this->output->write($buffer);
})->load($path);

$runTime = number_format((microtime(true) - $startTime) * 1000, 2);

// Finally, we will fire an event that this schema has been loaded so developers
// can perform any post schema load tasks that are necessary in listeners for
// this event, which may seed the database tables with some necessary data.
$this->dispatcher->dispatch(
new SchemaLoaded($connection, $path)
);

$this->line('<info>Loaded stored database schema.</info> ('.$runTime.'ms)');
}

/**
* Get the path to the stored schema for the given connection.
*
* @param \Illuminate\Database\Connection $connection
* @return string
*/
protected function schemaPath($connection)
{
return $this->option('schema-path') ?: database_path('schema/'.$connection->getName().'-schema.sql');
}
}
41 changes: 41 additions & 0 deletions src/Illuminate/Database/Events/SchemaDumped.php
@@ -0,0 +1,41 @@
<?php

namespace Illuminate\Database\Events;

class SchemaDumped
{
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
public $connection;

/**
* The database connection name.
*
* @var string
*/
public $connectionName;

/**
* The path to the schema dump.
*
* @var string
*/
public $path;

/**
* Create a new event instance.
*
* @param \Illuminate\Database\Connection $connection
* @param string $path
* @return void
*/
public function __construct($connection, $path)
{
$this->connection = $connection;
$this->connectionName = $connection->getName();
$this->path = $path;
}
}
41 changes: 41 additions & 0 deletions src/Illuminate/Database/Events/SchemaLoaded.php
@@ -0,0 +1,41 @@
<?php

namespace Illuminate\Database\Events;

class SchemaLoaded
{
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
public $connection;

/**
* The database connection name.
*
* @var string
*/
public $connectionName;

/**
* The path to the schema dump.
*
* @var string
*/
public $path;

/**
* Create a new event instance.
*
* @param \Illuminate\Database\Connection $connection
* @param string $path
* @return void
*/
public function __construct($connection, $path)
{
$this->connection = $connection;
$this->connectionName = $connection->getName();
$this->path = $path;
}
}
3 changes: 2 additions & 1 deletion src/Illuminate/Database/MigrationServiceProvider.php
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Database;

use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Database\Console\Migrations\FreshCommand;
use Illuminate\Database\Console\Migrations\InstallCommand;
Expand Down Expand Up @@ -116,7 +117,7 @@ protected function registerCommands(array $commands)
protected function registerMigrateCommand()
{
$this->app->singleton('command.migrate', function ($app) {
return new MigrateCommand($app['migrator']);
return new MigrateCommand($app['migrator'], $app[Dispatcher::class]);
});
}

Expand Down
12 changes: 12 additions & 0 deletions src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php
Expand Up @@ -169,6 +169,18 @@ public function repositoryExists()
return $schema->hasTable($this->table);
}

/**
* Delete the migration repository data store.
*
* @return void
*/
public function deleteRepository()
{
$schema = $this->getConnection()->getSchemaBuilder();

$schema->drop($this->table);
}

/**
* Get a query builder for the migration table.
*
Expand Down
7 changes: 5 additions & 2 deletions src/Illuminate/Database/Migrations/MigrationCreator.php
Expand Up @@ -63,9 +63,12 @@ public function create($name, $path, $table = null, $create = false)
// various place-holders, save the file, and run the post create event.
$stub = $this->getStub($table, $create);

$path = $this->getPath($name, $path);

$this->files->ensureDirectoryExists(dirname($path));

$this->files->put(
$path = $this->getPath($name, $path),
$this->populateStub($name, $stub, $table)
$path, $this->populateStub($name, $stub, $table)
);

// Next, we will fire any hooks that are supposed to fire after a migration is
Expand Down
Expand Up @@ -71,6 +71,13 @@ public function createRepository();
*/
public function repositoryExists();

/**
* Delete the migration repository data store.
*
* @return void
*/
public function deleteRepository();

/**
* Set the information source to gather data.
*
Expand Down