MigrationService.php 24 KB

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