You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Migrator.php 9.6KB

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