ConvertType.php 14 KB

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