Version.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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\Migrations\Configuration\Configuration;
  21. /**
  22. * Class which wraps a migration version and allows execution of the
  23. * individual migration version up or down method.
  24. *
  25. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  26. * @link www.doctrine-project.org
  27. * @since 2.0
  28. * @author Jonathan H. Wage <jonwage@gmail.com>
  29. */
  30. class Version
  31. {
  32. const STATE_NONE = 0;
  33. const STATE_PRE = 1;
  34. const STATE_EXEC = 2;
  35. const STATE_POST = 3;
  36. /**
  37. * The Migrations Configuration instance for this migration
  38. *
  39. * @var Configuration
  40. */
  41. private $configuration;
  42. /**
  43. * The OutputWriter object instance used for outputting information
  44. *
  45. * @var OutputWriter
  46. */
  47. private $outputWriter;
  48. /**
  49. * The version in timestamp format (YYYYMMDDHHMMSS)
  50. *
  51. * @param int
  52. */
  53. private $version;
  54. /**
  55. * @var \Doctrine\DBAL\Schema\AbstractSchemaManager
  56. */
  57. private $sm;
  58. /**
  59. * @var \Doctrine\DBAL\Platforms\AbstractPlatform
  60. */
  61. private $platform;
  62. /**
  63. * The migration instance for this version
  64. *
  65. * @var AbstractMigration
  66. */
  67. private $migration;
  68. /**
  69. * @var \Doctrine\DBAL\Connection
  70. */
  71. private $connection;
  72. /**
  73. * @var string
  74. */
  75. private $class;
  76. /** The array of collected SQL statements for this version */
  77. private $sql = array();
  78. /** The array of collected parameters for SQL statements for this version */
  79. private $params = array();
  80. /** The array of collected types for SQL statements for this version */
  81. private $types = array();
  82. /** The time in seconds that this migration version took to execute */
  83. private $time;
  84. /**
  85. * @var int
  86. */
  87. private $state = self::STATE_NONE;
  88. public function __construct(Configuration $configuration, $version, $class)
  89. {
  90. $this->configuration = $configuration;
  91. $this->outputWriter = $configuration->getOutputWriter();
  92. $this->class = $class;
  93. $this->connection = $configuration->getConnection();
  94. $this->sm = $this->connection->getSchemaManager();
  95. $this->platform = $this->connection->getDatabasePlatform();
  96. $this->migration = new $class($this);
  97. $this->version = $this->migration->getName() ?: $version;
  98. }
  99. /**
  100. * Returns the string version in the format YYYYMMDDHHMMSS
  101. *
  102. * @return string $version
  103. */
  104. public function getVersion()
  105. {
  106. return $this->version;
  107. }
  108. /**
  109. * Returns the Migrations Configuration object instance
  110. *
  111. * @return Configuration $configuration
  112. */
  113. public function getConfiguration()
  114. {
  115. return $this->configuration;
  116. }
  117. /**
  118. * Check if this version has been migrated or not.
  119. *
  120. * @return boolean
  121. */
  122. public function isMigrated()
  123. {
  124. return $this->configuration->hasVersionMigrated($this);
  125. }
  126. public function markMigrated()
  127. {
  128. $this->configuration->createMigrationTable();
  129. $this->connection->executeQuery("INSERT INTO " . $this->configuration->getMigrationsTableName() . " (version) VALUES (?)", array($this->version));
  130. }
  131. public function markNotMigrated()
  132. {
  133. $this->configuration->createMigrationTable();
  134. $this->connection->executeQuery("DELETE FROM " . $this->configuration->getMigrationsTableName() . " WHERE version = ?", array($this->version));
  135. }
  136. /**
  137. * Add some SQL queries to this versions migration
  138. *
  139. * @param array|string $sql
  140. * @param array $params
  141. * @param array $types
  142. *
  143. * @return void
  144. */
  145. public function addSql($sql, array $params = array(), array $types = array())
  146. {
  147. if (is_array($sql)) {
  148. foreach ($sql as $key => $query) {
  149. $this->sql[] = $query;
  150. if (isset($params[$key])) {
  151. $this->params[count($this->sql) - 1] = $params[$key];
  152. $this->types[count($this->sql) - 1] = isset($types[$key]) ? $types[$key] : array();
  153. }
  154. }
  155. } else {
  156. $this->sql[] = $sql;
  157. if ($params) {
  158. $this->params[count($this->sql) - 1] = $params;
  159. $this->types[count($this->sql) - 1] = $types ?: array();
  160. }
  161. }
  162. }
  163. /**
  164. * Write a migration SQL file to the given path
  165. *
  166. * @param string $path The path to write the migration SQL file.
  167. * @param string $direction The direction to execute.
  168. *
  169. * @return boolean $written
  170. */
  171. public function writeSqlFile($path, $direction = 'up')
  172. {
  173. $queries = $this->execute($direction, true);
  174. $string = sprintf("# Doctrine Migration File Generated on %s\n", date('Y-m-d H:m:s'));
  175. $string .= "\n# Version " . $this->version . "\n";
  176. foreach ($queries as $query) {
  177. $string .= $query . ";\n";
  178. }
  179. if (is_dir($path)) {
  180. $path = realpath($path);
  181. $path = $path . '/doctrine_migration_' . date('YmdHis') . '.sql';
  182. }
  183. $this->outputWriter->write("\n".sprintf('Writing migration file to "<info>%s</info>"', $path));
  184. return file_put_contents($path, $string);
  185. }
  186. /**
  187. * @return AbstractMigration
  188. */
  189. public function getMigration()
  190. {
  191. return $this->migration;
  192. }
  193. /**
  194. * Execute this migration version up or down and and return the SQL.
  195. *
  196. * @param string $direction The direction to execute the migration.
  197. * @param boolean $dryRun Whether to not actually execute the migration SQL and just do a dry run.
  198. *
  199. * @return array $sql
  200. *
  201. * @throws \Exception when migration fails
  202. */
  203. public function execute($direction, $dryRun = false)
  204. {
  205. $this->sql = array();
  206. $this->connection->beginTransaction();
  207. try {
  208. $start = microtime(true);
  209. $this->state = self::STATE_PRE;
  210. $fromSchema = $this->sm->createSchema();
  211. $this->migration->{'pre' . ucfirst($direction)}($fromSchema);
  212. if ($direction === 'up') {
  213. $this->outputWriter->write("\n" . sprintf(' <info>++</info> migrating <comment>%s</comment>', $this->version) . "\n");
  214. } else {
  215. $this->outputWriter->write("\n" . sprintf(' <info>--</info> reverting <comment>%s</comment>', $this->version) . "\n");
  216. }
  217. $this->state = self::STATE_EXEC;
  218. $toSchema = clone $fromSchema;
  219. $this->migration->$direction($toSchema);
  220. $this->addSql($fromSchema->getMigrateToSql($toSchema, $this->platform));
  221. if ($dryRun === false) {
  222. if ($this->sql) {
  223. foreach ($this->sql as $key => $query) {
  224. if ( ! isset($this->params[$key])) {
  225. $this->outputWriter->write(' <comment>-></comment> ' . $query);
  226. $this->connection->executeQuery($query);
  227. } else {
  228. $this->outputWriter->write(sprintf(' <comment>-</comment> %s (with parameters)', $query));
  229. $this->connection->executeQuery($query, $this->params[$key], $this->types[$key]);
  230. }
  231. }
  232. } else {
  233. $this->outputWriter->write(sprintf('<error>Migration %s was executed but did not result in any SQL statements.</error>', $this->version));
  234. }
  235. if ($direction === 'up') {
  236. $this->markMigrated();
  237. } else {
  238. $this->markNotMigrated();
  239. }
  240. } else {
  241. foreach ($this->sql as $query) {
  242. $this->outputWriter->write(' <comment>-></comment> ' . $query);
  243. }
  244. }
  245. $this->state = self::STATE_POST;
  246. $this->migration->{'post' . ucfirst($direction)}($toSchema);
  247. $end = microtime(true);
  248. $this->time = round($end - $start, 2);
  249. if ($direction === 'up') {
  250. $this->outputWriter->write(sprintf("\n <info>++</info> migrated (%ss)", $this->time));
  251. } else {
  252. $this->outputWriter->write(sprintf("\n <info>--</info> reverted (%ss)", $this->time));
  253. }
  254. $this->connection->commit();
  255. $this->state = self::STATE_NONE;
  256. return $this->sql;
  257. } catch (SkipMigrationException $e) {
  258. $this->connection->rollback();
  259. if ($dryRun == false) {
  260. // now mark it as migrated
  261. if ($direction === 'up') {
  262. $this->markMigrated();
  263. } else {
  264. $this->markNotMigrated();
  265. }
  266. }
  267. $this->outputWriter->write(sprintf("\n <info>SS</info> skipped (Reason: %s)", $e->getMessage()));
  268. $this->state = self::STATE_NONE;
  269. return array();
  270. } catch (\Exception $e) {
  271. $this->outputWriter->write(sprintf(
  272. '<error>Migration %s failed during %s. Error %s</error>',
  273. $this->version, $this->getExecutionState(), $e->getMessage()
  274. ));
  275. $this->connection->rollback();
  276. $this->state = self::STATE_NONE;
  277. throw $e;
  278. }
  279. }
  280. public function getExecutionState()
  281. {
  282. switch ($this->state) {
  283. case self::STATE_PRE:
  284. return 'Pre-Checks';
  285. case self::STATE_POST:
  286. return 'Post-Checks';
  287. case self::STATE_EXEC:
  288. return 'Execution';
  289. default:
  290. return 'No State';
  291. }
  292. }
  293. /**
  294. * Returns the time this migration version took to execute
  295. *
  296. * @return integer $time The time this migration version took to execute
  297. */
  298. public function getTime()
  299. {
  300. return $this->time;
  301. }
  302. public function __toString()
  303. {
  304. return $this->version;
  305. }
  306. }