Migrator.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author martin-rueegg <martin.rueegg@metaworx.ch>
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Robin Appelman <robin@icewind.nl>
  8. * @author tbelau666 <thomas.belau@gmx.de>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\DB;
  29. use \Doctrine\DBAL\DBALException;
  30. use \Doctrine\DBAL\Schema\Index;
  31. use \Doctrine\DBAL\Schema\Table;
  32. use \Doctrine\DBAL\Schema\Schema;
  33. use \Doctrine\DBAL\Schema\SchemaConfig;
  34. use \Doctrine\DBAL\Schema\Comparator;
  35. use Doctrine\DBAL\Types\StringType;
  36. use Doctrine\DBAL\Types\Type;
  37. use OCP\IConfig;
  38. use OCP\Security\ISecureRandom;
  39. use Symfony\Component\EventDispatcher\EventDispatcher;
  40. use Symfony\Component\EventDispatcher\GenericEvent;
  41. class Migrator {
  42. /**
  43. * @var \Doctrine\DBAL\Connection $connection
  44. */
  45. protected $connection;
  46. /**
  47. * @var ISecureRandom
  48. */
  49. private $random;
  50. /** @var IConfig */
  51. protected $config;
  52. /** @var EventDispatcher */
  53. private $dispatcher;
  54. /** @var bool */
  55. private $noEmit = false;
  56. /**
  57. * @param \Doctrine\DBAL\Connection|Connection $connection
  58. * @param ISecureRandom $random
  59. * @param IConfig $config
  60. * @param EventDispatcher $dispatcher
  61. */
  62. public function __construct(\Doctrine\DBAL\Connection $connection,
  63. ISecureRandom $random,
  64. IConfig $config,
  65. EventDispatcher $dispatcher = null) {
  66. $this->connection = $connection;
  67. $this->random = $random;
  68. $this->config = $config;
  69. $this->dispatcher = $dispatcher;
  70. }
  71. /**
  72. * @param \Doctrine\DBAL\Schema\Schema $targetSchema
  73. */
  74. public function migrate(Schema $targetSchema) {
  75. $this->noEmit = true;
  76. $this->applySchema($targetSchema);
  77. }
  78. /**
  79. * @param \Doctrine\DBAL\Schema\Schema $targetSchema
  80. * @return string
  81. */
  82. public function generateChangeScript(Schema $targetSchema) {
  83. $schemaDiff = $this->getDiff($targetSchema, $this->connection);
  84. $script = '';
  85. $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
  86. foreach ($sqls as $sql) {
  87. $script .= $this->convertStatementToScript($sql);
  88. }
  89. return $script;
  90. }
  91. /**
  92. * @param Schema $targetSchema
  93. * @throws \OC\DB\MigrationException
  94. */
  95. public function checkMigrate(Schema $targetSchema) {
  96. $this->noEmit = true;
  97. /**@var \Doctrine\DBAL\Schema\Table[] $tables */
  98. $tables = $targetSchema->getTables();
  99. $filterExpression = $this->getFilterExpression();
  100. $this->connection->getConfiguration()->
  101. setFilterSchemaAssetsExpression($filterExpression);
  102. $existingTables = $this->connection->getSchemaManager()->listTableNames();
  103. $step = 0;
  104. foreach ($tables as $table) {
  105. if (strpos($table->getName(), '.')) {
  106. list(, $tableName) = explode('.', $table->getName());
  107. } else {
  108. $tableName = $table->getName();
  109. }
  110. $this->emitCheckStep($tableName, $step++, count($tables));
  111. // don't need to check for new tables
  112. if (array_search($tableName, $existingTables) !== false) {
  113. $this->checkTableMigrate($table);
  114. }
  115. }
  116. }
  117. /**
  118. * Create a unique name for the temporary table
  119. *
  120. * @param string $name
  121. * @return string
  122. */
  123. protected function generateTemporaryTableName($name) {
  124. return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  125. }
  126. /**
  127. * Check the migration of a table on a copy so we can detect errors before messing with the real table
  128. *
  129. * @param \Doctrine\DBAL\Schema\Table $table
  130. * @throws \OC\DB\MigrationException
  131. */
  132. protected function checkTableMigrate(Table $table) {
  133. $name = $table->getName();
  134. $tmpName = $this->generateTemporaryTableName($name);
  135. $this->copyTable($name, $tmpName);
  136. //create the migration schema for the temporary table
  137. $tmpTable = $this->renameTableSchema($table, $tmpName);
  138. $schemaConfig = new SchemaConfig();
  139. $schemaConfig->setName($this->connection->getDatabase());
  140. $schema = new Schema(array($tmpTable), array(), $schemaConfig);
  141. try {
  142. $this->applySchema($schema);
  143. $this->dropTable($tmpName);
  144. } catch (DBALException $e) {
  145. // pgsql needs to commit it's failed transaction before doing anything else
  146. if ($this->connection->isTransactionActive()) {
  147. $this->connection->commit();
  148. }
  149. $this->dropTable($tmpName);
  150. throw new MigrationException($table->getName(), $e->getMessage());
  151. }
  152. }
  153. /**
  154. * @param \Doctrine\DBAL\Schema\Table $table
  155. * @param string $newName
  156. * @return \Doctrine\DBAL\Schema\Table
  157. */
  158. protected function renameTableSchema(Table $table, $newName) {
  159. /**
  160. * @var \Doctrine\DBAL\Schema\Index[] $indexes
  161. */
  162. $indexes = $table->getIndexes();
  163. $newIndexes = array();
  164. foreach ($indexes as $index) {
  165. if ($index->isPrimary()) {
  166. // do not rename primary key
  167. $indexName = $index->getName();
  168. } else {
  169. // avoid conflicts in index names
  170. $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
  171. }
  172. $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
  173. }
  174. // foreign keys are not supported so we just set it to an empty array
  175. return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
  176. }
  177. /**
  178. * @param Schema $targetSchema
  179. * @param \Doctrine\DBAL\Connection $connection
  180. * @return \Doctrine\DBAL\Schema\SchemaDiff
  181. * @throws DBALException
  182. */
  183. protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
  184. // adjust varchar columns with a length higher then getVarcharMaxLength to clob
  185. foreach ($targetSchema->getTables() as $table) {
  186. foreach ($table->getColumns() as $column) {
  187. if ($column->getType() instanceof StringType) {
  188. if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
  189. $column->setType(Type::getType('text'));
  190. $column->setLength(null);
  191. }
  192. }
  193. }
  194. }
  195. $filterExpression = $this->getFilterExpression();
  196. $this->connection->getConfiguration()->
  197. setFilterSchemaAssetsExpression($filterExpression);
  198. $sourceSchema = $connection->getSchemaManager()->createSchema();
  199. // remove tables we don't know about
  200. /** @var $table \Doctrine\DBAL\Schema\Table */
  201. foreach ($sourceSchema->getTables() as $table) {
  202. if (!$targetSchema->hasTable($table->getName())) {
  203. $sourceSchema->dropTable($table->getName());
  204. }
  205. }
  206. // remove sequences we don't know about
  207. foreach ($sourceSchema->getSequences() as $table) {
  208. if (!$targetSchema->hasSequence($table->getName())) {
  209. $sourceSchema->dropSequence($table->getName());
  210. }
  211. }
  212. $comparator = new Comparator();
  213. return $comparator->compare($sourceSchema, $targetSchema);
  214. }
  215. /**
  216. * @param \Doctrine\DBAL\Schema\Schema $targetSchema
  217. * @param \Doctrine\DBAL\Connection $connection
  218. */
  219. protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
  220. if (is_null($connection)) {
  221. $connection = $this->connection;
  222. }
  223. $schemaDiff = $this->getDiff($targetSchema, $connection);
  224. $connection->beginTransaction();
  225. $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
  226. $step = 0;
  227. foreach ($sqls as $sql) {
  228. $this->emit($sql, $step++, count($sqls));
  229. $connection->query($sql);
  230. }
  231. $connection->commit();
  232. }
  233. /**
  234. * @param string $sourceName
  235. * @param string $targetName
  236. */
  237. protected function copyTable($sourceName, $targetName) {
  238. $quotedSource = $this->connection->quoteIdentifier($sourceName);
  239. $quotedTarget = $this->connection->quoteIdentifier($targetName);
  240. $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
  241. $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
  242. }
  243. /**
  244. * @param string $name
  245. */
  246. protected function dropTable($name) {
  247. $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
  248. }
  249. /**
  250. * @param $statement
  251. * @return string
  252. */
  253. protected function convertStatementToScript($statement) {
  254. $script = $statement . ';';
  255. $script .= PHP_EOL;
  256. $script .= PHP_EOL;
  257. return $script;
  258. }
  259. protected function getFilterExpression() {
  260. return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
  261. }
  262. protected function emit($sql, $step, $max) {
  263. if ($this->noEmit) {
  264. return;
  265. }
  266. if(is_null($this->dispatcher)) {
  267. return;
  268. }
  269. $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
  270. }
  271. private function emitCheckStep($tableName, $step, $max) {
  272. if(is_null($this->dispatcher)) {
  273. return;
  274. }
  275. $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
  276. }
  277. }