MigrationService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
  4. * @copyright Copyright (c) 2017, ownCloud GmbH
  5. *
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\DB;
  27. use Doctrine\DBAL\Platforms\OraclePlatform;
  28. use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
  29. use Doctrine\DBAL\Schema\Index;
  30. use Doctrine\DBAL\Schema\Schema;
  31. use Doctrine\DBAL\Schema\SchemaException;
  32. use Doctrine\DBAL\Schema\Sequence;
  33. use Doctrine\DBAL\Schema\Table;
  34. use Doctrine\DBAL\Types\Type;
  35. use OC\App\InfoParser;
  36. use OC\IntegrityCheck\Helpers\AppLocator;
  37. use OC\Migration\SimpleOutput;
  38. use OCP\AppFramework\App;
  39. use OCP\AppFramework\QueryException;
  40. use OCP\IDBConnection;
  41. use OCP\Migration\IMigrationStep;
  42. use OCP\Migration\IOutput;
  43. class MigrationService {
  44. /** @var boolean */
  45. private $migrationTableCreated;
  46. /** @var array */
  47. private $migrations;
  48. /** @var IOutput */
  49. private $output;
  50. /** @var Connection */
  51. private $connection;
  52. /** @var string */
  53. private $appName;
  54. /** @var bool */
  55. private $checkOracle;
  56. /**
  57. * MigrationService constructor.
  58. *
  59. * @param $appName
  60. * @param IDBConnection $connection
  61. * @param AppLocator $appLocator
  62. * @param IOutput|null $output
  63. * @throws \Exception
  64. */
  65. public function __construct($appName, IDBConnection $connection, IOutput $output = null, AppLocator $appLocator = null) {
  66. $this->appName = $appName;
  67. $this->connection = $connection;
  68. $this->output = $output;
  69. if (null === $this->output) {
  70. $this->output = new SimpleOutput(\OC::$server->getLogger(), $appName);
  71. }
  72. if ($appName === 'core') {
  73. $this->migrationsPath = \OC::$SERVERROOT . '/core/Migrations';
  74. $this->migrationsNamespace = 'OC\\Core\\Migrations';
  75. $this->checkOracle = true;
  76. } else {
  77. if (null === $appLocator) {
  78. $appLocator = new AppLocator();
  79. }
  80. $appPath = $appLocator->getAppPath($appName);
  81. $namespace = App::buildAppNamespace($appName);
  82. $this->migrationsPath = "$appPath/lib/Migration";
  83. $this->migrationsNamespace = $namespace . '\\Migration';
  84. $infoParser = new InfoParser();
  85. $info = $infoParser->parse($appPath . '/appinfo/info.xml');
  86. if (!isset($info['dependencies']['database'])) {
  87. $this->checkOracle = true;
  88. } else {
  89. $this->checkOracle = false;
  90. foreach ($info['dependencies']['database'] as $database) {
  91. if (\is_string($database) && $database === 'oci') {
  92. $this->checkOracle = true;
  93. } else if (\is_array($database) && isset($database['@value']) && $database['@value'] === 'oci') {
  94. $this->checkOracle = true;
  95. }
  96. }
  97. }
  98. }
  99. }
  100. /**
  101. * Returns the name of the app for which this migration is executed
  102. *
  103. * @return string
  104. */
  105. public function getApp() {
  106. return $this->appName;
  107. }
  108. /**
  109. * @return bool
  110. * @codeCoverageIgnore - this will implicitly tested on installation
  111. */
  112. private function createMigrationTable() {
  113. if ($this->migrationTableCreated) {
  114. return false;
  115. }
  116. $schema = new SchemaWrapper($this->connection);
  117. /**
  118. * We drop the table when it has different columns or the definition does not
  119. * match. E.g. ownCloud uses a length of 177 for app and 14 for version.
  120. */
  121. try {
  122. $table = $schema->getTable('migrations');
  123. $columns = $table->getColumns();
  124. if (count($columns) === 2) {
  125. try {
  126. $column = $table->getColumn('app');
  127. $schemaMismatch = $column->getLength() !== 255;
  128. if (!$schemaMismatch) {
  129. $column = $table->getColumn('version');
  130. $schemaMismatch = $column->getLength() !== 255;
  131. }
  132. } catch (SchemaException $e) {
  133. // One of the columns is missing
  134. $schemaMismatch = true;
  135. }
  136. if (!$schemaMismatch) {
  137. // Table exists and schema matches: return back!
  138. $this->migrationTableCreated = true;
  139. return false;
  140. }
  141. }
  142. // Drop the table, when it didn't match our expectations.
  143. $this->connection->dropTable('migrations');
  144. // Recreate the schema after the table was dropped.
  145. $schema = new SchemaWrapper($this->connection);
  146. } catch (SchemaException $e) {
  147. // Table not found, no need to panic, we will create it.
  148. }
  149. $table = $schema->createTable('migrations');
  150. $table->addColumn('app', Type::STRING, ['length' => 255]);
  151. $table->addColumn('version', Type::STRING, ['length' => 255]);
  152. $table->setPrimaryKey(['app', 'version']);
  153. $this->connection->migrateToSchema($schema->getWrappedSchema());
  154. $this->migrationTableCreated = true;
  155. return true;
  156. }
  157. /**
  158. * Returns all versions which have already been applied
  159. *
  160. * @return string[]
  161. * @codeCoverageIgnore - no need to test this
  162. */
  163. public function getMigratedVersions() {
  164. $this->createMigrationTable();
  165. $qb = $this->connection->getQueryBuilder();
  166. $qb->select('version')
  167. ->from('migrations')
  168. ->where($qb->expr()->eq('app', $qb->createNamedParameter($this->getApp())))
  169. ->orderBy('version');
  170. $result = $qb->execute();
  171. $rows = $result->fetchAll(\PDO::FETCH_COLUMN);
  172. $result->closeCursor();
  173. return $rows;
  174. }
  175. /**
  176. * Returns all versions which are available in the migration folder
  177. *
  178. * @return array
  179. */
  180. public function getAvailableVersions() {
  181. $this->ensureMigrationsAreLoaded();
  182. return array_map('strval', array_keys($this->migrations));
  183. }
  184. protected function findMigrations() {
  185. $directory = realpath($this->migrationsPath);
  186. if ($directory === false || !file_exists($directory) || !is_dir($directory)) {
  187. return [];
  188. }
  189. $iterator = new \RegexIterator(
  190. new \RecursiveIteratorIterator(
  191. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
  192. \RecursiveIteratorIterator::LEAVES_ONLY
  193. ),
  194. '#^.+\\/Version[^\\/]{1,255}\\.php$#i',
  195. \RegexIterator::GET_MATCH);
  196. $files = array_keys(iterator_to_array($iterator));
  197. uasort($files, function ($a, $b) {
  198. preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($a), $matchA);
  199. preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($b), $matchB);
  200. if (!empty($matchA) && !empty($matchB)) {
  201. if ($matchA[1] !== $matchB[1]) {
  202. return ($matchA[1] < $matchB[1]) ? -1 : 1;
  203. }
  204. return ($matchA[2] < $matchB[2]) ? -1 : 1;
  205. }
  206. return (basename($a) < basename($b)) ? -1 : 1;
  207. });
  208. $migrations = [];
  209. foreach ($files as $file) {
  210. $className = basename($file, '.php');
  211. $version = (string) substr($className, 7);
  212. if ($version === '0') {
  213. throw new \InvalidArgumentException(
  214. "Cannot load a migrations with the name '$version' because it is a reserved number"
  215. );
  216. }
  217. $migrations[$version] = sprintf('%s\\%s', $this->migrationsNamespace, $className);
  218. }
  219. return $migrations;
  220. }
  221. /**
  222. * @param string $to
  223. * @return string[]
  224. */
  225. private function getMigrationsToExecute($to) {
  226. $knownMigrations = $this->getMigratedVersions();
  227. $availableMigrations = $this->getAvailableVersions();
  228. $toBeExecuted = [];
  229. foreach ($availableMigrations as $v) {
  230. if ($to !== 'latest' && $v > $to) {
  231. continue;
  232. }
  233. if ($this->shallBeExecuted($v, $knownMigrations)) {
  234. $toBeExecuted[] = $v;
  235. }
  236. }
  237. return $toBeExecuted;
  238. }
  239. /**
  240. * @param string $m
  241. * @param string[] $knownMigrations
  242. * @return bool
  243. */
  244. private function shallBeExecuted($m, $knownMigrations) {
  245. if (in_array($m, $knownMigrations)) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. /**
  251. * @param string $version
  252. */
  253. private function markAsExecuted($version) {
  254. $this->connection->insertIfNotExist('*PREFIX*migrations', [
  255. 'app' => $this->appName,
  256. 'version' => $version
  257. ]);
  258. }
  259. /**
  260. * Returns the name of the table which holds the already applied versions
  261. *
  262. * @return string
  263. */
  264. public function getMigrationsTableName() {
  265. return $this->connection->getPrefix() . 'migrations';
  266. }
  267. /**
  268. * Returns the namespace of the version classes
  269. *
  270. * @return string
  271. */
  272. public function getMigrationsNamespace() {
  273. return $this->migrationsNamespace;
  274. }
  275. /**
  276. * Returns the directory which holds the versions
  277. *
  278. * @return string
  279. */
  280. public function getMigrationsDirectory() {
  281. return $this->migrationsPath;
  282. }
  283. /**
  284. * Return the explicit version for the aliases; current, next, prev, latest
  285. *
  286. * @param string $alias
  287. * @return mixed|null|string
  288. */
  289. public function getMigration($alias) {
  290. switch($alias) {
  291. case 'current':
  292. return $this->getCurrentVersion();
  293. case 'next':
  294. return $this->getRelativeVersion($this->getCurrentVersion(), 1);
  295. case 'prev':
  296. return $this->getRelativeVersion($this->getCurrentVersion(), -1);
  297. case 'latest':
  298. $this->ensureMigrationsAreLoaded();
  299. $migrations = $this->getAvailableVersions();
  300. return @end($migrations);
  301. }
  302. return '0';
  303. }
  304. /**
  305. * @param string $version
  306. * @param int $delta
  307. * @return null|string
  308. */
  309. private function getRelativeVersion($version, $delta) {
  310. $this->ensureMigrationsAreLoaded();
  311. $versions = $this->getAvailableVersions();
  312. array_unshift($versions, 0);
  313. $offset = array_search($version, $versions, true);
  314. if ($offset === false || !isset($versions[$offset + $delta])) {
  315. // Unknown version or delta out of bounds.
  316. return null;
  317. }
  318. return (string) $versions[$offset + $delta];
  319. }
  320. /**
  321. * @return string
  322. */
  323. private function getCurrentVersion() {
  324. $m = $this->getMigratedVersions();
  325. if (count($m) === 0) {
  326. return '0';
  327. }
  328. $migrations = array_values($m);
  329. return @end($migrations);
  330. }
  331. /**
  332. * @param string $version
  333. * @return string
  334. * @throws \InvalidArgumentException
  335. */
  336. private function getClass($version) {
  337. $this->ensureMigrationsAreLoaded();
  338. if (isset($this->migrations[$version])) {
  339. return $this->migrations[$version];
  340. }
  341. throw new \InvalidArgumentException("Version $version is unknown.");
  342. }
  343. /**
  344. * Allows to set an IOutput implementation which is used for logging progress and messages
  345. *
  346. * @param IOutput $output
  347. */
  348. public function setOutput(IOutput $output) {
  349. $this->output = $output;
  350. }
  351. /**
  352. * Applies all not yet applied versions up to $to
  353. *
  354. * @param string $to
  355. * @param bool $schemaOnly
  356. * @throws \InvalidArgumentException
  357. */
  358. public function migrate($to = 'latest', $schemaOnly = false) {
  359. // read known migrations
  360. $toBeExecuted = $this->getMigrationsToExecute($to);
  361. foreach ($toBeExecuted as $version) {
  362. $this->executeStep($version, $schemaOnly);
  363. }
  364. }
  365. /**
  366. * Get the human readable descriptions for the migration steps to run
  367. *
  368. * @param string $to
  369. * @return string[] [$name => $description]
  370. */
  371. public function describeMigrationStep($to = 'latest') {
  372. $toBeExecuted = $this->getMigrationsToExecute($to);
  373. $description = [];
  374. foreach ($toBeExecuted as $version) {
  375. $migration = $this->createInstance($version);
  376. if ($migration->name()) {
  377. $description[$migration->name()] = $migration->description();
  378. }
  379. }
  380. return $description;
  381. }
  382. /**
  383. * @param string $version
  384. * @return IMigrationStep
  385. * @throws \InvalidArgumentException
  386. */
  387. protected function createInstance($version) {
  388. $class = $this->getClass($version);
  389. try {
  390. $s = \OC::$server->query($class);
  391. if (!$s instanceof IMigrationStep) {
  392. throw new \InvalidArgumentException('Not a valid migration');
  393. }
  394. } catch (QueryException $e) {
  395. if (class_exists($class)) {
  396. $s = new $class();
  397. } else {
  398. throw new \InvalidArgumentException("Migration step '$class' is unknown");
  399. }
  400. }
  401. return $s;
  402. }
  403. /**
  404. * Executes one explicit version
  405. *
  406. * @param string $version
  407. * @param bool $schemaOnly
  408. * @throws \InvalidArgumentException
  409. */
  410. public function executeStep($version, $schemaOnly = false) {
  411. $instance = $this->createInstance($version);
  412. if (!$schemaOnly) {
  413. $instance->preSchemaChange($this->output, function() {
  414. return new SchemaWrapper($this->connection);
  415. }, ['tablePrefix' => $this->connection->getPrefix()]);
  416. }
  417. $toSchema = $instance->changeSchema($this->output, function() {
  418. return new SchemaWrapper($this->connection);
  419. }, ['tablePrefix' => $this->connection->getPrefix()]);
  420. if ($toSchema instanceof SchemaWrapper) {
  421. $targetSchema = $toSchema->getWrappedSchema();
  422. if ($this->checkOracle) {
  423. $sourceSchema = $this->connection->createSchema();
  424. $this->ensureOracleIdentifierLengthLimit($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
  425. }
  426. $this->connection->migrateToSchema($targetSchema);
  427. $toSchema->performDropTableCalls();
  428. }
  429. if (!$schemaOnly) {
  430. $instance->postSchemaChange($this->output, function() {
  431. return new SchemaWrapper($this->connection);
  432. }, ['tablePrefix' => $this->connection->getPrefix()]);
  433. }
  434. $this->markAsExecuted($version);
  435. }
  436. public function ensureOracleIdentifierLengthLimit(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
  437. $sequences = $targetSchema->getSequences();
  438. foreach ($targetSchema->getTables() as $table) {
  439. try {
  440. $sourceTable = $sourceSchema->getTable($table->getName());
  441. } catch (SchemaException $e) {
  442. if (\strlen($table->getName()) - $prefixLength > 27) {
  443. throw new \InvalidArgumentException('Table name "' . $table->getName() . '" is too long.');
  444. }
  445. $sourceTable = null;
  446. }
  447. foreach ($table->getColumns() as $thing) {
  448. if ((!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) && \strlen($thing->getName()) > 30) {
  449. throw new \InvalidArgumentException('Column name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  450. }
  451. }
  452. foreach ($table->getIndexes() as $thing) {
  453. if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
  454. throw new \InvalidArgumentException('Index name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  455. }
  456. }
  457. foreach ($table->getForeignKeys() as $thing) {
  458. if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
  459. throw new \InvalidArgumentException('Foreign key name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  460. }
  461. }
  462. $primaryKey = $table->getPrimaryKey();
  463. if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
  464. $indexName = strtolower($primaryKey->getName());
  465. $isUsingDefaultName = $indexName === 'primary';
  466. if ($this->connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
  467. $defaultName = $table->getName() . '_pkey';
  468. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  469. if ($isUsingDefaultName) {
  470. $sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
  471. $sequences = array_filter($sequences, function(Sequence $sequence) use ($sequenceName) {
  472. return $sequence->getName() !== $sequenceName;
  473. });
  474. }
  475. } else if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
  476. $defaultName = $table->getName() . '_seq';
  477. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  478. }
  479. if (!$isUsingDefaultName && \strlen($indexName) > 30) {
  480. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  481. }
  482. if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
  483. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  484. }
  485. }
  486. }
  487. foreach ($sequences as $sequence) {
  488. if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
  489. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" is too long.');
  490. }
  491. }
  492. }
  493. private function ensureMigrationsAreLoaded() {
  494. if (empty($this->migrations)) {
  495. $this->migrations = $this->findMigrations();
  496. }
  497. }
  498. }