Completed
Push — master ( d7101c...2f6667 )
by Mike
05:39
created

Version::dispatchEvent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
crap 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the LGPL. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Migrations;
21
22
use Doctrine\DBAL\Types\Type;
23
use Doctrine\DBAL\Migrations\Configuration\Configuration;
24
use Doctrine\DBAL\Migrations\Event\MigrationsVersionEventArgs;
25
use Doctrine\DBAL\Migrations\Provider\LazySchemaDiffProvider;
26
use Doctrine\DBAL\Migrations\Provider\SchemaDiffProvider;
27
use Doctrine\DBAL\Migrations\Provider\SchemaDiffProviderInterface;
28
29
/**
30
 * Class which wraps a migration version and allows execution of the
31
 * individual migration version up or down method.
32
 *
33
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
34
 * @link        www.doctrine-project.org
35
 * @since       2.0
36
 * @author      Jonathan H. Wage <[email protected]>
37
 */
38
class Version
39
{
40
    const STATE_NONE = 0;
41
    const STATE_PRE  = 1;
42
    const STATE_EXEC = 2;
43
    const STATE_POST = 3;
44
45
    const DIRECTION_UP = 'up';
46
    const DIRECTION_DOWN = 'down';
47
48
    /**
49
     * The Migrations Configuration instance for this migration
50
     *
51
     * @var Configuration
52
     */
53
    private $configuration;
54
55
    /**
56
     * The OutputWriter object instance used for outputting information
57
     *
58
     * @var OutputWriter
59
     */
60
    private $outputWriter;
61
62
    /**
63
     * The version in timestamp format (YYYYMMDDHHMMSS)
64
     *
65
     * @param int
66
     */
67
    private $version;
68
69
    /**
70
     * The migration instance for this version
71
     *
72
     * @var AbstractMigration
73
     */
74
    private $migration;
75
76
    /**
77
     * @var \Doctrine\DBAL\Connection
78
     */
79
    private $connection;
80
81
    /**
82
     * @var string
83
     */
84
    private $class;
85
86
    /** The array of collected SQL statements for this version */
87
    private $sql = [];
88
89
    /** The array of collected parameters for SQL statements for this version */
90
    private $params = [];
91
92
    /** The array of collected types for SQL statements for this version */
93
    private $types = [];
94
95
    /** The time in seconds that this migration version took to execute */
96
    private $time;
97
98
    /**
99
     * @var int
100
     */
101
    private $state = self::STATE_NONE;
102
103
    /** @var SchemaDiffProviderInterface */
104
    private $schemaProvider;
105
106 112
    public function __construct(Configuration $configuration, $version, $class, SchemaDiffProviderInterface $schemaProvider=null)
107
    {
108 112
        $this->configuration = $configuration;
109 112
        $this->outputWriter = $configuration->getOutputWriter();
110 112
        $this->class = $class;
111 112
        $this->connection = $configuration->getConnection();
112 112
        $this->migration = new $class($this);
113 112
        $this->version = $version;
114
115 112
        if ($schemaProvider !== null) {
116 1
            $this->schemaProvider = $schemaProvider;
117 1
        }
118 112
        if($schemaProvider === null) {
119 111
            $schemaProvider = new SchemaDiffProvider($this->connection->getSchemaManager(),
120 111
                $this->connection->getDatabasePlatform());
121 111
            $this->schemaProvider = LazySchemaDiffProvider::fromDefaultProxyFacyoryConfiguration($schemaProvider);
122 111
        }
123 112
    }
124
125
    /**
126
     * Returns the string version in the format YYYYMMDDHHMMSS
127
     *
128
     * @return string $version
129
     */
130 72
    public function getVersion()
131
    {
132 72
        return $this->version;
133
    }
134
135
    /**
136
     * Returns the Migrations Configuration object instance
137
     *
138
     * @return Configuration $configuration
139
     */
140 108
    public function getConfiguration()
141
    {
142 108
        return $this->configuration;
143
    }
144
145
    /**
146
     * Check if this version has been migrated or not.
147
     *
148
     * @return boolean
149
     */
150 15
    public function isMigrated()
151
    {
152 15
        return $this->configuration->hasVersionMigrated($this);
153
    }
154
155 39
    public function markMigrated()
156
    {
157 39
        $this->markVersion('up');
158 39
    }
159
160 39
    private function markVersion($direction)
161
    {
162 39
        $action = $direction === 'up' ? 'insert' : 'delete';
163
164 39
        $this->configuration->createMigrationTable();
165 39
        $this->connection->$action(
166 39
            $this->configuration->getMigrationsTableName(),
167 39
            [$this->configuration->getMigrationsColumnName() => $this->version]
168 39
        );
169 39
    }
170
171 14
    public function markNotMigrated()
172
    {
173 9
        $this->markVersion('down');
174 14
    }
175
176
    /**
177
     * Add some SQL queries to this versions migration
178
     *
179
     * @param array|string $sql
180
     * @param array        $params
181
     * @param array        $types
182
     */
183 42
    public function addSql($sql, array $params = [], array $types = [])
184
    {
185 42
        if (is_array($sql)) {
186 41
            foreach ($sql as $key => $query) {
187 14
                $this->sql[] = $query;
188 14
                if (!empty($params[$key])) {
189 1
                    $queryTypes = isset($types[$key]) ? $types[$key] : [];
190 1
                    $this->addQueryParams($params[$key], $queryTypes);
191 1
                }
192 41
            }
193 41
        } else {
194 23
            $this->sql[] = $sql;
195 23
            if (!empty($params)) {
196 12
                $this->addQueryParams($params, $types);
197 12
            }
198
        }
199 42
    }
200
201
    /**
202
     * @param mixed[] $params Array of prepared statement parameters
203
     * @param string[] $types Array of the types of each statement parameters
204
     */
205 13
    private function addQueryParams($params, $types)
206
    {
207 13
        $index = count($this->sql) - 1;
208 13
        $this->params[$index] = $params;
209 13
        $this->types[$index] = $types;
210 13
    }
211
212
    /**
213
     * Write a migration SQL file to the given path
214
     *
215
     * @param string $path      The path to write the migration SQL file.
216
     * @param string $direction The direction to execute.
217
     *
218
     * @return boolean $written
219
     */
220 9
    public function writeSqlFile($path, $direction = self::DIRECTION_UP)
221
    {
222 9
        $queries = $this->execute($direction, true);
223
224 9
        if ( ! empty($this->params)) {
225 1
            throw MigrationException::migrationNotConvertibleToSql($this->class);
226
        }
227
228 8
        $this->outputWriter->write("\n-- Version " . $this->version . "\n");
229
230 8
        $sqlQueries = [$this->version => $queries];
231 8
        $sqlWriter = new SqlFileWriter(
232 8
            $this->configuration->getMigrationsColumnName(),
233 8
            $this->configuration->getMigrationsTableName(),
234 8
            $path,
235 8
            $this->outputWriter
236 8
        );
237
238 8
        return $sqlWriter->write($sqlQueries, $direction);
239
    }
240
241
    /**
242
     * @return AbstractMigration
243
     */
244 4
    public function getMigration()
245
    {
246 4
        return $this->migration;
247
    }
248
249
    /**
250
     * Execute this migration version up or down and and return the SQL.
251
     * We are only allowing the addSql call and the schema modification to take effect in the up and down call.
252
     * This is necessary to ensure that the migration is revertable.
253
     * The schema is passed to the pre and post method only to be able to test the presence of some table, And the
254
     * connection that can get used trough it allow for the test of the presence of records.
255
     *
256
     * @param string  $direction      The direction to execute the migration.
257
     * @param boolean $dryRun         Whether to not actually execute the migration SQL and just do a dry run.
258
     * @param boolean $timeAllQueries Measuring or not the execution time of each SQL query.
259
     *
260
     * @return array $sql
261
     *
262
     * @throws \Exception when migration fails
263
     */
264 43
    public function execute($direction, $dryRun = false, $timeAllQueries = false)
265
    {
266 43
        $this->dispatchEvent(Events::onMigrationsVersionExecuting, $direction, $dryRun);
267
268 43
        $this->sql = [];
269
270 43
        $transaction = $this->migration->isTransactional();
271 43
        if ($transaction) {
272
            //only start transaction if in transactional mode
273 43
            $this->connection->beginTransaction();
274 43
        }
275
276
        try {
277 43
            $migrationStart = microtime(true);
278
279 43
            $this->state = self::STATE_PRE;
280 43
            $fromSchema = $this->schemaProvider->createFromSchema();
281
282 43
            $this->migration->{'pre' . ucfirst($direction)}($fromSchema);
283
284 41
            if ($direction === self::DIRECTION_UP) {
285 39
                $this->outputWriter->write("\n" . sprintf('  <info>++</info> migrating <comment>%s</comment>', $this->version) . "\n");
286 39
            } else {
287 8
                $this->outputWriter->write("\n" . sprintf('  <info>--</info> reverting <comment>%s</comment>', $this->version) . "\n");
288
            }
289
290 41
            $this->state = self::STATE_EXEC;
291
292 41
            $toSchema = $this->schemaProvider->createToSchema($fromSchema);
293 41
            $this->migration->$direction($toSchema);
294
295 40
            $this->addSql($this->schemaProvider->getSqlDiffToMigrate($fromSchema, $toSchema));
296
297 40
            $this->executeRegisteredSql($dryRun, $timeAllQueries);
298
299 40
            $this->state = self::STATE_POST;
300 40
            $this->migration->{'post' . ucfirst($direction)}($toSchema);
301
302 40
            if (! $dryRun) {
303 28
                if ($direction === self::DIRECTION_UP) {
304 28
                    $this->markMigrated();
305 28
                } else {
306 6
                    $this->markNotMigrated();
307
                }
308 28
            }
309
310 40
            $migrationEnd = microtime(true);
311 40
            $this->time = round($migrationEnd - $migrationStart, 2);
312 40
            if ($direction === self::DIRECTION_UP) {
313 38
                $this->outputWriter->write(sprintf("\n  <info>++</info> migrated (%ss)", $this->time));
314 38
            } else {
315 8
                $this->outputWriter->write(sprintf("\n  <info>--</info> reverted (%ss)", $this->time));
316
            }
317
318 40
            if ($transaction) {
319
                //commit only if running in transactional mode
320 40
                $this->connection->commit();
321 40
            }
322
323 40
            $this->state = self::STATE_NONE;
324
325 40
            $this->dispatchEvent(Events::onMigrationsVersionExecuted, $direction, $dryRun);
326
327 40
            return $this->sql;
328 7
        } catch (SkipMigrationException $e) {
329 6
            if ($transaction) {
330
                //only rollback transaction if in transactional mode
331 6
                $this->connection->rollBack();
332 6
            }
333
334 6
            if ($dryRun === false) {
335
                // now mark it as migrated
336 5
                if ($direction === self::DIRECTION_UP) {
337 5
                    $this->markMigrated();
338 5
                } else {
339 1
                    $this->markNotMigrated();
340
                }
341 5
            }
342
343 6
            $this->outputWriter->write(sprintf("\n  <info>SS</info> skipped (Reason: %s)",  $e->getMessage()));
344
345 6
            $this->state = self::STATE_NONE;
346
347 6
            $this->dispatchEvent(Events::onMigrationsVersionSkipped, $direction, $dryRun);
348
349 6
            return [];
350 1
        } catch (\Exception $e) {
351
352 1
            $this->outputWriter->write(sprintf(
353 1
                '<error>Migration %s failed during %s. Error %s</error>',
354 1
                $this->version, $this->getExecutionState(), $e->getMessage()
355 1
            ));
356
357 1
            if ($transaction) {
358
                //only rollback transaction if in transactional mode
359 1
                $this->connection->rollBack();
360 1
            }
361
362 1
            $this->state = self::STATE_NONE;
363
364 1
            throw $e;
365
        }
366
    }
367
368 8
    public function getExecutionState()
369
    {
370 8
        switch ($this->state) {
371 8
            case self::STATE_PRE:
372 1
                return 'Pre-Checks';
373 7
            case self::STATE_POST:
374 1
                return 'Post-Checks';
375 6
            case self::STATE_EXEC:
376 2
                return 'Execution';
377 4
            default:
378 4
                return 'No State';
379 4
        }
380
    }
381
382 19
    private function outputQueryTime($queryStart, $timeAllQueries = false)
383
    {
384 19
        if ($timeAllQueries !== false) {
385 1
            $queryEnd = microtime(true);
386 1
            $queryTime = round($queryEnd - $queryStart, 4);
387
388 1
            $this->outputWriter->write(sprintf("  <info>%ss</info>", $queryTime));
389 1
        }
390 19
    }
391
392
    /**
393
     * Returns the time this migration version took to execute
394
     *
395
     * @return integer $time The time this migration version took to execute
396
     */
397 25
    public function getTime()
398
    {
399 25
        return $this->time;
400
    }
401
402 2
    public function __toString()
403
    {
404 2
        return $this->version;
405
    }
406
407 40
    private function executeRegisteredSql($dryRun = false, $timeAllQueries = false)
408
    {
409 40
        if (! $dryRun) {
410 28
            if (!empty($this->sql)) {
411 17
                foreach ($this->sql as $key => $query) {
412 17
                    $queryStart = microtime(true);
413
414 17
                    if ( ! isset($this->params[$key])) {
415 16
                        $this->outputWriter->write('     <comment>-></comment> ' . $query);
416 16
                        $this->connection->executeQuery($query);
417 16
                    } else {
418 7
                        $this->outputWriter->write(sprintf('    <comment>-</comment> %s (with parameters)', $query));
419 7
                        $this->connection->executeQuery($query, $this->params[$key], $this->types[$key]);
420
                    }
421
422 17
                    $this->outputQueryTime($queryStart, $timeAllQueries);
423 17
                }
424 17
            } else {
425 11
                $this->outputWriter->write(sprintf(
426 11
                    '<error>Migration %s was executed but did not result in any SQL statements.</error>',
427 11
                    $this->version
428 11
                ));
429
            }
430 28
        } else {
431 12
            foreach ($this->sql as $idx => $query) {
432 12
                $this->outputSqlQuery($idx, $query);
433 12
            }
434
        }
435 40
    }
436
437
    /**
438
     * Outputs a SQL query via the `OutputWriter`.
439
     *
440
     * @param int $idx The SQL query index. Used to look up params.
441
     * @param string $query the query to output
442
     * @return void
443
     */
444 12
    private function outputSqlQuery($idx, $query)
445
    {
446 12
        $params = $this->formatParamsForOutput(
447 12
            isset($this->params[$idx]) ? $this->params[$idx] : [],
448 12
            isset($this->types[$idx]) ? $this->types[$idx] : []
449 12
        );
450
451 12
        $this->outputWriter->write(rtrim(sprintf(
452 12
            '     <comment>-></comment> %s %s',
453 12
            $query,
454
            $params
455 12
        )));
456 12
    }
457
458
    /**
459
     * Formats a set of sql parameters for output with dry run.
460
     *
461
     * @param $params The query parameters
462
     * @param $types The types of the query params. Default type is a string
463
     * @return string|null a string of the parameters present.
464
     */
465 12
    private function formatParamsForOutput(array $params, array $types)
466
    {
467 12
        if (empty($params)) {
468 8
            return '';
469
        }
470
471 5
        $platform = $this->connection->getDatabasePlatform();
472 5
        $out = [];
473 5
        foreach ($params as $key => $value) {
474 5
            $type = isset($types[$key]) ? $types[$key] : 'string';
475 5
            $outval = Type::getType($type)->convertToDatabaseValue($value, $platform);
476 5
            $out[] = is_string($key) ? sprintf(':%s => %s', $key, $outval) : $outval;
477 5
        }
478
479 5
        return sprintf('with parameters (%s)', implode(', ', $out));
480
    }
481
482 43
    private function dispatchEvent($eventName, $direction, $dryRun)
483
    {
484 43
        $this->configuration->dispatchEvent($eventName, new MigrationsVersionEventArgs(
485 43
            $this,
486 43
            $this->configuration,
487 43
            $direction,
488
            $dryRun
489 43
        ));
490 43
    }
491
}
492