1
0

Connection.php 22 KB

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