Skip to content

Instantly share code, notes, and snippets.

@Petah
Created July 4, 2016 07:56
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Petah/1443ace6accce4a069d0bd34611ce720 to your computer and use it in GitHub Desktop.
Save Petah/1443ace6accce4a069d0bd34611ce720 to your computer and use it in GitHub Desktop.
Simple Migrate
<?php
namespace MyProject\Cli\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DbMigrate extends \Symfony\Component\Console\Command\Command
{
protected function configure()
{
$this->setName('db:migrate');
$this->setDescription('Migrate DB to the latest version.');
$this->addOption('execute', 'x', InputOption::VALUE_NONE, 'Execute commands (instead of dry run output).');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$execute = $input->getOption('execute');
$path = ROOT.'/migrations/';
$pdo = \MyProject\Application::current()->getPdo();
$pdo->query(file_get_contents($path . '/migrations.sql'));
$files = [];
foreach (glob("$path/up/*.sql") as $file) {
$files[] = basename($file);
}
sort($files);
foreach ($files as $file) {
$statment = $pdo->prepare('
SELECT *
FROM migrations
WHERE name = :name
');
$result = $statment->execute([
':name' => basename($file),
]);
if ($statment->rowCount() != 0) {
$output->writeln("Skipped migration " . (!$execute ? '(dry run)' : '') . " $path/up/$file");
continue;
}
if ($execute) {
$statment = $pdo->prepare('
INSERT INTO migrations (
name,
created
) VALUES (
:name,
UTC_TIMESTAMP()
)
');
$result = $statment->execute([
':name' => basename($file),
]);
}
$output->writeln("Running migration " . (!$execute ? '(dry run)' : '') . " $path/up/$file");
if ($execute) {
$sql = file_get_contents("$path/up/$file");
$pdo->query($sql);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment