Connection.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Ole Ostergaard <ole.c.ostergaard@gmail.com>
  12. * @author Ole Ostergaard <ole.ostergaard@knime.com>
  13. * @author Philipp Schaffrath <github@philipp.schaffrath.email>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\DB;
  35. use Doctrine\Common\EventManager;
  36. use Doctrine\DBAL\Cache\QueryCacheProfile;
  37. use Doctrine\DBAL\Configuration;
  38. use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
  39. use Doctrine\DBAL\Driver;
  40. use Doctrine\DBAL\Exception;
  41. use Doctrine\DBAL\Exception\ConnectionLost;
  42. use Doctrine\DBAL\Platforms\MySQLPlatform;
  43. use Doctrine\DBAL\Platforms\OraclePlatform;
  44. use Doctrine\DBAL\Platforms\SqlitePlatform;
  45. use Doctrine\DBAL\Result;
  46. use Doctrine\DBAL\Schema\Schema;
  47. use Doctrine\DBAL\Statement;
  48. use OC\DB\QueryBuilder\QueryBuilder;
  49. use OC\SystemConfig;
  50. use OCP\DB\QueryBuilder\IQueryBuilder;
  51. use OCP\Diagnostics\IEventLogger;
  52. use OCP\IRequestId;
  53. use OCP\PreConditionNotMetException;
  54. use OCP\Profiler\IProfiler;
  55. use Psr\Clock\ClockInterface;
  56. use Psr\Log\LoggerInterface;
  57. use function in_array;
  58. class Connection extends PrimaryReadReplicaConnection {
  59. /** @var string */
  60. protected $tablePrefix;
  61. /** @var \OC\DB\Adapter $adapter */
  62. protected $adapter;
  63. /** @var SystemConfig */
  64. private $systemConfig;
  65. private ClockInterface $clock;
  66. private LoggerInterface $logger;
  67. protected $lockedTable = null;
  68. /** @var int */
  69. protected $queriesBuilt = 0;
  70. /** @var int */
  71. protected $queriesExecuted = 0;
  72. /** @var DbDataCollector|null */
  73. protected $dbDataCollector = null;
  74. private array $lastConnectionCheck = [];
  75. protected ?float $transactionActiveSince = null;
  76. /** @var array<string, int> */
  77. protected $tableDirtyWrites = [];
  78. /**
  79. * Initializes a new instance of the Connection class.
  80. *
  81. * @throws \Exception
  82. */
  83. public function __construct(
  84. array $params,
  85. Driver $driver,
  86. ?Configuration $config = null,
  87. ?EventManager $eventManager = null
  88. ) {
  89. if (!isset($params['adapter'])) {
  90. throw new \Exception('adapter not set');
  91. }
  92. if (!isset($params['tablePrefix'])) {
  93. throw new \Exception('tablePrefix not set');
  94. }
  95. /**
  96. * @psalm-suppress InternalMethod
  97. */
  98. parent::__construct($params, $driver, $config, $eventManager);
  99. $this->adapter = new $params['adapter']($this);
  100. $this->tablePrefix = $params['tablePrefix'];
  101. $this->systemConfig = \OC::$server->getSystemConfig();
  102. $this->clock = \OCP\Server::get(ClockInterface::class);
  103. $this->logger = \OC::$server->get(LoggerInterface::class);
  104. /** @var \OCP\Profiler\IProfiler */
  105. $profiler = \OC::$server->get(IProfiler::class);
  106. if ($profiler->isEnabled()) {
  107. $this->dbDataCollector = new DbDataCollector($this);
  108. $profiler->add($this->dbDataCollector);
  109. $debugStack = new BacktraceDebugStack();
  110. $this->dbDataCollector->setDebugStack($debugStack);
  111. $this->_config->setSQLLogger($debugStack);
  112. }
  113. }
  114. /**
  115. * @throws Exception
  116. */
  117. public function connect($connectionName = null) {
  118. try {
  119. if ($this->_conn) {
  120. $this->reconnectIfNeeded();
  121. /** @psalm-suppress InternalMethod */
  122. return parent::connect();
  123. }
  124. $this->lastConnectionCheck[$this->getConnectionName()] = time();
  125. // Only trigger the event logger for the initial connect call
  126. $eventLogger = \OC::$server->get(IEventLogger::class);
  127. $eventLogger->start('connect:db', 'db connection opened');
  128. /** @psalm-suppress InternalMethod */
  129. $status = parent::connect();
  130. $eventLogger->end('connect:db');
  131. return $status;
  132. } catch (Exception $e) {
  133. // throw a new exception to prevent leaking info from the stacktrace
  134. throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
  135. }
  136. }
  137. public function getStats(): array {
  138. return [
  139. 'built' => $this->queriesBuilt,
  140. 'executed' => $this->queriesExecuted,
  141. ];
  142. }
  143. /**
  144. * Returns a QueryBuilder for the connection.
  145. */
  146. public function getQueryBuilder(): IQueryBuilder {
  147. $this->queriesBuilt++;
  148. return new QueryBuilder(
  149. new ConnectionAdapter($this),
  150. $this->systemConfig,
  151. $this->logger
  152. );
  153. }
  154. /**
  155. * Gets the QueryBuilder for the connection.
  156. *
  157. * @return \Doctrine\DBAL\Query\QueryBuilder
  158. * @deprecated please use $this->getQueryBuilder() instead
  159. */
  160. public function createQueryBuilder() {
  161. $backtrace = $this->getCallerBacktrace();
  162. $this->logger->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  163. $this->queriesBuilt++;
  164. return parent::createQueryBuilder();
  165. }
  166. /**
  167. * Gets the ExpressionBuilder for the connection.
  168. *
  169. * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
  170. * @deprecated please use $this->getQueryBuilder()->expr() instead
  171. */
  172. public function getExpressionBuilder() {
  173. $backtrace = $this->getCallerBacktrace();
  174. $this->logger->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  175. $this->queriesBuilt++;
  176. return parent::getExpressionBuilder();
  177. }
  178. /**
  179. * Get the file and line that called the method where `getCallerBacktrace()` was used
  180. *
  181. * @return string
  182. */
  183. protected function getCallerBacktrace() {
  184. $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  185. // 0 is the method where we use `getCallerBacktrace`
  186. // 1 is the target method which uses the method we want to log
  187. if (isset($traces[1])) {
  188. return $traces[1]['file'] . ':' . $traces[1]['line'];
  189. }
  190. return '';
  191. }
  192. /**
  193. * @return string
  194. */
  195. public function getPrefix() {
  196. return $this->tablePrefix;
  197. }
  198. /**
  199. * Prepares an SQL statement.
  200. *
  201. * @param string $statement The SQL statement to prepare.
  202. * @param int|null $limit
  203. * @param int|null $offset
  204. *
  205. * @return Statement The prepared statement.
  206. * @throws Exception
  207. */
  208. public function prepare($sql, $limit = null, $offset = null): Statement {
  209. if ($limit === -1 || $limit === null) {
  210. $limit = null;
  211. } else {
  212. $limit = (int) $limit;
  213. }
  214. if ($offset !== null) {
  215. $offset = (int) $offset;
  216. }
  217. if (!is_null($limit)) {
  218. $platform = $this->getDatabasePlatform();
  219. $sql = $platform->modifyLimitQuery($sql, $limit, $offset);
  220. }
  221. $statement = $this->replaceTablePrefix($sql);
  222. $statement = $this->adapter->fixupStatement($statement);
  223. return parent::prepare($statement);
  224. }
  225. /**
  226. * Executes an, optionally parametrized, SQL query.
  227. *
  228. * If the query is parametrized, a prepared statement is used.
  229. * If an SQLLogger is configured, the execution is logged.
  230. *
  231. * @param string $sql The SQL query to execute.
  232. * @param array $params The parameters to bind to the query, if any.
  233. * @param array $types The types the previous parameters are in.
  234. * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
  235. *
  236. * @return Result The executed statement.
  237. *
  238. * @throws \Doctrine\DBAL\Exception
  239. */
  240. public function executeQuery(string $sql, array $params = [], $types = [], ?QueryCacheProfile $qcp = null): Result {
  241. $tables = $this->getQueriedTables($sql);
  242. $now = $this->clock->now()->getTimestamp();
  243. $dirtyTableWrites = [];
  244. foreach ($tables as $table) {
  245. $lastAccess = $this->tableDirtyWrites[$table] ?? 0;
  246. // Only very recent writes are considered dirty
  247. if ($lastAccess >= ($now - 3)) {
  248. $dirtyTableWrites[] = $table;
  249. }
  250. }
  251. if ($this->isTransactionActive()) {
  252. // Transacted queries go to the primary. The consistency of the primary guarantees that we can not run
  253. // into a dirty read.
  254. } elseif (count($dirtyTableWrites) === 0) {
  255. // No tables read that could have been written already in the same request and no transaction active
  256. // so we can switch back to the replica for reading as long as no writes happen that switch back to the primary
  257. // We cannot log here as this would log too early in the server boot process
  258. $this->ensureConnectedToReplica();
  259. } else {
  260. // Read to a table that has been written to previously
  261. // While this might not necessarily mean that we did a read after write it is an indication for a code path to check
  262. $this->logger->log(
  263. (int) ($this->systemConfig->getValue('loglevel_dirty_database_queries', null) ?? 0),
  264. 'dirty table reads: ' . $sql,
  265. [
  266. 'tables' => array_keys($this->tableDirtyWrites),
  267. 'reads' => $tables,
  268. 'exception' => new \Exception('dirty table reads: ' . $sql),
  269. ],
  270. );
  271. // To prevent a dirty read on a replica that is slightly out of sync, we
  272. // switch back to the primary. This is detrimental for performance but
  273. // safer for consistency.
  274. $this->ensureConnectedToPrimary();
  275. }
  276. $sql = $this->replaceTablePrefix($sql);
  277. $sql = $this->adapter->fixupStatement($sql);
  278. $this->queriesExecuted++;
  279. $this->logQueryToFile($sql);
  280. return parent::executeQuery($sql, $params, $types, $qcp);
  281. }
  282. /**
  283. * Helper function to get the list of tables affected by a given query
  284. * used to track dirty tables that received a write with the current request
  285. */
  286. private function getQueriedTables(string $sql): array {
  287. $re = '/(\*PREFIX\*\w+)/mi';
  288. preg_match_all($re, $sql, $matches);
  289. return array_map([$this, 'replaceTablePrefix'], $matches[0] ?? []);
  290. }
  291. /**
  292. * @throws Exception
  293. */
  294. public function executeUpdate(string $sql, array $params = [], array $types = []): int {
  295. $sql = $this->replaceTablePrefix($sql);
  296. $sql = $this->adapter->fixupStatement($sql);
  297. $this->queriesExecuted++;
  298. $this->logQueryToFile($sql);
  299. return parent::executeUpdate($sql, $params, $types);
  300. }
  301. /**
  302. * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
  303. * and returns the number of affected rows.
  304. *
  305. * This method supports PDO binding types as well as DBAL mapping types.
  306. *
  307. * @param string $sql The SQL query.
  308. * @param array $params The query parameters.
  309. * @param array $types The parameter types.
  310. *
  311. * @return int The number of affected rows.
  312. *
  313. * @throws \Doctrine\DBAL\Exception
  314. */
  315. public function executeStatement($sql, array $params = [], array $types = []): int {
  316. $tables = $this->getQueriedTables($sql);
  317. foreach ($tables as $table) {
  318. $this->tableDirtyWrites[$table] = $this->clock->now()->getTimestamp();
  319. }
  320. $sql = $this->replaceTablePrefix($sql);
  321. $sql = $this->adapter->fixupStatement($sql);
  322. $this->queriesExecuted++;
  323. $this->logQueryToFile($sql);
  324. return (int)parent::executeStatement($sql, $params, $types);
  325. }
  326. protected function logQueryToFile(string $sql): void {
  327. $logFile = $this->systemConfig->getValue('query_log_file');
  328. if ($logFile !== '' && is_writable(dirname($logFile)) && (!file_exists($logFile) || is_writable($logFile))) {
  329. $prefix = '';
  330. if ($this->systemConfig->getValue('query_log_file_requestid') === 'yes') {
  331. $prefix .= \OC::$server->get(IRequestId::class)->getId() . "\t";
  332. }
  333. // FIXME: Improve to log the actual target db host
  334. $isPrimary = $this->connections['primary'] === $this->_conn;
  335. $prefix .= ' ' . ($isPrimary === true ? 'primary' : 'replica') . ' ';
  336. $prefix .= ' ' . $this->getTransactionNestingLevel() . ' ';
  337. file_put_contents(
  338. $this->systemConfig->getValue('query_log_file', ''),
  339. $prefix . $sql . "\n",
  340. FILE_APPEND
  341. );
  342. }
  343. }
  344. /**
  345. * Returns the ID of the last inserted row, or the last value from a sequence object,
  346. * depending on the underlying driver.
  347. *
  348. * Note: This method may not return a meaningful or consistent result across different drivers,
  349. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  350. * columns or sequences.
  351. *
  352. * @param string $seqName Name of the sequence object from which the ID should be returned.
  353. *
  354. * @return int the last inserted ID.
  355. * @throws Exception
  356. */
  357. public function lastInsertId($name = null): int {
  358. if ($name) {
  359. $name = $this->replaceTablePrefix($name);
  360. }
  361. return $this->adapter->lastInsertId($name);
  362. }
  363. /**
  364. * @internal
  365. * @throws Exception
  366. */
  367. public function realLastInsertId($seqName = null) {
  368. return parent::lastInsertId($seqName);
  369. }
  370. /**
  371. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  372. * it is needed that there is also a unique constraint on the values. Then this method will
  373. * catch the exception and return 0.
  374. *
  375. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  376. * @param array $input data that should be inserted into the table (column name => value)
  377. * @param array|null $compare List of values that should be checked for "if not exists"
  378. * If this is null or an empty array, all keys of $input will be compared
  379. * Please note: text fields (clob) must not be used in the compare array
  380. * @return int number of inserted rows
  381. * @throws \Doctrine\DBAL\Exception
  382. * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
  383. */
  384. public function insertIfNotExist($table, $input, ?array $compare = null) {
  385. return $this->adapter->insertIfNotExist($table, $input, $compare);
  386. }
  387. public function insertIgnoreConflict(string $table, array $values) : int {
  388. return $this->adapter->insertIgnoreConflict($table, $values);
  389. }
  390. private function getType($value) {
  391. if (is_bool($value)) {
  392. return IQueryBuilder::PARAM_BOOL;
  393. } elseif (is_int($value)) {
  394. return IQueryBuilder::PARAM_INT;
  395. } else {
  396. return IQueryBuilder::PARAM_STR;
  397. }
  398. }
  399. /**
  400. * Insert or update a row value
  401. *
  402. * @param string $table
  403. * @param array $keys (column name => value)
  404. * @param array $values (column name => value)
  405. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  406. * @return int number of new rows
  407. * @throws \OCP\DB\Exception
  408. * @throws PreConditionNotMetException
  409. */
  410. public function setValues(string $table, array $keys, array $values, array $updatePreconditionValues = []): int {
  411. try {
  412. $insertQb = $this->getQueryBuilder();
  413. $insertQb->insert($table)
  414. ->values(
  415. array_map(function ($value) use ($insertQb) {
  416. return $insertQb->createNamedParameter($value, $this->getType($value));
  417. }, array_merge($keys, $values))
  418. );
  419. return $insertQb->executeStatement();
  420. } catch (\OCP\DB\Exception $e) {
  421. if (!in_array($e->getReason(), [
  422. \OCP\DB\Exception::REASON_CONSTRAINT_VIOLATION,
  423. \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION,
  424. ])
  425. ) {
  426. throw $e;
  427. }
  428. // value already exists, try update
  429. $updateQb = $this->getQueryBuilder();
  430. $updateQb->update($table);
  431. foreach ($values as $name => $value) {
  432. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  433. }
  434. $where = $updateQb->expr()->andX();
  435. $whereValues = array_merge($keys, $updatePreconditionValues);
  436. foreach ($whereValues as $name => $value) {
  437. if ($value === '') {
  438. $where->add($updateQb->expr()->emptyString(
  439. $name
  440. ));
  441. } else {
  442. $where->add($updateQb->expr()->eq(
  443. $name,
  444. $updateQb->createNamedParameter($value, $this->getType($value)),
  445. $this->getType($value)
  446. ));
  447. }
  448. }
  449. $updateQb->where($where);
  450. $affected = $updateQb->executeStatement();
  451. if ($affected === 0 && !empty($updatePreconditionValues)) {
  452. throw new PreConditionNotMetException();
  453. }
  454. return 0;
  455. }
  456. }
  457. /**
  458. * Create an exclusive read+write lock on a table
  459. *
  460. * @param string $tableName
  461. *
  462. * @throws \BadMethodCallException When trying to acquire a second lock
  463. * @throws Exception
  464. * @since 9.1.0
  465. */
  466. public function lockTable($tableName) {
  467. if ($this->lockedTable !== null) {
  468. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  469. }
  470. $tableName = $this->tablePrefix . $tableName;
  471. $this->lockedTable = $tableName;
  472. $this->adapter->lockTable($tableName);
  473. }
  474. /**
  475. * Release a previous acquired lock again
  476. *
  477. * @throws Exception
  478. * @since 9.1.0
  479. */
  480. public function unlockTable() {
  481. $this->adapter->unlockTable();
  482. $this->lockedTable = null;
  483. }
  484. /**
  485. * returns the error code and message as a string for logging
  486. * works with DoctrineException
  487. * @return string
  488. */
  489. public function getError() {
  490. $msg = $this->errorCode() . ': ';
  491. $errorInfo = $this->errorInfo();
  492. if (!empty($errorInfo)) {
  493. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  494. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  495. $msg .= 'Driver Message = '.$errorInfo[2];
  496. }
  497. return $msg;
  498. }
  499. public function errorCode() {
  500. return -1;
  501. }
  502. public function errorInfo() {
  503. return [];
  504. }
  505. /**
  506. * Drop a table from the database if it exists
  507. *
  508. * @param string $table table name without the prefix
  509. *
  510. * @throws Exception
  511. */
  512. public function dropTable($table) {
  513. $table = $this->tablePrefix . trim($table);
  514. $schema = $this->getSchemaManager();
  515. if ($schema->tablesExist([$table])) {
  516. $schema->dropTable($table);
  517. }
  518. }
  519. /**
  520. * Check if a table exists
  521. *
  522. * @param string $table table name without the prefix
  523. *
  524. * @return bool
  525. * @throws Exception
  526. */
  527. public function tableExists($table) {
  528. $table = $this->tablePrefix . trim($table);
  529. $schema = $this->getSchemaManager();
  530. return $schema->tablesExist([$table]);
  531. }
  532. // internal use
  533. /**
  534. * @param string $statement
  535. * @return string
  536. */
  537. protected function replaceTablePrefix($statement) {
  538. return str_replace('*PREFIX*', $this->tablePrefix, $statement);
  539. }
  540. /**
  541. * Check if a transaction is active
  542. *
  543. * @return bool
  544. * @since 8.2.0
  545. */
  546. public function inTransaction() {
  547. return $this->getTransactionNestingLevel() > 0;
  548. }
  549. /**
  550. * Escape a parameter to be used in a LIKE query
  551. *
  552. * @param string $param
  553. * @return string
  554. */
  555. public function escapeLikeParameter($param) {
  556. return addcslashes($param, '\\_%');
  557. }
  558. /**
  559. * Check whether or not the current database support 4byte wide unicode
  560. *
  561. * @return bool
  562. * @since 11.0.0
  563. */
  564. public function supports4ByteText() {
  565. if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
  566. return true;
  567. }
  568. return $this->getParams()['charset'] === 'utf8mb4';
  569. }
  570. /**
  571. * Create the schema of the connected database
  572. *
  573. * @return Schema
  574. * @throws Exception
  575. */
  576. public function createSchema() {
  577. $migrator = $this->getMigrator();
  578. return $migrator->createSchema();
  579. }
  580. /**
  581. * Migrate the database to the given schema
  582. *
  583. * @param Schema $toSchema
  584. * @param bool $dryRun If true, will return the sql queries instead of running them.
  585. *
  586. * @throws Exception
  587. *
  588. * @return string|null Returns a string only if $dryRun is true.
  589. */
  590. public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
  591. $migrator = $this->getMigrator();
  592. if ($dryRun) {
  593. return $migrator->generateChangeScript($toSchema);
  594. } else {
  595. $migrator->migrate($toSchema);
  596. }
  597. }
  598. private function getMigrator() {
  599. // TODO properly inject those dependencies
  600. $random = \OC::$server->getSecureRandom();
  601. $platform = $this->getDatabasePlatform();
  602. $config = \OC::$server->getConfig();
  603. $dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class);
  604. if ($platform instanceof SqlitePlatform) {
  605. return new SQLiteMigrator($this, $config, $dispatcher);
  606. } elseif ($platform instanceof OraclePlatform) {
  607. return new OracleMigrator($this, $config, $dispatcher);
  608. } else {
  609. return new Migrator($this, $config, $dispatcher);
  610. }
  611. }
  612. public function beginTransaction() {
  613. if (!$this->inTransaction()) {
  614. $this->transactionActiveSince = microtime(true);
  615. }
  616. return parent::beginTransaction();
  617. }
  618. public function commit() {
  619. $result = parent::commit();
  620. if ($this->getTransactionNestingLevel() === 0) {
  621. $timeTook = microtime(true) - $this->transactionActiveSince;
  622. $this->transactionActiveSince = null;
  623. if ($timeTook > 1) {
  624. $this->logger->warning('Transaction took ' . $timeTook . 's', ['exception' => new \Exception('Transaction took ' . $timeTook . 's')]);
  625. }
  626. }
  627. return $result;
  628. }
  629. public function rollBack() {
  630. $result = parent::rollBack();
  631. if ($this->getTransactionNestingLevel() === 0) {
  632. $timeTook = microtime(true) - $this->transactionActiveSince;
  633. $this->transactionActiveSince = null;
  634. if ($timeTook > 1) {
  635. $this->logger->warning('Transaction rollback took longer than 1s: ' . $timeTook, ['exception' => new \Exception('Long running transaction rollback')]);
  636. }
  637. }
  638. return $result;
  639. }
  640. private function reconnectIfNeeded(): void {
  641. if (
  642. !isset($this->lastConnectionCheck[$this->getConnectionName()]) ||
  643. time() <= $this->lastConnectionCheck[$this->getConnectionName()] + 30 ||
  644. $this->isTransactionActive()
  645. ) {
  646. return;
  647. }
  648. try {
  649. $this->_conn->query($this->getDriver()->getDatabasePlatform()->getDummySelectSQL());
  650. $this->lastConnectionCheck[$this->getConnectionName()] = time();
  651. } catch (ConnectionLost|\Exception $e) {
  652. $this->logger->warning('Exception during connectivity check, closing and reconnecting', ['exception' => $e]);
  653. $this->close();
  654. }
  655. }
  656. private function getConnectionName(): string {
  657. return $this->isConnectedToPrimary() ? 'primary' : 'replica';
  658. }
  659. }