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