Version.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. namespace Doctrine\DBAL\Migrations;
  20. use Doctrine\DBAL\Types\Type;
  21. use Doctrine\DBAL\Migrations\Configuration\Configuration;
  22. use Doctrine\DBAL\Migrations\Provider\LazySchemaDiffProvider;
  23. use Doctrine\DBAL\Migrations\Provider\SchemaDiffProvider;
  24. use Doctrine\DBAL\Migrations\Provider\SchemaDiffProviderInterface;
  25. /**
  26. * Class which wraps a migration version and allows execution of the
  27. * individual migration version up or down method.
  28. *
  29. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  30. * @link www.doctrine-project.org
  31. * @since 2.0
  32. * @author Jonathan H. Wage <jonwage@gmail.com>
  33. */
  34. class Version
  35. {
  36. const STATE_NONE = 0;
  37. const STATE_PRE = 1;
  38. const STATE_EXEC = 2;
  39. const STATE_POST = 3;
  40. const DIRECTION_UP = 'up';
  41. const DIRECTION_DOWN = 'down';
  42. /**
  43. * The Migrations Configuration instance for this migration
  44. *
  45. * @var Configuration
  46. */
  47. private $configuration;
  48. /**
  49. * The OutputWriter object instance used for outputting information
  50. *
  51. * @var OutputWriter
  52. */
  53. private $outputWriter;
  54. /**
  55. * The version in timestamp format (YYYYMMDDHHMMSS)
  56. *
  57. * @param int
  58. */
  59. private $version;
  60. /**
  61. * The migration instance for this version
  62. *
  63. * @var AbstractMigration
  64. */
  65. private $migration;
  66. /**
  67. * @var \Doctrine\DBAL\Connection
  68. */
  69. private $connection;
  70. /**
  71. * @var string
  72. */
  73. private $class;
  74. /** The array of collected SQL statements for this version */
  75. private $sql = [];
  76. /** The array of collected parameters for SQL statements for this version */
  77. private $params = [];
  78. /** The array of collected types for SQL statements for this version */
  79. private $types = [];
  80. /** The time in seconds that this migration version took to execute */
  81. private $time;
  82. /**
  83. * @var int
  84. */
  85. private $state = self::STATE_NONE;
  86. /** @var SchemaDiffProviderInterface */
  87. private $schemaProvider;
  88. public function __construct(Configuration $configuration, $version, $class, SchemaDiffProviderInterface $schemaProvider=null)
  89. {
  90. $this->configuration = $configuration;
  91. $this->outputWriter = $configuration->getOutputWriter();
  92. $this->class = $class;
  93. $this->connection = $configuration->getConnection();
  94. $this->migration = new $class($this);
  95. $this->version = $version;
  96. if ($schemaProvider !== null) {
  97. $this->schemaProvider = $schemaProvider;
  98. }
  99. if($schemaProvider === null) {
  100. $schemaProvider = new SchemaDiffProvider($this->connection->getSchemaManager(),
  101. $this->connection->getDatabasePlatform());
  102. $this->schemaProvider = LazySchemaDiffProvider::fromDefaultProxyFacyoryConfiguration($schemaProvider);
  103. }
  104. }
  105. /**
  106. * Returns the string version in the format YYYYMMDDHHMMSS
  107. *
  108. * @return string $version
  109. */
  110. public function getVersion()
  111. {
  112. return $this->version;
  113. }
  114. /**
  115. * Returns the Migrations Configuration object instance
  116. *
  117. * @return Configuration $configuration
  118. */
  119. public function getConfiguration()
  120. {
  121. return $this->configuration;
  122. }
  123. /**
  124. * Check if this version has been migrated or not.
  125. *
  126. * @return boolean
  127. */
  128. public function isMigrated()
  129. {
  130. return $this->configuration->hasVersionMigrated($this);
  131. }
  132. public function markMigrated()
  133. {
  134. $this->markVersion('up');
  135. }
  136. private function markVersion($direction)
  137. {
  138. $action = $direction === 'up' ? 'insert' : 'delete';
  139. $this->configuration->createMigrationTable();
  140. $this->connection->$action(
  141. $this->configuration->getMigrationsTableName(),
  142. [$this->configuration->getMigrationsColumnName() => $this->version]
  143. );
  144. }
  145. public function markNotMigrated()
  146. {
  147. $this->markVersion('down');
  148. }
  149. /**
  150. * Add some SQL queries to this versions migration
  151. *
  152. * @param array|string $sql
  153. * @param array $params
  154. * @param array $types
  155. */
  156. public function addSql($sql, array $params = [], array $types = [])
  157. {
  158. if (is_array($sql)) {
  159. foreach ($sql as $key => $query) {
  160. $this->sql[] = $query;
  161. if (!empty($params[$key])) {
  162. $queryTypes = isset($types[$key]) ? $types[$key] : [];
  163. $this->addQueryParams($params[$key], $queryTypes);
  164. }
  165. }
  166. } else {
  167. $this->sql[] = $sql;
  168. if (!empty($params)) {
  169. $this->addQueryParams($params, $types);
  170. }
  171. }
  172. }
  173. /**
  174. * @param mixed[] $params Array of prepared statement parameters
  175. * @param string[] $types Array of the types of each statement parameters
  176. */
  177. private function addQueryParams($params, $types)
  178. {
  179. $index = count($this->sql) - 1;
  180. $this->params[$index] = $params;
  181. $this->types[$index] = $types;
  182. }
  183. /**
  184. * Write a migration SQL file to the given path
  185. *
  186. * @param string $path The path to write the migration SQL file.
  187. * @param string $direction The direction to execute.
  188. *
  189. * @return boolean $written
  190. */
  191. public function writeSqlFile($path, $direction = self::DIRECTION_UP)
  192. {
  193. $queries = $this->execute($direction, true);
  194. if ( ! empty($this->params)) {
  195. throw MigrationException::migrationNotConvertibleToSql($this->class);
  196. }
  197. $this->outputWriter->write("\n-- Version " . $this->version . "\n");
  198. $sqlQueries = [$this->version => $queries];
  199. $sqlWriter = new SqlFileWriter(
  200. $this->configuration->getMigrationsColumnName(),
  201. $this->configuration->getMigrationsTableName(),
  202. $path,
  203. $this->outputWriter
  204. );
  205. return $sqlWriter->write($sqlQueries, $direction);
  206. }
  207. /**
  208. * @return AbstractMigration
  209. */
  210. public function getMigration()
  211. {
  212. return $this->migration;
  213. }
  214. /**
  215. * Execute this migration version up or down and and return the SQL.
  216. * We are only allowing the addSql call and the schema modification to take effect in the up and down call.
  217. * This is necessary to ensure that the migration is revertable.
  218. * The schema is passed to the pre and post method only to be able to test the presence of some table, And the
  219. * connection that can get used trough it allow for the test of the presence of records.
  220. *
  221. * @param string $direction The direction to execute the migration.
  222. * @param boolean $dryRun Whether to not actually execute the migration SQL and just do a dry run.
  223. * @param boolean $timeAllQueries Measuring or not the execution time of each SQL query.
  224. *
  225. * @return array $sql
  226. *
  227. * @throws \Exception when migration fails
  228. */
  229. public function execute($direction, $dryRun = false, $timeAllQueries = false)
  230. {
  231. $this->sql = [];
  232. $transaction = $this->migration->isTransactional();
  233. if ($transaction) {
  234. //only start transaction if in transactional mode
  235. $this->connection->beginTransaction();
  236. }
  237. try {
  238. $migrationStart = microtime(true);
  239. $this->state = self::STATE_PRE;
  240. $fromSchema = $this->schemaProvider->createFromSchema();
  241. $this->migration->{'pre' . ucfirst($direction)}($fromSchema);
  242. if ($direction === self::DIRECTION_UP) {
  243. $this->outputWriter->write("\n" . sprintf(' <info>++</info> migrating <comment>%s</comment>', $this->version) . "\n");
  244. } else {
  245. $this->outputWriter->write("\n" . sprintf(' <info>--</info> reverting <comment>%s</comment>', $this->version) . "\n");
  246. }
  247. $this->state = self::STATE_EXEC;
  248. $toSchema = $this->schemaProvider->createToSchema($fromSchema);
  249. $this->migration->$direction($toSchema);
  250. $this->addSql($this->schemaProvider->getSqlDiffToMigrate($fromSchema, $toSchema));
  251. $this->executeRegisteredSql($dryRun, $timeAllQueries);
  252. $this->state = self::STATE_POST;
  253. $this->migration->{'post' . ucfirst($direction)}($toSchema);
  254. if (! $dryRun) {
  255. if ($direction === self::DIRECTION_UP) {
  256. $this->markMigrated();
  257. } else {
  258. $this->markNotMigrated();
  259. }
  260. }
  261. $migrationEnd = microtime(true);
  262. $this->time = round($migrationEnd - $migrationStart, 2);
  263. if ($direction === self::DIRECTION_UP) {
  264. $this->outputWriter->write(sprintf("\n <info>++</info> migrated (%ss)", $this->time));
  265. } else {
  266. $this->outputWriter->write(sprintf("\n <info>--</info> reverted (%ss)", $this->time));
  267. }
  268. if ($transaction) {
  269. //commit only if running in transactional mode
  270. $this->connection->commit();
  271. }
  272. $this->state = self::STATE_NONE;
  273. return $this->sql;
  274. } catch (SkipMigrationException $e) {
  275. if ($transaction) {
  276. //only rollback transaction if in transactional mode
  277. $this->connection->rollBack();
  278. }
  279. if ($dryRun === false) {
  280. // now mark it as migrated
  281. if ($direction === self::DIRECTION_UP) {
  282. $this->markMigrated();
  283. } else {
  284. $this->markNotMigrated();
  285. }
  286. }
  287. $this->outputWriter->write(sprintf("\n <info>SS</info> skipped (Reason: %s)", $e->getMessage()));
  288. $this->state = self::STATE_NONE;
  289. return [];
  290. } catch (\Exception $e) {
  291. $this->outputWriter->write(sprintf(
  292. '<error>Migration %s failed during %s. Error %s</error>',
  293. $this->version, $this->getExecutionState(), $e->getMessage()
  294. ));
  295. if ($transaction) {
  296. //only rollback transaction if in transactional mode
  297. $this->connection->rollBack();
  298. }
  299. $this->state = self::STATE_NONE;
  300. throw $e;
  301. }
  302. }
  303. public function getExecutionState()
  304. {
  305. switch ($this->state) {
  306. case self::STATE_PRE:
  307. return 'Pre-Checks';
  308. case self::STATE_POST:
  309. return 'Post-Checks';
  310. case self::STATE_EXEC:
  311. return 'Execution';
  312. default:
  313. return 'No State';
  314. }
  315. }
  316. private function outputQueryTime($queryStart, $timeAllQueries = false)
  317. {
  318. if ($timeAllQueries !== false) {
  319. $queryEnd = microtime(true);
  320. $queryTime = round($queryEnd - $queryStart, 4);
  321. $this->outputWriter->write(sprintf(" <info>%ss</info>", $queryTime));
  322. }
  323. }
  324. /**
  325. * Returns the time this migration version took to execute
  326. *
  327. * @return integer $time The time this migration version took to execute
  328. */
  329. public function getTime()
  330. {
  331. return $this->time;
  332. }
  333. public function __toString()
  334. {
  335. return $this->version;
  336. }
  337. private function executeRegisteredSql($dryRun = false, $timeAllQueries = false)
  338. {
  339. if (! $dryRun) {
  340. if (!empty($this->sql)) {
  341. foreach ($this->sql as $key => $query) {
  342. $queryStart = microtime(true);
  343. if ( ! isset($this->params[$key])) {
  344. $this->outputWriter->write(' <comment>-></comment> ' . $query);
  345. $this->connection->executeQuery($query);
  346. } else {
  347. $this->outputWriter->write(sprintf(' <comment>-</comment> %s (with parameters)', $query));
  348. $this->connection->executeQuery($query, $this->params[$key], $this->types[$key]);
  349. }
  350. $this->outputQueryTime($queryStart, $timeAllQueries);
  351. }
  352. } else {
  353. $this->outputWriter->write(sprintf(
  354. '<error>Migration %s was executed but did not result in any SQL statements.</error>',
  355. $this->version
  356. ));
  357. }
  358. } else {
  359. foreach ($this->sql as $idx => $query) {
  360. $this->outputSqlQuery($idx, $query);
  361. }
  362. }
  363. }
  364. /**
  365. * Outputs a SQL query via the `OutputWriter`.
  366. *
  367. * @param int $idx The SQL query index. Used to look up params.
  368. * @param string $query the query to output
  369. * @return void
  370. */
  371. private function outputSqlQuery($idx, $query)
  372. {
  373. $params = $this->formatParamsForOutput(
  374. isset($this->params[$idx]) ? $this->params[$idx] : [],
  375. isset($this->types[$idx]) ? $this->types[$idx] : []
  376. );
  377. $this->outputWriter->write(rtrim(sprintf(
  378. ' <comment>-></comment> %s %s',
  379. $query,
  380. $params
  381. )));
  382. }
  383. /**
  384. * Formats a set of sql parameters for output with dry run.
  385. *
  386. * @param $params The query parameters
  387. * @param $types The types of the query params. Default type is a string
  388. * @return string|null a string of the parameters present.
  389. */
  390. private function formatParamsForOutput(array $params, array $types)
  391. {
  392. if (empty($params)) {
  393. return '';
  394. }
  395. $platform = $this->connection->getDatabasePlatform();
  396. $out = [];
  397. foreach ($params as $key => $value) {
  398. $type = isset($types[$key]) ? $types[$key] : 'string';
  399. $outval = Type::getType($type)->convertToDatabaseValue($value, $platform);
  400. $out[] = is_string($key) ? sprintf(':%s => %s', $key, $outval) : $outval;
  401. }
  402. return sprintf('with parameters (%s)', implode(', ', $out));
  403. }
  404. }