1
0

MigrationService.php 23 KB

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