Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 371 lines (311 sloc) 10.503 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
<?php

/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Propel\Generator\Manager;

use Propel\Generator\Exception\InvalidArgumentException;
use Propel\Generator\Model\Column;
use Propel\Generator\Model\Table;

use \PDO;
use \Exception;
use \PDOException;

/**
* Service class for preparing and executing migrations
*
* @author François Zaninotto
*/
class MigrationManager extends AbstractManager
{
    /**
* @var array
*/
    protected $connections = array();

    /**
* @var array
*/
    protected $pdoConnections = array();

    /**
* @var string
*/
    protected $migrationTable;

    /**
* Set the database connection settings
*
* @param array $connections
*/
    public function setConnections($connections)
    {
        $this->connections = $connections;
    }

    /**
* Get the database connection settings
*
* @return array
*/
    public function getConnections()
    {
        return $this->connections;
    }

    public function getConnection($datasource)
    {
        if (!isset($this->connections[$datasource])) {
            throw new InvalidArgumentException(sprintf('Unknown datasource "%s"', $datasource));
        }

        return $this->connections[$datasource];
    }

    public function getPdoConnection($datasource)
    {
        if (!isset($pdoConnections[$datasource])) {
            $buildConnection = $this->getConnection($datasource);
            $dsn = str_replace("@DB@", $datasource, $buildConnection['dsn']);

            // Set user + password to null if they are empty strings or missing
            $username = isset($buildConnection['user']) && $buildConnection['user'] ? $buildConnection['user'] : null;
            $password = isset($buildConnection['password']) && $buildConnection['password'] ? $buildConnection['password'] : null;

            $pdo = new PDO($dsn, $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $pdoConnections[$datasource] = $pdo;
        }

        return $pdoConnections[$datasource];
    }

    public function getPlatform($datasource)
    {
        $params = $this->getConnection($datasource);
        $adapter = $params['adapter'];
        $adapterClass = '\\Propel\\Generator\\Platform\\' . ucfirst($adapter) . 'Platform';

        return new $adapterClass();
    }

    /**
* Set the migration table name
*
* @param string $migrationTable
*/
    public function setMigrationTable($migrationTable)
    {
        $this->migrationTable = $migrationTable;
    }

    /**
* get the migration table name
*
* @return string
*/
    public function getMigrationTable()
    {
        return $this->migrationTable;
    }

    public function getOldestDatabaseVersion()
    {
        if (!$connections = $this->getConnections()) {
            throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use migrations');
        }

        $oldestMigrationTimestamp = null;
        $migrationTimestamps = array();
        foreach ($connections as $name => $params) {
            $pdo = $this->getPdoConnection($name);
            $sql = sprintf('SELECT version FROM %s', $this->getMigrationTable());

            try {
                $stmt = $pdo->prepare($sql);
                $stmt->execute();
                if ($migrationTimestamp = $stmt->fetchColumn()) {
                    $migrationTimestamps[$name] = $migrationTimestamp;
                }
            } catch (PDOException $e) {
                $this->createMigrationTable($name);
                $oldestMigrationTimestamp = 0;
            }
        }

        if ($oldestMigrationTimestamp === null && $migrationTimestamps) {
            sort($migrationTimestamps);
            $oldestMigrationTimestamp = array_shift($migrationTimestamps);
        }

        return $oldestMigrationTimestamp;
    }

    public function migrationTableExists($datasource)
    {
        $pdo = $this->getPdoConnection($datasource);
        $sql = sprintf('SELECT version FROM %s', $this->getMigrationTable());
        $stmt = $pdo->prepare($sql);
        try {
            $stmt->execute();

            return true;
        } catch (PDOException $e) {
            return false;
        }
    }

    public function createMigrationTable($datasource)
    {
        $platform = $this->getPlatform($datasource);
        // modelize the table
        $database = new Database($datasource);
        $database->setPlatform($platform);

        $table = new Table($this->getMigrationTable());
        $database->addTable($table);

        $column = new Column('version');
        $column->getDomain()->copy($platform->getDomainForType('INTEGER'));
        $column->setDefaultValue(0);

        $table->addColumn($column);
        // insert the table into the database
        $statements = $platform->getAddTableDDL($table);
        $pdo = $this->getPdoConnection($datasource);
        $res = SqlParser::executeString($statements, $pdo);

        if (!$res) {
            throw new Exception(sprintf('Unable to create migration table in datasource "%s"', $datasource));
        }
    }

    public function updateLatestMigrationTimestamp($datasource, $timestamp)
    {
        $platform = $this->getPlatform($datasource);
        $pdo = $this->getPdoConnection($datasource);
        $sql = sprintf('DELETE FROM %s', $this->getMigrationTable());
        $pdo->beginTransaction();
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $sql = sprintf('INSERT INTO %s (%s) VALUES (?)',
            $this->getMigrationTable(),
            $platform->quoteIdentifier('version')
        );
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(1, $timestamp, PDO::PARAM_INT);
        $stmt->execute();
        $pdo->commit();
    }

    public function getMigrationTimestamps()
    {
        $path = $this->getWorkingDirectory();
        $migrationTimestamps = array();

        if (is_dir($path)) {
            $files = scandir($path);
            foreach ($files as $file) {
                if (preg_match('/^PropelMigration_(\d+)\.php$/', $file, $matches)) {
                    $migrationTimestamps[] = (integer) $matches[1];
                }
            }
        }

        return $migrationTimestamps;
    }

    public function getValidMigrationTimestamps()
    {
        $oldestMigrationTimestamp = $this->getOldestDatabaseVersion();
        $migrationTimestamps = $this->getMigrationTimestamps();
        // removing already executed migrations
        foreach ($migrationTimestamps as $key => $timestamp) {
            if ($timestamp <= $oldestMigrationTimestamp) {
                unset($migrationTimestamps[$key]);
            }
        }
        sort($migrationTimestamps);

        return $migrationTimestamps;
    }

    public function hasPendingMigrations()
    {
        return array() !== $this->getValidMigrationTimestamps();
    }

    public function getAlreadyExecutedMigrationTimestamps()
    {
        $oldestMigrationTimestamp = $this->getOldestDatabaseVersion();
        $migrationTimestamps = $this->getMigrationTimestamps();
        // removing already executed migrations
        foreach ($migrationTimestamps as $key => $timestamp) {
            if ($timestamp > $oldestMigrationTimestamp) {
                unset($migrationTimestamps[$key]);
            }
        }
        sort($migrationTimestamps);

        return $migrationTimestamps;
    }

    public function getFirstUpMigrationTimestamp()
    {
        $validTimestamps = $this->getValidMigrationTimestamps();

        return array_shift($validTimestamps);
    }

    public function getFirstDownMigrationTimestamp()
    {
        return $this->getOldestDatabaseVersion();
    }

    static public function getMigrationClassName($timestamp)
    {
        return sprintf('PropelMigration_%d', $timestamp);
    }

    public function getMigrationObject($timestamp)
    {
        $className = $this->getMigrationClassName($timestamp);
        require_once sprintf('%s/%s.php',
            $this->getWorkingDirectory(),
            $className
        );

        return new $className();
    }

    public function getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp)
    {
        $timeInWords = date('Y-m-d H:i:s', $timestamp);
        $migrationAuthor = ($author = $this->getUser()) ? 'by ' . $author : '';
        $migrationClassName = $this->getMigrationClassName($timestamp);
        $migrationUpString = var_export($migrationsUp, true);
        $migrationDownString = var_export($migrationsDown, true);
        $migrationClassBody = <<<EOP
<?php

/**
* Data object containing the SQL and PHP code to migrate the database
* up to version $timestamp.
* Generated on $timeInWords $migrationAuthor
*/
class $migrationClassName
{

    public function preUp(\$manager)
    {
        // add the pre-migration code here
    }

    public function postUp(\$manager)
    {
        // add the post-migration code here
    }

    public function preDown(\$manager)
    {
        // add the pre-migration code here
    }

    public function postDown(\$manager)
    {
        // add the post-migration code here
    }

    /**
* Get the SQL statements for the Up migration
*
* @return array list of the SQL strings to execute for the Up migration
* the keys being the datasources
*/
    public function getUpSQL()
    {
        return $migrationUpString;
    }

    /**
* Get the SQL statements for the Down migration
*
* @return array list of the SQL strings to execute for the Down migration
* the keys being the datasources
*/
    public function getDownSQL()
    {
        return $migrationDownString;
    }

}
EOP;

        return $migrationClassBody;
    }

    static public function getMigrationFileName($timestamp)
    {
        return sprintf('%s.php', self::getMigrationClassName($timestamp));
    }

    static public function getUser()
    {
        if (function_exists('posix_getuid')) {
            $currentUser = posix_getpwuid(posix_getuid());
            if (isset($currentUser['name'])) {
                return $currentUser['name'];
            }
        }

        return '';
    }
}
Something went wrong with that request. Please try again.