2016-02-08 22:26:13 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Icinga\Module\Director\Db;
|
|
|
|
|
|
|
|
use Exception;
|
|
|
|
use Icinga\Exception\IcingaException;
|
|
|
|
use Icinga\Module\Director\Db;
|
|
|
|
|
|
|
|
class Migration
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $sql;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var int
|
|
|
|
*/
|
|
|
|
protected $version;
|
|
|
|
|
|
|
|
public function __construct($version, $sql)
|
|
|
|
{
|
|
|
|
$this->version = $version;
|
|
|
|
$this->sql = $sql;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function apply(Db $connection)
|
|
|
|
{
|
|
|
|
$db = $connection->getDbAdapter();
|
2016-02-17 15:42:34 +01:00
|
|
|
|
|
|
|
// TODO: this is fagile and depends on accordingly written schema files:
|
|
|
|
$queries = preg_split('/[\n\s\t]*\;[\n\s\t]+/s', $this->sql, -1, PREG_SPLIT_NO_EMPTY);
|
2016-02-08 22:26:13 +01:00
|
|
|
|
|
|
|
if (empty($queries)) {
|
|
|
|
throw new IcingaException(
|
|
|
|
'Migration %d has no queries',
|
|
|
|
$this->version
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
foreach ($queries as $query) {
|
2016-07-26 13:43:18 +02:00
|
|
|
if (preg_match('/^OPTIMIZE /i', $query)) {
|
|
|
|
$db->query($query);
|
|
|
|
} else {
|
|
|
|
$db->exec($query);
|
|
|
|
}
|
2016-02-08 22:26:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
|
|
|
throw new IcingaException(
|
2016-02-17 15:42:34 +01:00
|
|
|
'Migration %d failed (%s) while running %s',
|
2016-02-08 22:26:13 +01:00
|
|
|
$this->version,
|
2016-02-17 15:42:34 +01:00
|
|
|
$e->getMessage(),
|
|
|
|
$query
|
2016-02-08 22:26:13 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
}
|