Connection.php 22 KB

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