Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Migrator.php 9.6KB

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