MigrationService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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->output->debug('Migrating schema only');
  344. $this->migrateSchemaOnly($to);
  345. return;
  346. }
  347. // read known migrations
  348. $toBeExecuted = $this->getMigrationsToExecute($to);
  349. foreach ($toBeExecuted as $version) {
  350. try {
  351. $this->executeStep($version, $schemaOnly);
  352. } catch (\Exception $e) {
  353. // The exception itself does not contain the name of the migration,
  354. // so we wrap it here, to make debugging easier.
  355. throw new \Exception('Database error when running migration ' . $version . ' for app ' . $this->getApp() . PHP_EOL. $e->getMessage(), 0, $e);
  356. }
  357. }
  358. }
  359. /**
  360. * Applies all not yet applied versions up to $to
  361. * @throws \InvalidArgumentException
  362. */
  363. public function migrateSchemaOnly(string $to = 'latest'): void {
  364. // read known migrations
  365. $toBeExecuted = $this->getMigrationsToExecute($to);
  366. if (empty($toBeExecuted)) {
  367. return;
  368. }
  369. $toSchema = null;
  370. foreach ($toBeExecuted as $version) {
  371. $this->output->debug('- Reading ' . $version);
  372. $instance = $this->createInstance($version);
  373. $toSchema = $instance->changeSchema($this->output, function () use ($toSchema): ISchemaWrapper {
  374. return $toSchema ?: new SchemaWrapper($this->connection);
  375. }, ['tablePrefix' => $this->connection->getPrefix()]) ?: $toSchema;
  376. }
  377. if ($toSchema instanceof SchemaWrapper) {
  378. $this->output->debug('- Checking target database schema');
  379. $targetSchema = $toSchema->getWrappedSchema();
  380. $this->ensureUniqueNamesConstraints($targetSchema);
  381. if ($this->checkOracle) {
  382. $beforeSchema = $this->connection->createSchema();
  383. $this->ensureOracleConstraints($beforeSchema, $targetSchema, strlen($this->connection->getPrefix()));
  384. }
  385. $this->output->debug('- Migrate database schema');
  386. $this->connection->migrateToSchema($targetSchema);
  387. $toSchema->performDropTableCalls();
  388. }
  389. $this->output->debug('- Mark migrations as executed');
  390. foreach ($toBeExecuted as $version) {
  391. $this->markAsExecuted($version);
  392. }
  393. }
  394. /**
  395. * Get the human readable descriptions for the migration steps to run
  396. *
  397. * @param string $to
  398. * @return string[] [$name => $description]
  399. */
  400. public function describeMigrationStep($to = 'latest') {
  401. $toBeExecuted = $this->getMigrationsToExecute($to);
  402. $description = [];
  403. foreach ($toBeExecuted as $version) {
  404. $migration = $this->createInstance($version);
  405. if ($migration->name()) {
  406. $description[$migration->name()] = $migration->description();
  407. }
  408. }
  409. return $description;
  410. }
  411. /**
  412. * @param string $version
  413. * @return IMigrationStep
  414. * @throws \InvalidArgumentException
  415. */
  416. protected function createInstance($version) {
  417. $class = $this->getClass($version);
  418. try {
  419. $s = \OCP\Server::get($class);
  420. if (!$s instanceof IMigrationStep) {
  421. throw new \InvalidArgumentException('Not a valid migration');
  422. }
  423. } catch (QueryException $e) {
  424. if (class_exists($class)) {
  425. $s = new $class();
  426. } else {
  427. throw new \InvalidArgumentException("Migration step '$class' is unknown");
  428. }
  429. }
  430. return $s;
  431. }
  432. /**
  433. * Executes one explicit version
  434. *
  435. * @param string $version
  436. * @param bool $schemaOnly
  437. * @throws \InvalidArgumentException
  438. */
  439. public function executeStep($version, $schemaOnly = false) {
  440. $instance = $this->createInstance($version);
  441. if (!$schemaOnly) {
  442. $instance->preSchemaChange($this->output, function (): ISchemaWrapper {
  443. return new SchemaWrapper($this->connection);
  444. }, ['tablePrefix' => $this->connection->getPrefix()]);
  445. }
  446. $toSchema = $instance->changeSchema($this->output, function (): ISchemaWrapper {
  447. return new SchemaWrapper($this->connection);
  448. }, ['tablePrefix' => $this->connection->getPrefix()]);
  449. if ($toSchema instanceof SchemaWrapper) {
  450. $targetSchema = $toSchema->getWrappedSchema();
  451. $this->ensureUniqueNamesConstraints($targetSchema);
  452. if ($this->checkOracle) {
  453. $sourceSchema = $this->connection->createSchema();
  454. $this->ensureOracleConstraints($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
  455. }
  456. $this->connection->migrateToSchema($targetSchema);
  457. $toSchema->performDropTableCalls();
  458. }
  459. if (!$schemaOnly) {
  460. $instance->postSchemaChange($this->output, function (): ISchemaWrapper {
  461. return new SchemaWrapper($this->connection);
  462. }, ['tablePrefix' => $this->connection->getPrefix()]);
  463. }
  464. $this->markAsExecuted($version);
  465. }
  466. /**
  467. * Naming constraints:
  468. * - Tables names must be 30 chars or shorter (27 + oc_ prefix)
  469. * - Column names must be 30 chars or shorter
  470. * - Index names must be 30 chars or shorter
  471. * - Sequence names must be 30 chars or shorter
  472. * - Primary key names must be set or the table name 23 chars or shorter
  473. *
  474. * Data constraints:
  475. * - Tables need a primary key (Not specific to Oracle, but required for performant clustering support)
  476. * - Columns with "NotNull" can not have empty string as default value
  477. * - Columns with "NotNull" can not have number 0 as default value
  478. * - Columns with type "bool" (which is in fact integer of length 1) can not be "NotNull" as it can not store 0/false
  479. * - Columns with type "string" can not be longer than 4.000 characters, use "text" instead
  480. *
  481. * @see https://github.com/nextcloud/documentation/blob/master/developer_manual/basics/storage/database.rst
  482. *
  483. * @param Schema $sourceSchema
  484. * @param Schema $targetSchema
  485. * @param int $prefixLength
  486. * @throws \Doctrine\DBAL\Exception
  487. */
  488. public function ensureOracleConstraints(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
  489. $sequences = $targetSchema->getSequences();
  490. foreach ($targetSchema->getTables() as $table) {
  491. try {
  492. $sourceTable = $sourceSchema->getTable($table->getName());
  493. } catch (SchemaException $e) {
  494. if (\strlen($table->getName()) - $prefixLength > 27) {
  495. throw new \InvalidArgumentException('Table name "' . $table->getName() . '" is too long.');
  496. }
  497. $sourceTable = null;
  498. }
  499. foreach ($table->getColumns() as $thing) {
  500. // If the table doesn't exist OR if the column doesn't exist in the table
  501. if (!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) {
  502. if (\strlen($thing->getName()) > 30) {
  503. throw new \InvalidArgumentException('Column name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  504. }
  505. if ($thing->getNotnull() && $thing->getDefault() === ''
  506. && $sourceTable instanceof Table && !$sourceTable->hasColumn($thing->getName())) {
  507. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is NotNull, but has empty string or null as default.');
  508. }
  509. if ($thing->getNotnull() && $thing->getType()->getName() === Types::BOOLEAN) {
  510. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type Bool and also NotNull, so it can not store "false".');
  511. }
  512. $sourceColumn = null;
  513. } else {
  514. $sourceColumn = $sourceTable->getColumn($thing->getName());
  515. }
  516. // If the column was just created OR the length changed OR the type changed
  517. // we will NOT detect invalid length if the column is not modified
  518. if (($sourceColumn === null || $sourceColumn->getLength() !== $thing->getLength() || $sourceColumn->getType()->getName() !== Types::STRING)
  519. && $thing->getLength() > 4000 && $thing->getType()->getName() === Types::STRING) {
  520. throw new \InvalidArgumentException('Column "' . $table->getName() . '"."' . $thing->getName() . '" is type String, but exceeding the 4.000 length limit.');
  521. }
  522. }
  523. foreach ($table->getIndexes() as $thing) {
  524. if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
  525. throw new \InvalidArgumentException('Index name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  526. }
  527. }
  528. foreach ($table->getForeignKeys() as $thing) {
  529. if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
  530. throw new \InvalidArgumentException('Foreign key name "' . $table->getName() . '"."' . $thing->getName() . '" is too long.');
  531. }
  532. }
  533. $primaryKey = $table->getPrimaryKey();
  534. if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
  535. $indexName = strtolower($primaryKey->getName());
  536. $isUsingDefaultName = $indexName === 'primary';
  537. if ($this->connection->getDatabasePlatform() instanceof PostgreSQL94Platform) {
  538. $defaultName = $table->getName() . '_pkey';
  539. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  540. if ($isUsingDefaultName) {
  541. $sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
  542. $sequences = array_filter($sequences, function (Sequence $sequence) use ($sequenceName) {
  543. return $sequence->getName() !== $sequenceName;
  544. });
  545. }
  546. } elseif ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
  547. $defaultName = $table->getName() . '_seq';
  548. $isUsingDefaultName = strtolower($defaultName) === $indexName;
  549. }
  550. if (!$isUsingDefaultName && \strlen($indexName) > 30) {
  551. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  552. }
  553. if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
  554. throw new \InvalidArgumentException('Primary index name on "' . $table->getName() . '" is too long.');
  555. }
  556. } elseif (!$primaryKey instanceof Index && !$sourceTable instanceof Table) {
  557. /** @var LoggerInterface $logger */
  558. $logger = \OC::$server->get(LoggerInterface::class);
  559. $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.');
  560. // throw new \InvalidArgumentException('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups.');
  561. }
  562. }
  563. foreach ($sequences as $sequence) {
  564. if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
  565. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" is too long.');
  566. }
  567. }
  568. }
  569. /**
  570. * Naming constraints:
  571. * - Index, sequence and primary key names must be unique within a Postgres Schema
  572. *
  573. * @param Schema $targetSchema
  574. */
  575. public function ensureUniqueNamesConstraints(Schema $targetSchema): void {
  576. $constraintNames = [];
  577. $sequences = $targetSchema->getSequences();
  578. foreach ($targetSchema->getTables() as $table) {
  579. foreach ($table->getIndexes() as $thing) {
  580. $indexName = strtolower($thing->getName());
  581. if ($indexName === 'primary' || $thing->isPrimary()) {
  582. continue;
  583. }
  584. if (isset($constraintNames[$thing->getName()])) {
  585. throw new \InvalidArgumentException('Index name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  586. }
  587. $constraintNames[$thing->getName()] = $table->getName();
  588. }
  589. foreach ($table->getForeignKeys() as $thing) {
  590. if (isset($constraintNames[$thing->getName()])) {
  591. throw new \InvalidArgumentException('Foreign key name "' . $thing->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  592. }
  593. $constraintNames[$thing->getName()] = $table->getName();
  594. }
  595. $primaryKey = $table->getPrimaryKey();
  596. if ($primaryKey instanceof Index) {
  597. $indexName = strtolower($primaryKey->getName());
  598. if ($indexName === 'primary') {
  599. continue;
  600. }
  601. if (isset($constraintNames[$indexName])) {
  602. throw new \InvalidArgumentException('Primary index name "' . $indexName . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  603. }
  604. $constraintNames[$indexName] = $table->getName();
  605. }
  606. }
  607. foreach ($sequences as $sequence) {
  608. if (isset($constraintNames[$sequence->getName()])) {
  609. throw new \InvalidArgumentException('Sequence name "' . $sequence->getName() . '" for table "' . $table->getName() . '" collides with the constraint on table "' . $constraintNames[$thing->getName()] . '".');
  610. }
  611. $constraintNames[$sequence->getName()] = 'sequence';
  612. }
  613. }
  614. private function ensureMigrationsAreLoaded() {
  615. if (empty($this->migrations)) {
  616. $this->migrations = $this->findMigrations();
  617. }
  618. }
  619. }