add backup of database in case of update failure

This commit is contained in:
Kacper Donat 2019-02-02 22:28:07 +01:00
parent 5a9096830f
commit 702ae47945
3 changed files with 28 additions and 11 deletions

View File

@ -37,7 +37,9 @@ class ZtmGdanskDepartureRepository implements DepartureRepository
$estimates = json_decode(file_get_contents(static::ESTIMATES_URL . "?stopId=" . $stop->getId()), true)['delay']; $estimates = json_decode(file_get_contents(static::ESTIMATES_URL . "?stopId=" . $stop->getId()), true)['delay'];
$estimates = collect($estimates); $estimates = collect($estimates);
$lines = $estimates->map(function ($delay) { return $delay['routeId']; })->unique(); $lines = $estimates->map(function ($delay) {
return $delay['routeId'];
})->unique();
$lines = $this->lines->getManyById($lines)->keyBy(t\property('id')); $lines = $this->lines->getManyById($lines)->keyBy(t\property('id'));
return collect($estimates)->map(function ($delay) use ($stop, $lines) { return collect($estimates)->map(function ($delay) use ($stop, $lines) {
@ -52,7 +54,7 @@ class ZtmGdanskDepartureRepository implements DepartureRepository
'vehicle' => $this->reference->get(Vehicle::class, $delay['vehicleCode']), 'vehicle' => $this->reference->get(Vehicle::class, $delay['vehicleCode']),
'line' => $lines->get($delay['routeId']) ?: Line::createFromArray([ 'line' => $lines->get($delay['routeId']) ?: Line::createFromArray([
'symbol' => $delay['routeId'], 'symbol' => $delay['routeId'],
'type' => Line::TYPE_UNKNOWN 'type' => Line::TYPE_UNKNOWN,
]), ]),
]); ]);
})->values(); })->values();

View File

@ -5,6 +5,7 @@ namespace App\Service;
use App\Event\DataUpdateEvent; use App\Event\DataUpdateEvent;
use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\Table;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use function Sodium\add;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class DataUpdater class DataUpdater
@ -34,10 +35,24 @@ class DataUpdater
$connection->getConfiguration()->setSQLLogger(null); $connection->getConfiguration()->setSQLLogger(null);
$schema = $connection->getSchemaManager(); $schema = $connection->getSchemaManager();
$path = $connection->getParams()['path'];
$backup = "$path.backup";
copy($path, $backup);
try {
collect($schema->listTables())->reject(function (Table $schema) { collect($schema->listTables())->reject(function (Table $schema) {
return $schema->getName() === 'migration_versions'; return $schema->getName() === 'migration_versions';
})->each([$schema, 'dropAndCreateTable']); })->each([$schema, 'dropAndCreateTable']);
$this->dispatcher->dispatch(self::UPDATE_EVENT, new DataUpdateEvent()); $this->dispatcher->dispatch(self::UPDATE_EVENT, new DataUpdateEvent());
} catch (\Throwable $exception) {
$connection->close();
unlink($path);
rename($backup, $path);
} finally {
unlink($backup);
}
} }
} }