From afe0bfb373c23ba514e49aa3c38ea6575907efef Mon Sep 17 00:00:00 2001 From: Thomas Gelf Date: Wed, 17 Feb 2016 15:42:34 +0100 Subject: [PATCH] Migrations: run initial schema file... ...when no migrations have ever been applied --- library/Director/Db/Migration.php | 14 ++++++-------- library/Director/Db/Migrations.php | 27 ++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/library/Director/Db/Migration.php b/library/Director/Db/Migration.php index 5e67224f..3392a43c 100644 --- a/library/Director/Db/Migration.php +++ b/library/Director/Db/Migration.php @@ -27,7 +27,9 @@ class Migration public function apply(Db $connection) { $db = $connection->getDbAdapter(); - $queries = preg_split('/[\n\s\t]*\;[\n\s\t]*/s', $this->sql, -1, PREG_SPLIT_NO_EMPTY); + + // 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); if (empty($queries)) { throw new IcingaException( @@ -37,21 +39,17 @@ class Migration } try { - $db->beginTransaction(); - foreach ($queries as $query) { $db->exec($query); } - $db->commit(); - } catch (Exception $e) { - $db->rollback(); throw new IcingaException( - 'Migration %d failed: %s', + 'Migration %d failed (%s) while running %s', $this->version, - $e->getMessage() + $e->getMessage(), + $query ); } diff --git a/library/Director/Db/Migrations.php b/library/Director/Db/Migrations.php index c48b7cd4..7872aef3 100644 --- a/library/Director/Db/Migrations.php +++ b/library/Director/Db/Migrations.php @@ -74,6 +74,11 @@ class Migrations public function listPendingMigrations() { + $lastMigration = $this->getLastMigrationNumber(); + if ($lastMigration === 0) { + return array(0); + } + return $this->listMigrationsAfter($this->getLastMigrationNumber()); } @@ -101,11 +106,15 @@ class Migrations public function loadMigrationFile($version) { - $filename = sprintf( - '%s/upgrade_%d.sql', - $this->getMigrationsDir(), - $version - ); + if ($version === 0) { + $filename = $this->getFullSchemaFile(); + } else { + $filename = sprintf( + '%s/upgrade_%d.sql', + $this->getMigrationsDir(), + $version + ); + } return file_get_contents($filename); } @@ -133,4 +142,12 @@ class Migrations return $this->migrationsDir; } + + protected function getFullSchemaFile() + { + return dirname(dirname(dirname(__DIR__))) + . '/schema/' + . $this->connection->getDbType() + . '.sql'; + } }