You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConvertType.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Ostertag <bernieo.code@gmx.de>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Łukasz Buśko <busko.lukasz@pm.me>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Sander Ruitenbeek <sander@grids.be>
  15. * @author Simon Spannagel <simonspa@kth.se>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\Core\Command\Db;
  34. use Doctrine\DBAL\Exception;
  35. use Doctrine\DBAL\Schema\AbstractAsset;
  36. use Doctrine\DBAL\Schema\Table;
  37. use OCP\DB\Types;
  38. use OC\DB\Connection;
  39. use OC\DB\ConnectionFactory;
  40. use OC\DB\MigrationService;
  41. use OCP\DB\QueryBuilder\IQueryBuilder;
  42. use OCP\IConfig;
  43. use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
  44. use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
  45. use Symfony\Component\Console\Command\Command;
  46. use Symfony\Component\Console\Helper\ProgressBar;
  47. use Symfony\Component\Console\Helper\QuestionHelper;
  48. use Symfony\Component\Console\Input\InputArgument;
  49. use Symfony\Component\Console\Input\InputInterface;
  50. use Symfony\Component\Console\Input\InputOption;
  51. use Symfony\Component\Console\Output\OutputInterface;
  52. use Symfony\Component\Console\Question\ConfirmationQuestion;
  53. use Symfony\Component\Console\Question\Question;
  54. use function preg_match;
  55. use function preg_quote;
  56. class ConvertType extends Command implements CompletionAwareInterface {
  57. protected IConfig $config;
  58. protected ConnectionFactory $connectionFactory;
  59. protected array $columnTypes;
  60. public function __construct(IConfig $config, ConnectionFactory $connectionFactory) {
  61. $this->config = $config;
  62. $this->connectionFactory = $connectionFactory;
  63. parent::__construct();
  64. }
  65. protected function configure() {
  66. $this
  67. ->setName('db:convert-type')
  68. ->setDescription('Convert the Nextcloud database to the newly configured one')
  69. ->addArgument(
  70. 'type',
  71. InputArgument::REQUIRED,
  72. 'the type of the database to convert to'
  73. )
  74. ->addArgument(
  75. 'username',
  76. InputArgument::REQUIRED,
  77. 'the username of the database to convert to'
  78. )
  79. ->addArgument(
  80. 'hostname',
  81. InputArgument::REQUIRED,
  82. 'the hostname of the database to convert to'
  83. )
  84. ->addArgument(
  85. 'database',
  86. InputArgument::REQUIRED,
  87. 'the name of the database to convert to'
  88. )
  89. ->addOption(
  90. 'port',
  91. null,
  92. InputOption::VALUE_REQUIRED,
  93. 'the port of the database to convert to'
  94. )
  95. ->addOption(
  96. 'password',
  97. null,
  98. InputOption::VALUE_REQUIRED,
  99. 'the password of the database to convert to. Will be asked when not specified. Can also be passed via stdin.'
  100. )
  101. ->addOption(
  102. 'clear-schema',
  103. null,
  104. InputOption::VALUE_NONE,
  105. 'remove all tables from the destination database'
  106. )
  107. ->addOption(
  108. 'all-apps',
  109. null,
  110. InputOption::VALUE_NONE,
  111. 'whether to create schema for all apps instead of only installed apps'
  112. )
  113. ->addOption(
  114. 'chunk-size',
  115. null,
  116. InputOption::VALUE_REQUIRED,
  117. 'the maximum number of database rows to handle in a single query, bigger tables will be handled in chunks of this size. Lower this if the process runs out of memory during conversion.',
  118. '1000'
  119. )
  120. ;
  121. }
  122. protected function validateInput(InputInterface $input, OutputInterface $output) {
  123. $type = $this->connectionFactory->normalizeType($input->getArgument('type'));
  124. if ($type === 'sqlite3') {
  125. throw new \InvalidArgumentException(
  126. 'Converting to SQLite (sqlite3) is currently not supported.'
  127. );
  128. }
  129. if ($type === $this->config->getSystemValue('dbtype', '')) {
  130. throw new \InvalidArgumentException(sprintf(
  131. 'Can not convert from %1$s to %1$s.',
  132. $type
  133. ));
  134. }
  135. if ($type === 'oci' && $input->getOption('clear-schema')) {
  136. // Doctrine unconditionally tries (at least in version 2.3)
  137. // to drop sequence triggers when dropping a table, even though
  138. // such triggers may not exist. This results in errors like
  139. // "ORA-04080: trigger 'OC_STORAGES_AI_PK' does not exist".
  140. throw new \InvalidArgumentException(
  141. 'The --clear-schema option is not supported when converting to Oracle (oci).'
  142. );
  143. }
  144. }
  145. protected function readPassword(InputInterface $input, OutputInterface $output) {
  146. // Explicitly specified password
  147. if ($input->getOption('password')) {
  148. return;
  149. }
  150. // Read from stdin. stream_set_blocking is used to prevent blocking
  151. // when nothing is passed via stdin.
  152. stream_set_blocking(STDIN, 0);
  153. $password = file_get_contents('php://stdin');
  154. stream_set_blocking(STDIN, 1);
  155. if (trim($password) !== '') {
  156. $input->setOption('password', $password);
  157. return;
  158. }
  159. // Read password by interacting
  160. if ($input->isInteractive()) {
  161. /** @var QuestionHelper $helper */
  162. $helper = $this->getHelper('question');
  163. $question = new Question('What is the database password?');
  164. $question->setHidden(true);
  165. $question->setHiddenFallback(false);
  166. $password = $helper->ask($input, $output, $question);
  167. $input->setOption('password', $password);
  168. return;
  169. }
  170. }
  171. protected function execute(InputInterface $input, OutputInterface $output): int {
  172. $this->validateInput($input, $output);
  173. $this->readPassword($input, $output);
  174. /** @var Connection $fromDB */
  175. $fromDB = \OC::$server->get(Connection::class);
  176. $toDB = $this->getToDBConnection($input, $output);
  177. if ($input->getOption('clear-schema')) {
  178. $this->clearSchema($toDB, $input, $output);
  179. }
  180. $this->createSchema($fromDB, $toDB, $input, $output);
  181. $toTables = $this->getTables($toDB);
  182. $fromTables = $this->getTables($fromDB);
  183. // warn/fail if there are more tables in 'from' database
  184. $extraFromTables = array_diff($fromTables, $toTables);
  185. if (!empty($extraFromTables)) {
  186. $output->writeln('<comment>The following tables will not be converted:</comment>');
  187. $output->writeln($extraFromTables);
  188. if (!$input->getOption('all-apps')) {
  189. $output->writeln('<comment>Please note that tables belonging to available but currently not installed apps</comment>');
  190. $output->writeln('<comment>can be included by specifying the --all-apps option.</comment>');
  191. }
  192. $continueConversion = !$input->isInteractive(); // assume yes for --no-interaction and no otherwise.
  193. $question = new ConfirmationQuestion('Continue with the conversion (y/n)? [n] ', $continueConversion);
  194. /** @var QuestionHelper $helper */
  195. $helper = $this->getHelper('question');
  196. if (!$helper->ask($input, $output, $question)) {
  197. return 1;
  198. }
  199. }
  200. $intersectingTables = array_intersect($toTables, $fromTables);
  201. $this->convertDB($fromDB, $toDB, $intersectingTables, $input, $output);
  202. return 0;
  203. }
  204. protected function createSchema(Connection $fromDB, Connection $toDB, InputInterface $input, OutputInterface $output) {
  205. $output->writeln('<info>Creating schema in new database</info>');
  206. $fromMS = new MigrationService('core', $fromDB);
  207. $currentMigration = $fromMS->getMigration('current');
  208. if ($currentMigration !== '0') {
  209. $toMS = new MigrationService('core', $toDB);
  210. $toMS->migrate($currentMigration);
  211. }
  212. $apps = $input->getOption('all-apps') ? \OC_App::getAllApps() : \OC_App::getEnabledApps();
  213. foreach ($apps as $app) {
  214. $output->writeln('<info> - '.$app.'</info>');
  215. // Make sure autoloading works...
  216. \OC_App::loadApp($app);
  217. $fromMS = new MigrationService($app, $fromDB);
  218. $currentMigration = $fromMS->getMigration('current');
  219. if ($currentMigration !== '0') {
  220. $toMS = new MigrationService($app, $toDB);
  221. $toMS->migrate($currentMigration, true);
  222. }
  223. }
  224. }
  225. protected function getToDBConnection(InputInterface $input, OutputInterface $output) {
  226. $type = $input->getArgument('type');
  227. $connectionParams = $this->connectionFactory->createConnectionParams();
  228. $connectionParams = array_merge($connectionParams, [
  229. 'host' => $input->getArgument('hostname'),
  230. 'user' => $input->getArgument('username'),
  231. 'password' => $input->getOption('password'),
  232. 'dbname' => $input->getArgument('database'),
  233. ]);
  234. if ($input->getOption('port')) {
  235. $connectionParams['port'] = $input->getOption('port');
  236. }
  237. return $this->connectionFactory->getConnection($type, $connectionParams);
  238. }
  239. protected function clearSchema(Connection $db, InputInterface $input, OutputInterface $output) {
  240. $toTables = $this->getTables($db);
  241. if (!empty($toTables)) {
  242. $output->writeln('<info>Clearing schema in new database</info>');
  243. }
  244. foreach ($toTables as $table) {
  245. $db->getSchemaManager()->dropTable($table);
  246. }
  247. }
  248. protected function getTables(Connection $db) {
  249. $db->getConfiguration()->setSchemaAssetsFilter(function ($asset) {
  250. /** @var string|AbstractAsset $asset */
  251. $filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
  252. if ($asset instanceof AbstractAsset) {
  253. return preg_match($filterExpression, $asset->getName()) !== false;
  254. }
  255. return preg_match($filterExpression, $asset) !== false;
  256. });
  257. return $db->getSchemaManager()->listTableNames();
  258. }
  259. /**
  260. * @param Connection $fromDB
  261. * @param Connection $toDB
  262. * @param Table $table
  263. * @param InputInterface $input
  264. * @param OutputInterface $output
  265. */
  266. protected function copyTable(Connection $fromDB, Connection $toDB, Table $table, InputInterface $input, OutputInterface $output) {
  267. if ($table->getName() === $toDB->getPrefix() . 'migrations') {
  268. $output->writeln('<comment>Skipping migrations table because it was already filled by running the migrations</comment>');
  269. return;
  270. }
  271. $chunkSize = (int)$input->getOption('chunk-size');
  272. $query = $fromDB->getQueryBuilder();
  273. $query->automaticTablePrefix(false);
  274. $query->select($query->func()->count('*', 'num_entries'))
  275. ->from($table->getName());
  276. $result = $query->execute();
  277. $count = $result->fetchOne();
  278. $result->closeCursor();
  279. $numChunks = ceil($count / $chunkSize);
  280. if ($numChunks > 1) {
  281. $output->writeln('chunked query, ' . $numChunks . ' chunks');
  282. }
  283. $progress = new ProgressBar($output, $count);
  284. $progress->setFormat('very_verbose');
  285. $progress->start();
  286. $redraw = $count > $chunkSize ? 100 : ($count > 100 ? 5 : 1);
  287. $progress->setRedrawFrequency($redraw);
  288. $query = $fromDB->getQueryBuilder();
  289. $query->automaticTablePrefix(false);
  290. $query->select('*')
  291. ->from($table->getName())
  292. ->setMaxResults($chunkSize);
  293. try {
  294. $orderColumns = $table->getPrimaryKeyColumns();
  295. } catch (Exception $e) {
  296. $orderColumns = $table->getColumns();
  297. }
  298. foreach ($orderColumns as $column) {
  299. $query->addOrderBy($column->getName());
  300. }
  301. $insertQuery = $toDB->getQueryBuilder();
  302. $insertQuery->automaticTablePrefix(false);
  303. $insertQuery->insert($table->getName());
  304. $parametersCreated = false;
  305. for ($chunk = 0; $chunk < $numChunks; $chunk++) {
  306. $query->setFirstResult($chunk * $chunkSize);
  307. $result = $query->execute();
  308. try {
  309. $toDB->beginTransaction();
  310. while ($row = $result->fetch()) {
  311. $progress->advance();
  312. if (!$parametersCreated) {
  313. foreach ($row as $key => $value) {
  314. $insertQuery->setValue($key, $insertQuery->createParameter($key));
  315. }
  316. $parametersCreated = true;
  317. }
  318. foreach ($row as $key => $value) {
  319. $type = $this->getColumnType($table, $key);
  320. if ($type !== false) {
  321. $insertQuery->setParameter($key, $value, $type);
  322. } else {
  323. $insertQuery->setParameter($key, $value);
  324. }
  325. }
  326. $insertQuery->execute();
  327. }
  328. $result->closeCursor();
  329. $toDB->commit();
  330. } catch (\Throwable $e) {
  331. $toDB->rollBack();
  332. throw $e;
  333. }
  334. }
  335. $progress->finish();
  336. $output->writeln('');
  337. }
  338. protected function getColumnType(Table $table, $columnName) {
  339. $tableName = $table->getName();
  340. if (isset($this->columnTypes[$tableName][$columnName])) {
  341. return $this->columnTypes[$tableName][$columnName];
  342. }
  343. $type = $table->getColumn($columnName)->getType()->getName();
  344. switch ($type) {
  345. case Types::BLOB:
  346. case Types::TEXT:
  347. $this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_LOB;
  348. break;
  349. case Types::BOOLEAN:
  350. $this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_BOOL;
  351. break;
  352. default:
  353. $this->columnTypes[$tableName][$columnName] = false;
  354. }
  355. return $this->columnTypes[$tableName][$columnName];
  356. }
  357. protected function convertDB(Connection $fromDB, Connection $toDB, array $tables, InputInterface $input, OutputInterface $output) {
  358. $this->config->setSystemValue('maintenance', true);
  359. $schema = $fromDB->createSchema();
  360. try {
  361. // copy table rows
  362. foreach ($tables as $table) {
  363. $output->writeln('<info> - '.$table.'</info>');
  364. $this->copyTable($fromDB, $toDB, $schema->getTable($table), $input, $output);
  365. }
  366. if ($input->getArgument('type') === 'pgsql') {
  367. $tools = new \OC\DB\PgSqlTools($this->config);
  368. $tools->resynchronizeDatabaseSequences($toDB);
  369. }
  370. // save new database config
  371. $this->saveDBInfo($input);
  372. } catch (\Exception $e) {
  373. $this->config->setSystemValue('maintenance', false);
  374. throw $e;
  375. }
  376. $this->config->setSystemValue('maintenance', false);
  377. }
  378. protected function saveDBInfo(InputInterface $input) {
  379. $type = $input->getArgument('type');
  380. $username = $input->getArgument('username');
  381. $dbHost = $input->getArgument('hostname');
  382. $dbName = $input->getArgument('database');
  383. $password = $input->getOption('password');
  384. if ($input->getOption('port')) {
  385. $dbHost .= ':'.$input->getOption('port');
  386. }
  387. $this->config->setSystemValues([
  388. 'dbtype' => $type,
  389. 'dbname' => $dbName,
  390. 'dbhost' => $dbHost,
  391. 'dbuser' => $username,
  392. 'dbpassword' => $password,
  393. ]);
  394. }
  395. /**
  396. * Return possible values for the named option
  397. *
  398. * @param string $optionName
  399. * @param CompletionContext $context
  400. * @return string[]
  401. */
  402. public function completeOptionValues($optionName, CompletionContext $context) {
  403. return [];
  404. }
  405. /**
  406. * Return possible values for the named argument
  407. *
  408. * @param string $argumentName
  409. * @param CompletionContext $context
  410. * @return string[]
  411. */
  412. public function completeArgumentValues($argumentName, CompletionContext $context) {
  413. if ($argumentName === 'type') {
  414. return ['mysql', 'oci', 'pgsql'];
  415. }
  416. return [];
  417. }
  418. }