MigrationService.php 23 KB

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