MigrationService.php 24 KB

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