MigrationService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
  4. * @copyright Copyright (c) 2017, ownCloud GmbH
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  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\Platforms\OraclePlatform;
  30. use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
  31. use Doctrine\DBAL\Schema\Index;
  32. use Doctrine\DBAL\Schema\Schema;
  33. use Doctrine\DBAL\Schema\SchemaException;
  34. use Doctrine\DBAL\Schema\Sequence;
  35. use Doctrine\DBAL\Schema\Table;
  36. use Doctrine\DBAL\Types\Types;
  37. use OC\App\InfoParser;
  38. use OC\IntegrityCheck\Helpers\AppLocator;
  39. use OC\Migration\SimpleOutput;
  40. use OCP\AppFramework\App;
  41. use OCP\AppFramework\QueryException;
  42. use OCP\DB\ISchemaWrapper;
  43. use OCP\Migration\IMigrationStep;
  44. use OCP\Migration\IOutput;
  45. use OCP\Server;
  46. use Psr\Log\LoggerInterface;
  47. class MigrationService {
  48. private bool $migrationTableCreated;
  49. private array $migrations;
  50. private string $migrationsPath;
  51. private string $migrationsNamespace;
  52. private IOutput $output;
  53. private LoggerInterface $logger;
  54. private Connection $connection;
  55. private string $appName;
  56. private bool $checkOracle;
  57. /**
  58. * @throws \Exception
  59. */
  60. public function __construct(string $appName, Connection $connection, ?IOutput $output = null, ?AppLocator $appLocator = null, ?LoggerInterface $logger = null) {
  61. $this->appName = $appName;
  62. $this->connection = $connection;
  63. if ($logger === null) {
  64. $this->logger = Server::get(LoggerInterface::class);
  65. } else {
  66. $this->logger = $logger;
  67. }
  68. if ($output === null) {
  69. $this->output = new SimpleOutput($this->logger, $appName);
  70. } else {
  71. $this->output = $output;
  72. }
  73. if ($appName === 'core') {
  74. $this->migrationsPath = \OC::$SERVERROOT . '/core/Migrations';
  75. $this->migrationsNamespace = 'OC\\Core\\Migrations';
  76. $this->checkOracle = true;
  77. } else {
  78. if ($appLocator === null) {
  79. $appLocator = new AppLocator();
  80. }
  81. $appPath = $appLocator->getAppPath($appName);
  82. $namespace = App::buildAppNamespace($appName);
  83. $this->migrationsPath = "$appPath/lib/Migration";
  84. $this->migrationsNamespace = $namespace . '\\Migration';
  85. $infoParser = new InfoParser();
  86. $info = $infoParser->parse($appPath . '/appinfo/info.xml');
  87. if (!isset($info['dependencies']['database'])) {
  88. $this->checkOracle = true;
  89. } else {
  90. $this->checkOracle = false;
  91. foreach ($info['dependencies']['database'] as $database) {
  92. if (\is_string($database) && $database === 'oci') {
  93. $this->checkOracle = true;
  94. } elseif (\is_array($database) && isset($database['@value']) && $database['@value'] === 'oci') {
  95. $this->checkOracle = true;
  96. }
  97. }
  98. }
  99. }
  100. $this->migrationTableCreated = false;
  101. }
  102. /**
  103. * Returns the name of the app for which this migration is executed
  104. */
  105. public function getApp(): string {
  106. return $this->appName;
  107. }
  108. /**
  109. * @codeCoverageIgnore - this will implicitly tested on installation
  110. */
  111. private function createMigrationTable(): bool {
  112. if ($this->migrationTableCreated) {
  113. return false;
  114. }
  115. if ($this->connection->tableExists('migrations') && \OC::$server->getConfig()->getAppValue('core', 'vendor', '') !== 'owncloud') {
  116. $this->migrationTableCreated = true;
  117. return false;
  118. }
  119. $schema = new SchemaWrapper($this->connection);
  120. /**
  121. * We drop the table when it has different columns or the definition does not
  122. * match. E.g. ownCloud uses a length of 177 for app and 14 for version.
  123. */
  124. try {
  125. $table = $schema->getTable('migrations');
  126. $columns = $table->getColumns();
  127. if (count($columns) === 2) {
  128. try {
  129. $column = $table->getColumn('app');
  130. $schemaMismatch = $column->getLength() !== 255;
  131. if (!$schemaMismatch) {
  132. $column = $table->getColumn('version');
  133. $schemaMismatch = $column->getLength() !== 255;
  134. }
  135. } catch (SchemaException $e) {
  136. // One of the columns is missing
  137. $schemaMismatch = true;
  138. }
  139. if (!$schemaMismatch) {
  140. // Table exists and schema matches: return back!
  141. $this->migrationTableCreated = true;
  142. return false;
  143. }
  144. }
  145. // Drop the table, when it didn't match our expectations.
  146. $this->connection->dropTable('migrations');
  147. // Recreate the schema after the table was dropped.
  148. $schema = new SchemaWrapper($this->connection);
  149. } catch (SchemaException $e) {
  150. // Table not found, no need to panic, we will create it.
  151. }
  152. $table = $schema->createTable('migrations');
  153. $table->addColumn('app', Types::STRING, ['length' => 255]);
  154. $table->addColumn('version', Types::STRING, ['length' => 255]);
  155. $table->setPrimaryKey(['app', 'version']);
  156. $this->connection->migrateToSchema($schema->getWrappedSchema());
  157. $this->migrationTableCreated = true;
  158. return true;
  159. }
  160. /**
  161. * Returns all versions which have already been applied
  162. *
  163. * @return string[]
  164. * @codeCoverageIgnore - no need to test this
  165. */
  166. public function getMigratedVersions() {
  167. $this->createMigrationTable();
  168. $qb = $this->connection->getQueryBuilder();
  169. $qb->select('version')
  170. ->from('migrations')
  171. ->where($qb->expr()->eq('app', $qb->createNamedParameter($this->getApp())))
  172. ->orderBy('version');
  173. $result = $qb->executeQuery();
  174. $rows = $result->fetchAll(\PDO::FETCH_COLUMN);
  175. $result->closeCursor();
  176. return $rows;
  177. }
  178. /**
  179. * Returns all versions which are available in the migration folder
  180. * @return list<string>
  181. */
  182. public function getAvailableVersions(): array {
  183. $this->ensureMigrationsAreLoaded();
  184. return array_map('strval', array_keys($this->migrations));
  185. }
  186. /**
  187. * @return array<string, string>
  188. */
  189. protected function findMigrations(): array {
  190. $directory = realpath($this->migrationsPath);
  191. if ($directory === false || !file_exists($directory) || !is_dir($directory)) {
  192. return [];
  193. }
  194. $iterator = new \RegexIterator(
  195. new \RecursiveIteratorIterator(
  196. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
  197. \RecursiveIteratorIterator::LEAVES_ONLY
  198. ),
  199. '#^.+\\/Version[^\\/]{1,255}\\.php$#i',
  200. \RegexIterator::GET_MATCH);
  201. $files = array_keys(iterator_to_array($iterator));
  202. uasort($files, function ($a, $b) {
  203. preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($a), $matchA);
  204. preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($b), $matchB);
  205. if (!empty($matchA) && !empty($matchB)) {
  206. if ($matchA[1] !== $matchB[1]) {
  207. return ($matchA[1] < $matchB[1]) ? -1 : 1;
  208. }
  209. return ($matchA[2] < $matchB[2]) ? -1 : 1;
  210. }
  211. return (basename($a) < basename($b)) ? -1 : 1;
  212. });
  213. $migrations = [];
  214. foreach ($files as $file) {
  215. $className = basename($file, '.php');
  216. $version = (string) substr($className, 7);
  217. if ($version === '0') {
  218. throw new \InvalidArgumentException(
  219. "Cannot load a migrations with the name '$version' because it is a reserved number"
  220. );
  221. }
  222. $migrations[$version] = sprintf('%s\\%s', $this->migrationsNamespace, $className);
  223. }
  224. return $migrations;
  225. }
  226. /**
  227. * @param string $to
  228. * @return string[]
  229. */
  230. private function getMigrationsToExecute($to) {
  231. $knownMigrations = $this->getMigratedVersions();
  232. $availableMigrations = $this->getAvailableVersions();
  233. $toBeExecuted = [];
  234. foreach ($availableMigrations as $v) {
  235. if ($to !== 'latest' && $v > $to) {
  236. continue;
  237. }
  238. if ($this->shallBeExecuted($v, $knownMigrations)) {
  239. $toBeExecuted[] = $v;
  240. }
  241. }
  242. return $toBeExecuted;
  243. }
  244. /**
  245. * @param string $m
  246. * @param string[] $knownMigrations
  247. * @return bool
  248. */
  249. private function shallBeExecuted($m, $knownMigrations) {
  250. if (in_array($m, $knownMigrations)) {
  251. return false;
  252. }
  253. return true;
  254. }
  255. /**
  256. * @param string $version
  257. */
  258. private function markAsExecuted($version) {
  259. $this->connection->insertIfNotExist('*PREFIX*migrations', [
  260. 'app' => $this->appName,
  261. 'version' => $version
  262. ]);
  263. }
  264. /**
  265. * Returns the name of the table which holds the already applied versions
  266. *
  267. * @return string
  268. */
  269. public function getMigrationsTableName() {
  270. return $this->connection->getPrefix() . 'migrations';
  271. }
  272. /**
  273. * Returns the namespace of the version classes
  274. *
  275. * @return string
  276. */
  277. public function getMigrationsNamespace() {
  278. return $this->migrationsNamespace;
  279. }
  280. /**
  281. * Returns the directory which holds the versions
  282. *
  283. * @return string
  284. */
  285. public function getMigrationsDirectory() {
  286. return $this->migrationsPath;
  287. }
  288. /**
  289. * Return the explicit version for the aliases; current, next, prev, latest
  290. *
  291. * @return mixed|null|string
  292. */
  293. public function getMigration(string $alias) {
  294. switch ($alias) {
  295. case 'current':
  296. return $this->getCurrentVersion();
  297. case 'next':
  298. return $this->getRelativeVersion($this->getCurrentVersion(), 1);
  299. case 'prev':
  300. return $this->getRelativeVersion($this->getCurrentVersion(), -1);
  301. case 'latest':
  302. $this->ensureMigrationsAreLoaded();
  303. $migrations = $this->getAvailableVersions();
  304. return @end($migrations);
  305. }
  306. return '0';
  307. }
  308. private function getRelativeVersion(string $version, int $delta): ?string {
  309. $this->ensureMigrationsAreLoaded();
  310. $versions = $this->getAvailableVersions();
  311. array_unshift($versions, '0');
  312. /** @var int $offset */
  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. private function getCurrentVersion(): string {
  321. $m = $this->getMigratedVersions();
  322. if (count($m) === 0) {
  323. return '0';
  324. }
  325. $migrations = array_values($m);
  326. return @end($migrations);
  327. }
  328. /**
  329. * @throws \InvalidArgumentException
  330. */
  331. private function getClass(string $version): string {
  332. $this->ensureMigrationsAreLoaded();
  333. if (isset($this->migrations[$version])) {
  334. return $this->migrations[$version];
  335. }
  336. throw new \InvalidArgumentException("Version $version is unknown.");
  337. }
  338. /**
  339. * Allows to set an IOutput implementation which is used for logging progress and messages
  340. */
  341. public function setOutput(IOutput $output): void {
  342. $this->output = $output;
  343. }
  344. /**
  345. * Applies all not yet applied versions up to $to
  346. * @throws \InvalidArgumentException
  347. */
  348. public function migrate(string $to = 'latest', bool $schemaOnly = false): void {
  349. if ($schemaOnly) {
  350. $this->output->debug('Migrating schema only');
  351. $this->migrateSchemaOnly($to);
  352. return;
  353. }
  354. // read known migrations
  355. $toBeExecuted = $this->getMigrationsToExecute($to);
  356. foreach ($toBeExecuted as $version) {
  357. try {
  358. $this->executeStep($version, $schemaOnly);
  359. } catch (\Exception $e) {
  360. // The exception itself does not contain the name of the migration,
  361. // so we wrap it here, to make debugging easier.
  362. throw new \Exception('Database error when running migration ' . $version . ' for app ' . $this->getApp() . PHP_EOL. $e->getMessage(), 0, $e);
  363. }
  364. }
  365. }
  366. /**
  367. * Applies all not yet applied versions up to $to
  368. * @throws \InvalidArgumentException
  369. */
  370. public function migrateSchemaOnly(string $to = 'latest'): void {
  371. // read known migrations
  372. $toBeExecuted = $this->getMigrationsToExecute($to);
  373. if (empty($toBeExecuted)) {
  374. return;
  375. }
  376. $toSchema = null;
  377. foreach ($toBeExecuted as $version) {
  378. $this->output->debug('- Reading ' . $version);
  379. $instance = $this->createInstance($version);
  380. $toSchema = $instance->changeSchema($this->output, function () use ($toSchema): ISchemaWrapper {
  381. return $toSchema ?: new SchemaWrapper($this->connection);
  382. }, ['tablePrefix' => $this->connection->getPrefix()]) ?: $toSchema;
  383. }
  384. if ($toSchema instanceof SchemaWrapper) {
  385. $this->output->debug('- Checking target database schema');
  386. $targetSchema = $toSchema->getWrappedSchema();
  387. $this->ensureUniqueNamesConstraints($targetSchema, true);
  388. if ($this->checkOracle) {
  389. $beforeSchema = $this->connection->createSchema();
  390. $this->ensureOracleConstraints($beforeSchema, $targetSchema, strlen($this->connection->getPrefix()));
  391. }
  392. $this->output->debug('- Migrate database schema');
  393. $this->connection->migrateToSchema($targetSchema);
  394. $toSchema->performDropTableCalls();
  395. }
  396. $this->output->debug('- Mark migrations as executed');
  397. foreach ($toBeExecuted as $version) {
  398. $this->markAsExecuted($version);
  399. }
  400. }
  401. /**
  402. * Get the human readable descriptions for the migration steps to run
  403. *
  404. * @param string $to
  405. * @return string[] [$name => $description]
  406. */
  407. public function describeMigrationStep($to = 'latest') {
  408. $toBeExecuted = $this->getMigrationsToExecute($to);
  409. $description = [];
  410. foreach ($toBeExecuted as $version) {
  411. $migration = $this->createInstance($version);
  412. if ($migration->name()) {
  413. $description[$migration->name()] = $migration->description();
  414. }
  415. }
  416. return $description;
  417. }
  418. /**
  419. * @param string $version
  420. * @return IMigrationStep
  421. * @throws \InvalidArgumentException
  422. */
  423. protected function createInstance($version) {
  424. $class = $this->getClass($version);
  425. try {
  426. $s = \OCP\Server::get($class);
  427. if (!$s instanceof IMigrationStep) {
  428. throw new \InvalidArgumentException('Not a valid migration');
  429. }
  430. } catch (QueryException $e) {
  431. if (class_exists($class)) {
  432. $s = new $class();
  433. } else {
  434. throw new \InvalidArgumentException("Migration step '$class' is unknown");
  435. }
  436. }
  437. return $s;
  438. }
  439. /**
  440. * Executes one explicit version
  441. *
  442. * @param string $version
  443. * @param bool $schemaOnly
  444. * @throws \InvalidArgumentException
  445. */
  446. public function executeStep($version, $schemaOnly = false) {
  447. $instance = $this->createInstance($version);
  448. if (!$schemaOnly) {
  449. $instance->preSchemaChange($this->output, function (): ISchemaWrapper {
  450. return new SchemaWrapper($this->connection);
  451. }, ['tablePrefix' => $this->connection->getPrefix()]);
  452. }
  453. $toSchema = $instance->changeSchema($this->output, function (): ISchemaWrapper {
  454. return new SchemaWrapper($this->connection);
  455. }, ['tablePrefix' => $this->connection->getPrefix()]);
  456. if ($toSchema instanceof SchemaWrapper) {
  457. $targetSchema = $toSchema->getWrappedSchema();
  458. $this->ensureUniqueNamesConstraints($targetSchema, $schemaOnly);
  459. if ($this->checkOracle) {
  460. $sourceSchema = $this->connection->createSchema();
  461. $this->ensureOracleConstraints($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
  462. }
  463. $this->connection->migrateToSchema($targetSchema);
  464. $toSchema->performDropTableCalls();
  465. }
  466. if (!$schemaOnly) {
  467. $instance->postSchemaChange($this->output, function (): ISchemaWrapper {
  468. return new SchemaWrapper($this->connection);
  469. }, ['tablePrefix' => $this->connection->getPrefix()]);
  470. }
  471. $this->markAsExecuted($version);
  472. }
  473. /**
  474. * Naming constraints:
  475. * - Tables names must be 30 chars or shorter (27 + oc_ prefix)
  476. * - Column names must be 30 chars or shorter
  477. * - Index names must be 30 chars or shorter
  478. * - Sequence names must be 30 chars or shorter
  479. * - Primary key names must be set or the table name 23 chars or shorter
  480. *
  481. * Data constraints:
  482. * - Tables need a primary key (Not specific to Oracle, but required for performant clustering support)
  483. * - Columns with "NotNull" can not have empty string as default value
  484. * - Columns with "NotNull" can not have number 0 as default value
  485. * - Columns with type "bool" (which is in fact integer of length 1) can not be "NotNull" as it can not store 0/false
  486. * - Columns with type "string" can not be longer than 4.000 characters, use "text" instead
  487. *
  488. * @see https://github.com/nextcloud/documentation/blob/master/developer_manual/basics/storage/database.rst
  489. *
  490. * @param Schema $sourceSchema
  491. * @param Schema $targetSchema
  492. * @param int $prefixLength
  493. * @throws \Doctrine\DBAL\Exception
  494. */
  495. public function ensureOracleConstraints(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
  496. $sequences = $targetSchema->getSequences();
  497. foreach ($targetSchema->getTables() as $table) {
  498. try {
  499. $sourceTable = $sourceSchema->getTable($table->getName());
  500. } catch (SchemaException $e) {
  501. if (\strlen($table->getName()) - $prefixLength > 27) {
  502. throw new \InvalidArgumentException('Table name "' . $table->getName() . '" is too long.');
  503. }
  504. $sourceTable = null;
  505. }
  506. foreach ($table->getColumns() as $thing) {
  507. // If the table doesn't exist OR if the column doesn't exist in the table
  508. if (!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) {
  509. if (\strlen($thing->getName()) > 30) {
  510. throw new \InvalidArgumentException('Column name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  511. }
  512. if ($thing->getNotnull() && $thing->getDefault() === ''
  513. && $sourceTable instanceof Table && !$sourceTable->hasColumn($thing->getName())) {
  514. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is NotNull, but has empty string or null as default.');
  515. }
  516. if ($thing->getNotnull() && $thing->getType()->getName() === Types::BOOLEAN) {
  517. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type Bool and also NotNull, so it can not store "false".');
  518. }
  519. $sourceColumn = null;
  520. } else {
  521. $sourceColumn = $sourceTable->getColumn($thing->getName());
  522. }
  523. // If the column was just created OR the length changed OR the type changed
  524. // we will NOT detect invalid length if the column is not modified
  525. if (($sourceColumn === null || $sourceColumn->getLength() !== $thing->getLength() || $sourceColumn->getType()->getName() !== Types::STRING)
  526. && $thing->getLength() > 4000 && $thing->getType()->getName() === Types::STRING) {
  527. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type String, but exceeding the 4.000 length limit.');
  528. }
  529. }
  530. foreach ($table->getIndexes() as $thing) {
  531. if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
  532. throw new \InvalidArgumentException('Index name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  533. }
  534. }
  535. foreach ($table->getForeignKeys() as $thing) {
  536. if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
  537. throw new \InvalidArgumentException('Foreign key name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  538. }
  539. }
  540. $primaryKey = $table->getPrimaryKey();
  541. if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
  542. $indexName = strtolower($primaryKey->getName());
  543. $isUsingDefaultName = $indexName === 'primary';
  544. if ($this->connection->getDatabasePlatform() instanceof PostgreSQL94Platform) {
  545. $defaultName = $table->getName() . '_pkey';
  546. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  547. if ($isUsingDefaultName) {
  548. $sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
  549. $sequences = array_filter($sequences, function (Sequence $sequence) use ($sequenceName) {
  550. return $sequence->getName() !== $sequenceName;
  551. });
  552. }
  553. } elseif ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
  554. $defaultName = $table->getName() . '_seq';
  555. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  556. }
  557. if (!$isUsingDefaultName && \strlen($indexName) > 30) {
  558. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  559. }
  560. if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
  561. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  562. }
  563. } elseif (!$primaryKey instanceof Index && !$sourceTable instanceof Table) {
  564. /** @var LoggerInterface $logger */
  565. $logger = \OC::$server->get(LoggerInterface::class);
  566. $logger->error('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups. This will throw an exception and not be installable in a future version of Nextcloud.');
  567. // throw new \InvalidArgumentException('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups.');
  568. }
  569. }
  570. foreach ($sequences as $sequence) {
  571. if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
  572. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" is too long.');
  573. }
  574. }
  575. }
  576. /**
  577. * Ensure naming constraints
  578. *
  579. * Naming constraints:
  580. * - Index, sequence and primary key names must be unique within a Postgres Schema
  581. *
  582. * Only on installation we want to break hard, so that all developers notice
  583. * the bugs when installing the app on any database or CI, and can work on
  584. * fixing their migrations before releasing a version incompatible with Postgres.
  585. *
  586. * In case of updates we might be running on production instances and the
  587. * administrators being faced with the error would not know how to resolve it
  588. * anyway. This can also happen with instances, that had the issue before the
  589. * current update, so we don't want to make their life more complicated
  590. * than needed.
  591. *
  592. * @param Schema $targetSchema
  593. * @param bool $isInstalling
  594. */
  595. public function ensureUniqueNamesConstraints(Schema $targetSchema, bool $isInstalling): void {
  596. $constraintNames = [];
  597. $sequences = $targetSchema->getSequences();
  598. foreach ($targetSchema->getTables() as $table) {
  599. foreach ($table->getIndexes() as $thing) {
  600. $indexName = strtolower($thing->getName());
  601. if ($indexName === 'primary' || $thing->isPrimary()) {
  602. continue;
  603. }
  604. if (isset($constraintNames[$thing->getName()])) {
  605. if ($isInstalling) {
  606. throw new \InvalidArgumentException('Index name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  607. }
  608. $this->logErrorOrWarning('Index name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  609. }
  610. $constraintNames[$thing->getName()] = $table->getName();
  611. }
  612. foreach ($table->getForeignKeys() as $thing) {
  613. if (isset($constraintNames[$thing->getName()])) {
  614. if ($isInstalling) {
  615. throw new \InvalidArgumentException('Foreign key name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  616. }
  617. $this->logErrorOrWarning('Foreign key name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  618. }
  619. $constraintNames[$thing->getName()] = $table->getName();
  620. }
  621. $primaryKey = $table->getPrimaryKey();
  622. if ($primaryKey instanceof Index) {
  623. $indexName = strtolower($primaryKey->getName());
  624. if ($indexName === 'primary') {
  625. continue;
  626. }
  627. if (isset($constraintNames[$indexName])) {
  628. if ($isInstalling) {
  629. throw new \InvalidArgumentException('Primary index name "' . $indexName . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  630. }
  631. $this->logErrorOrWarning('Primary index name "' . $indexName . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  632. }
  633. $constraintNames[$indexName] = $table->getName();
  634. }
  635. }
  636. foreach ($sequences as $sequence) {
  637. if (isset($constraintNames[$sequence->getName()])) {
  638. if ($isInstalling) {
  639. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  640. }
  641. $this->logErrorOrWarning('Sequence name "' . $sequence->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  642. }
  643. $constraintNames[$sequence->getName()] = 'sequence';
  644. }
  645. }
  646. protected function logErrorOrWarning(string $log): void {
  647. if ($this->output instanceof SimpleOutput) {
  648. $this->output->warning($log);
  649. } else {
  650. $this->logger->error($log);
  651. }
  652. }
  653. private function ensureMigrationsAreLoaded() {
  654. if (empty($this->migrations)) {
  655. $this->migrations = $this->findMigrations();
  656. }
  657. }
  658. }