MigrationService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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 list<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. usort($rows, $this->sortMigrations(...));
  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. $versions = array_map('strval', array_keys($this->migrations));
  164. usort($versions, $this->sortMigrations(...));
  165. return $versions;
  166. }
  167. protected function sortMigrations(string $a, string $b): int {
  168. preg_match('/(\d+)Date(\d+)/', basename($a), $matchA);
  169. preg_match('/(\d+)Date(\d+)/', basename($b), $matchB);
  170. if (!empty($matchA) && !empty($matchB)) {
  171. $versionA = (int)$matchA[1];
  172. $versionB = (int)$matchB[1];
  173. if ($versionA !== $versionB) {
  174. return ($versionA < $versionB) ? -1 : 1;
  175. }
  176. return ($matchA[2] < $matchB[2]) ? -1 : 1;
  177. }
  178. return (basename($a) < basename($b)) ? -1 : 1;
  179. }
  180. /**
  181. * @return array<string, string>
  182. */
  183. protected function findMigrations(): array {
  184. $directory = realpath($this->migrationsPath);
  185. if ($directory === false || !file_exists($directory) || !is_dir($directory)) {
  186. return [];
  187. }
  188. $iterator = new \RegexIterator(
  189. new \RecursiveIteratorIterator(
  190. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
  191. \RecursiveIteratorIterator::LEAVES_ONLY
  192. ),
  193. '#^.+\\/Version[^\\/]{1,255}\\.php$#i',
  194. \RegexIterator::GET_MATCH);
  195. $files = array_keys(iterator_to_array($iterator));
  196. usort($files, $this->sortMigrations(...));
  197. $migrations = [];
  198. foreach ($files as $file) {
  199. $className = basename($file, '.php');
  200. $version = (string)substr($className, 7);
  201. if ($version === '0') {
  202. throw new \InvalidArgumentException(
  203. "Cannot load a migrations with the name '$version' because it is a reserved number"
  204. );
  205. }
  206. $migrations[$version] = sprintf('%s\\%s', $this->migrationsNamespace, $className);
  207. }
  208. return $migrations;
  209. }
  210. /**
  211. * @param string $to
  212. * @return string[]
  213. */
  214. private function getMigrationsToExecute($to) {
  215. $knownMigrations = $this->getMigratedVersions();
  216. $availableMigrations = $this->getAvailableVersions();
  217. $toBeExecuted = [];
  218. foreach ($availableMigrations as $v) {
  219. if ($to !== 'latest' && $v > $to) {
  220. continue;
  221. }
  222. if ($this->shallBeExecuted($v, $knownMigrations)) {
  223. $toBeExecuted[] = $v;
  224. }
  225. }
  226. return $toBeExecuted;
  227. }
  228. /**
  229. * @param string $m
  230. * @param string[] $knownMigrations
  231. * @return bool
  232. */
  233. private function shallBeExecuted($m, $knownMigrations) {
  234. if (in_array($m, $knownMigrations)) {
  235. return false;
  236. }
  237. return true;
  238. }
  239. /**
  240. * @param string $version
  241. */
  242. private function markAsExecuted($version) {
  243. $this->connection->insertIfNotExist('*PREFIX*migrations', [
  244. 'app' => $this->appName,
  245. 'version' => $version
  246. ]);
  247. }
  248. /**
  249. * Returns the name of the table which holds the already applied versions
  250. *
  251. * @return string
  252. */
  253. public function getMigrationsTableName() {
  254. return $this->connection->getPrefix() . 'migrations';
  255. }
  256. /**
  257. * Returns the namespace of the version classes
  258. *
  259. * @return string
  260. */
  261. public function getMigrationsNamespace() {
  262. return $this->migrationsNamespace;
  263. }
  264. /**
  265. * Returns the directory which holds the versions
  266. *
  267. * @return string
  268. */
  269. public function getMigrationsDirectory() {
  270. return $this->migrationsPath;
  271. }
  272. /**
  273. * Return the explicit version for the aliases; current, next, prev, latest
  274. *
  275. * @return mixed|null|string
  276. */
  277. public function getMigration(string $alias) {
  278. switch ($alias) {
  279. case 'current':
  280. return $this->getCurrentVersion();
  281. case 'next':
  282. return $this->getRelativeVersion($this->getCurrentVersion(), 1);
  283. case 'prev':
  284. return $this->getRelativeVersion($this->getCurrentVersion(), -1);
  285. case 'latest':
  286. $this->ensureMigrationsAreLoaded();
  287. $migrations = $this->getAvailableVersions();
  288. return @end($migrations);
  289. }
  290. return '0';
  291. }
  292. private function getRelativeVersion(string $version, int $delta): ?string {
  293. $this->ensureMigrationsAreLoaded();
  294. $versions = $this->getAvailableVersions();
  295. array_unshift($versions, '0');
  296. /** @var int $offset */
  297. $offset = array_search($version, $versions, true);
  298. if ($offset === false || !isset($versions[$offset + $delta])) {
  299. // Unknown version or delta out of bounds.
  300. return null;
  301. }
  302. return (string)$versions[$offset + $delta];
  303. }
  304. private function getCurrentVersion(): string {
  305. $m = $this->getMigratedVersions();
  306. if (count($m) === 0) {
  307. return '0';
  308. }
  309. $migrations = array_values($m);
  310. return @end($migrations);
  311. }
  312. /**
  313. * @throws \InvalidArgumentException
  314. */
  315. private function getClass(string $version): string {
  316. $this->ensureMigrationsAreLoaded();
  317. if (isset($this->migrations[$version])) {
  318. return $this->migrations[$version];
  319. }
  320. throw new \InvalidArgumentException("Version $version is unknown.");
  321. }
  322. /**
  323. * Allows to set an IOutput implementation which is used for logging progress and messages
  324. */
  325. public function setOutput(IOutput $output): void {
  326. $this->output = $output;
  327. }
  328. /**
  329. * Applies all not yet applied versions up to $to
  330. * @throws \InvalidArgumentException
  331. */
  332. public function migrate(string $to = 'latest', bool $schemaOnly = false): void {
  333. if ($schemaOnly) {
  334. $this->output->debug('Migrating schema only');
  335. $this->migrateSchemaOnly($to);
  336. return;
  337. }
  338. // read known migrations
  339. $toBeExecuted = $this->getMigrationsToExecute($to);
  340. foreach ($toBeExecuted as $version) {
  341. try {
  342. $this->executeStep($version, $schemaOnly);
  343. } catch (\Exception $e) {
  344. // The exception itself does not contain the name of the migration,
  345. // so we wrap it here, to make debugging easier.
  346. throw new \Exception('Database error when running migration ' . $version . ' for app ' . $this->getApp() . PHP_EOL . $e->getMessage(), 0, $e);
  347. }
  348. }
  349. }
  350. /**
  351. * Applies all not yet applied versions up to $to
  352. * @throws \InvalidArgumentException
  353. */
  354. public function migrateSchemaOnly(string $to = 'latest'): void {
  355. // read known migrations
  356. $toBeExecuted = $this->getMigrationsToExecute($to);
  357. if (empty($toBeExecuted)) {
  358. return;
  359. }
  360. $toSchema = null;
  361. foreach ($toBeExecuted as $version) {
  362. $this->output->debug('- Reading ' . $version);
  363. $instance = $this->createInstance($version);
  364. $toSchema = $instance->changeSchema($this->output, function () use ($toSchema): ISchemaWrapper {
  365. return $toSchema ?: new SchemaWrapper($this->connection);
  366. }, ['tablePrefix' => $this->connection->getPrefix()]) ?: $toSchema;
  367. }
  368. if ($toSchema instanceof SchemaWrapper) {
  369. $this->output->debug('- Checking target database schema');
  370. $targetSchema = $toSchema->getWrappedSchema();
  371. $this->ensureUniqueNamesConstraints($targetSchema, true);
  372. if ($this->checkOracle) {
  373. $beforeSchema = $this->connection->createSchema();
  374. $this->ensureOracleConstraints($beforeSchema, $targetSchema, strlen($this->connection->getPrefix()));
  375. }
  376. $this->output->debug('- Migrate database schema');
  377. $this->connection->migrateToSchema($targetSchema);
  378. $toSchema->performDropTableCalls();
  379. }
  380. $this->output->debug('- Mark migrations as executed');
  381. foreach ($toBeExecuted as $version) {
  382. $this->markAsExecuted($version);
  383. }
  384. }
  385. /**
  386. * Get the human readable descriptions for the migration steps to run
  387. *
  388. * @param string $to
  389. * @return string[] [$name => $description]
  390. */
  391. public function describeMigrationStep($to = 'latest') {
  392. $toBeExecuted = $this->getMigrationsToExecute($to);
  393. $description = [];
  394. foreach ($toBeExecuted as $version) {
  395. $migration = $this->createInstance($version);
  396. if ($migration->name()) {
  397. $description[$migration->name()] = $migration->description();
  398. }
  399. }
  400. return $description;
  401. }
  402. /**
  403. * @param string $version
  404. * @return IMigrationStep
  405. * @throws \InvalidArgumentException
  406. */
  407. public function createInstance($version) {
  408. $class = $this->getClass($version);
  409. try {
  410. $s = \OCP\Server::get($class);
  411. if (!$s instanceof IMigrationStep) {
  412. throw new \InvalidArgumentException('Not a valid migration');
  413. }
  414. } catch (QueryException $e) {
  415. if (class_exists($class)) {
  416. $s = new $class();
  417. } else {
  418. throw new \InvalidArgumentException("Migration step '$class' is unknown");
  419. }
  420. }
  421. return $s;
  422. }
  423. /**
  424. * Executes one explicit version
  425. *
  426. * @param string $version
  427. * @param bool $schemaOnly
  428. * @throws \InvalidArgumentException
  429. */
  430. public function executeStep($version, $schemaOnly = false) {
  431. $instance = $this->createInstance($version);
  432. if (!$schemaOnly) {
  433. $instance->preSchemaChange($this->output, function (): ISchemaWrapper {
  434. return new SchemaWrapper($this->connection);
  435. }, ['tablePrefix' => $this->connection->getPrefix()]);
  436. }
  437. $toSchema = $instance->changeSchema($this->output, function (): ISchemaWrapper {
  438. return new SchemaWrapper($this->connection);
  439. }, ['tablePrefix' => $this->connection->getPrefix()]);
  440. if ($toSchema instanceof SchemaWrapper) {
  441. $targetSchema = $toSchema->getWrappedSchema();
  442. $this->ensureUniqueNamesConstraints($targetSchema, $schemaOnly);
  443. if ($this->checkOracle) {
  444. $sourceSchema = $this->connection->createSchema();
  445. $this->ensureOracleConstraints($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
  446. }
  447. $this->connection->migrateToSchema($targetSchema);
  448. $toSchema->performDropTableCalls();
  449. }
  450. if (!$schemaOnly) {
  451. $instance->postSchemaChange($this->output, function (): ISchemaWrapper {
  452. return new SchemaWrapper($this->connection);
  453. }, ['tablePrefix' => $this->connection->getPrefix()]);
  454. }
  455. $this->markAsExecuted($version);
  456. }
  457. /**
  458. * Naming constraints:
  459. * - Tables names must be 30 chars or shorter (27 + oc_ prefix)
  460. * - Column names must be 30 chars or shorter
  461. * - Index names must be 30 chars or shorter
  462. * - Sequence names must be 30 chars or shorter
  463. * - Primary key names must be set or the table name 23 chars or shorter
  464. *
  465. * Data constraints:
  466. * - Tables need a primary key (Not specific to Oracle, but required for performant clustering support)
  467. * - Columns with "NotNull" can not have empty string as default value
  468. * - Columns with "NotNull" can not have number 0 as default value
  469. * - Columns with type "bool" (which is in fact integer of length 1) can not be "NotNull" as it can not store 0/false
  470. * - Columns with type "string" can not be longer than 4.000 characters, use "text" instead
  471. *
  472. * @see https://github.com/nextcloud/documentation/blob/master/developer_manual/basics/storage/database.rst
  473. *
  474. * @param Schema $sourceSchema
  475. * @param Schema $targetSchema
  476. * @param int $prefixLength
  477. * @throws \Doctrine\DBAL\Exception
  478. */
  479. public function ensureOracleConstraints(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
  480. $sequences = $targetSchema->getSequences();
  481. foreach ($targetSchema->getTables() as $table) {
  482. try {
  483. $sourceTable = $sourceSchema->getTable($table->getName());
  484. } catch (SchemaException $e) {
  485. if (\strlen($table->getName()) - $prefixLength > 27) {
  486. throw new \InvalidArgumentException('Table name "' . $table->getName() . '" is too long.');
  487. }
  488. $sourceTable = null;
  489. }
  490. foreach ($table->getColumns() as $thing) {
  491. // If the table doesn't exist OR if the column doesn't exist in the table
  492. if (!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) {
  493. if (\strlen($thing->getName()) > 30) {
  494. throw new \InvalidArgumentException('Column name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  495. }
  496. if ($thing->getNotnull() && $thing->getDefault() === ''
  497. && $sourceTable instanceof Table && !$sourceTable->hasColumn($thing->getName())) {
  498. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is NotNull, but has empty string or null as default.');
  499. }
  500. if ($thing->getNotnull() && $thing->getType()->getName() === Types::BOOLEAN) {
  501. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type Bool and also NotNull, so it can not store "false".');
  502. }
  503. $sourceColumn = null;
  504. } else {
  505. $sourceColumn = $sourceTable->getColumn($thing->getName());
  506. }
  507. // If the column was just created OR the length changed OR the type changed
  508. // we will NOT detect invalid length if the column is not modified
  509. if (($sourceColumn === null || $sourceColumn->getLength() !== $thing->getLength() || $sourceColumn->getType()->getName() !== Types::STRING)
  510. && $thing->getLength() > 4000 && $thing->getType()->getName() === Types::STRING) {
  511. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type String, but exceeding the 4.000 length limit.');
  512. }
  513. }
  514. foreach ($table->getIndexes() as $thing) {
  515. if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
  516. throw new \InvalidArgumentException('Index name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  517. }
  518. }
  519. foreach ($table->getForeignKeys() as $thing) {
  520. if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
  521. throw new \InvalidArgumentException('Foreign key name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  522. }
  523. }
  524. $primaryKey = $table->getPrimaryKey();
  525. if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
  526. $indexName = strtolower($primaryKey->getName());
  527. $isUsingDefaultName = $indexName === 'primary';
  528. if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
  529. $defaultName = $table->getName() . '_pkey';
  530. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  531. if ($isUsingDefaultName) {
  532. $sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
  533. $sequences = array_filter($sequences, function (Sequence $sequence) use ($sequenceName) {
  534. return $sequence->getName() !== $sequenceName;
  535. });
  536. }
  537. } elseif ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
  538. $defaultName = $table->getName() . '_seq';
  539. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  540. }
  541. if (!$isUsingDefaultName && \strlen($indexName) > 30) {
  542. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  543. }
  544. if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
  545. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  546. }
  547. } elseif (!$primaryKey instanceof Index && !$sourceTable instanceof Table) {
  548. /** @var LoggerInterface $logger */
  549. $logger = \OC::$server->get(LoggerInterface::class);
  550. $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.');
  551. // throw new \InvalidArgumentException('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups.');
  552. }
  553. }
  554. foreach ($sequences as $sequence) {
  555. if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
  556. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" is too long.');
  557. }
  558. }
  559. }
  560. /**
  561. * Ensure naming constraints
  562. *
  563. * Naming constraints:
  564. * - Index, sequence and primary key names must be unique within a Postgres Schema
  565. *
  566. * Only on installation we want to break hard, so that all developers notice
  567. * the bugs when installing the app on any database or CI, and can work on
  568. * fixing their migrations before releasing a version incompatible with Postgres.
  569. *
  570. * In case of updates we might be running on production instances and the
  571. * administrators being faced with the error would not know how to resolve it
  572. * anyway. This can also happen with instances, that had the issue before the
  573. * current update, so we don't want to make their life more complicated
  574. * than needed.
  575. *
  576. * @param Schema $targetSchema
  577. * @param bool $isInstalling
  578. */
  579. public function ensureUniqueNamesConstraints(Schema $targetSchema, bool $isInstalling): void {
  580. $constraintNames = [];
  581. $sequences = $targetSchema->getSequences();
  582. foreach ($targetSchema->getTables() as $table) {
  583. foreach ($table->getIndexes() as $thing) {
  584. $indexName = strtolower($thing->getName());
  585. if ($indexName === 'primary' || $thing->isPrimary()) {
  586. continue;
  587. }
  588. if (isset($constraintNames[$thing->getName()])) {
  589. if ($isInstalling) {
  590. throw new \InvalidArgumentException('Index name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  591. }
  592. $this->logErrorOrWarning('Index name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  593. }
  594. $constraintNames[$thing->getName()] = $table->getName();
  595. }
  596. foreach ($table->getForeignKeys() as $thing) {
  597. if (isset($constraintNames[$thing->getName()])) {
  598. if ($isInstalling) {
  599. throw new \InvalidArgumentException('Foreign key name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  600. }
  601. $this->logErrorOrWarning('Foreign key name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  602. }
  603. $constraintNames[$thing->getName()] = $table->getName();
  604. }
  605. $primaryKey = $table->getPrimaryKey();
  606. if ($primaryKey instanceof Index) {
  607. $indexName = strtolower($primaryKey->getName());
  608. if ($indexName === 'primary') {
  609. continue;
  610. }
  611. if (isset($constraintNames[$indexName])) {
  612. if ($isInstalling) {
  613. throw new \InvalidArgumentException('Primary index name "' . $indexName . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  614. }
  615. $this->logErrorOrWarning('Primary index name "' . $indexName . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  616. }
  617. $constraintNames[$indexName] = $table->getName();
  618. }
  619. }
  620. foreach ($sequences as $sequence) {
  621. if (isset($constraintNames[$sequence->getName()])) {
  622. if ($isInstalling) {
  623. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  624. }
  625. $this->logErrorOrWarning('Sequence name "' . $sequence->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  626. }
  627. $constraintNames[$sequence->getName()] = 'sequence';
  628. }
  629. }
  630. protected function logErrorOrWarning(string $log): void {
  631. if ($this->output instanceof SimpleOutput) {
  632. $this->output->warning($log);
  633. } else {
  634. $this->logger->error($log);
  635. }
  636. }
  637. private function ensureMigrationsAreLoaded() {
  638. if (empty($this->migrations)) {
  639. $this->migrations = $this->findMigrations();
  640. }
  641. }
  642. }