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

Connection.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. $postfix = '';
  335. if ($this->systemConfig->getValue('query_log_file_backtrace') === 'yes') {
  336. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  337. array_pop($trace);
  338. $postfix .= '; ' . json_encode($trace);
  339. }
  340. // FIXME: Improve to log the actual target db host
  341. $isPrimary = $this->connections['primary'] === $this->_conn;
  342. $prefix .= ' ' . ($isPrimary === true ? 'primary' : 'replica') . ' ';
  343. $prefix .= ' ' . $this->getTransactionNestingLevel() . ' ';
  344. file_put_contents(
  345. $this->systemConfig->getValue('query_log_file', ''),
  346. $prefix . $sql . $postfix . "\n",
  347. FILE_APPEND
  348. );
  349. }
  350. }
  351. /**
  352. * Returns the ID of the last inserted row, or the last value from a sequence object,
  353. * depending on the underlying driver.
  354. *
  355. * Note: This method may not return a meaningful or consistent result across different drivers,
  356. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  357. * columns or sequences.
  358. *
  359. * @param string $seqName Name of the sequence object from which the ID should be returned.
  360. *
  361. * @return int the last inserted ID.
  362. * @throws Exception
  363. */
  364. public function lastInsertId($name = null): int {
  365. if ($name) {
  366. $name = $this->replaceTablePrefix($name);
  367. }
  368. return $this->adapter->lastInsertId($name);
  369. }
  370. /**
  371. * @internal
  372. * @throws Exception
  373. */
  374. public function realLastInsertId($seqName = null) {
  375. return parent::lastInsertId($seqName);
  376. }
  377. /**
  378. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  379. * it is needed that there is also a unique constraint on the values. Then this method will
  380. * catch the exception and return 0.
  381. *
  382. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  383. * @param array $input data that should be inserted into the table (column name => value)
  384. * @param array|null $compare List of values that should be checked for "if not exists"
  385. * If this is null or an empty array, all keys of $input will be compared
  386. * Please note: text fields (clob) must not be used in the compare array
  387. * @return int number of inserted rows
  388. * @throws \Doctrine\DBAL\Exception
  389. * @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
  390. */
  391. public function insertIfNotExist($table, $input, ?array $compare = null) {
  392. return $this->adapter->insertIfNotExist($table, $input, $compare);
  393. }
  394. public function insertIgnoreConflict(string $table, array $values) : int {
  395. return $this->adapter->insertIgnoreConflict($table, $values);
  396. }
  397. private function getType($value) {
  398. if (is_bool($value)) {
  399. return IQueryBuilder::PARAM_BOOL;
  400. } elseif (is_int($value)) {
  401. return IQueryBuilder::PARAM_INT;
  402. } else {
  403. return IQueryBuilder::PARAM_STR;
  404. }
  405. }
  406. /**
  407. * Insert or update a row value
  408. *
  409. * @param string $table
  410. * @param array $keys (column name => value)
  411. * @param array $values (column name => value)
  412. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  413. * @return int number of new rows
  414. * @throws \OCP\DB\Exception
  415. * @throws PreConditionNotMetException
  416. */
  417. public function setValues(string $table, array $keys, array $values, array $updatePreconditionValues = []): int {
  418. try {
  419. $insertQb = $this->getQueryBuilder();
  420. $insertQb->insert($table)
  421. ->values(
  422. array_map(function ($value) use ($insertQb) {
  423. return $insertQb->createNamedParameter($value, $this->getType($value));
  424. }, array_merge($keys, $values))
  425. );
  426. return $insertQb->executeStatement();
  427. } catch (\OCP\DB\Exception $e) {
  428. if (!in_array($e->getReason(), [
  429. \OCP\DB\Exception::REASON_CONSTRAINT_VIOLATION,
  430. \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION,
  431. ])
  432. ) {
  433. throw $e;
  434. }
  435. // value already exists, try update
  436. $updateQb = $this->getQueryBuilder();
  437. $updateQb->update($table);
  438. foreach ($values as $name => $value) {
  439. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  440. }
  441. $where = $updateQb->expr()->andX();
  442. $whereValues = array_merge($keys, $updatePreconditionValues);
  443. foreach ($whereValues as $name => $value) {
  444. if ($value === '') {
  445. $where->add($updateQb->expr()->emptyString(
  446. $name
  447. ));
  448. } else {
  449. $where->add($updateQb->expr()->eq(
  450. $name,
  451. $updateQb->createNamedParameter($value, $this->getType($value)),
  452. $this->getType($value)
  453. ));
  454. }
  455. }
  456. $updateQb->where($where);
  457. $affected = $updateQb->executeStatement();
  458. if ($affected === 0 && !empty($updatePreconditionValues)) {
  459. throw new PreConditionNotMetException();
  460. }
  461. return 0;
  462. }
  463. }
  464. /**
  465. * Create an exclusive read+write lock on a table
  466. *
  467. * @param string $tableName
  468. *
  469. * @throws \BadMethodCallException When trying to acquire a second lock
  470. * @throws Exception
  471. * @since 9.1.0
  472. */
  473. public function lockTable($tableName) {
  474. if ($this->lockedTable !== null) {
  475. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  476. }
  477. $tableName = $this->tablePrefix . $tableName;
  478. $this->lockedTable = $tableName;
  479. $this->adapter->lockTable($tableName);
  480. }
  481. /**
  482. * Release a previous acquired lock again
  483. *
  484. * @throws Exception
  485. * @since 9.1.0
  486. */
  487. public function unlockTable() {
  488. $this->adapter->unlockTable();
  489. $this->lockedTable = null;
  490. }
  491. /**
  492. * returns the error code and message as a string for logging
  493. * works with DoctrineException
  494. * @return string
  495. */
  496. public function getError() {
  497. $msg = $this->errorCode() . ': ';
  498. $errorInfo = $this->errorInfo();
  499. if (!empty($errorInfo)) {
  500. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  501. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  502. $msg .= 'Driver Message = '.$errorInfo[2];
  503. }
  504. return $msg;
  505. }
  506. public function errorCode() {
  507. return -1;
  508. }
  509. public function errorInfo() {
  510. return [];
  511. }
  512. /**
  513. * Drop a table from the database if it exists
  514. *
  515. * @param string $table table name without the prefix
  516. *
  517. * @throws Exception
  518. */
  519. public function dropTable($table) {
  520. $table = $this->tablePrefix . trim($table);
  521. $schema = $this->getSchemaManager();
  522. if ($schema->tablesExist([$table])) {
  523. $schema->dropTable($table);
  524. }
  525. }
  526. /**
  527. * Check if a table exists
  528. *
  529. * @param string $table table name without the prefix
  530. *
  531. * @return bool
  532. * @throws Exception
  533. */
  534. public function tableExists($table) {
  535. $table = $this->tablePrefix . trim($table);
  536. $schema = $this->getSchemaManager();
  537. return $schema->tablesExist([$table]);
  538. }
  539. protected function finishQuery(string $statement): string {
  540. $statement = $this->replaceTablePrefix($statement);
  541. $statement = $this->adapter->fixupStatement($statement);
  542. if ($this->logRequestId) {
  543. return $statement . " /* reqid: " . $this->requestId . " */";
  544. } else {
  545. return $statement;
  546. }
  547. }
  548. // internal use
  549. /**
  550. * @param string $statement
  551. * @return string
  552. */
  553. protected function replaceTablePrefix($statement) {
  554. return str_replace('*PREFIX*', $this->tablePrefix, $statement);
  555. }
  556. /**
  557. * Check if a transaction is active
  558. *
  559. * @return bool
  560. * @since 8.2.0
  561. */
  562. public function inTransaction() {
  563. return $this->getTransactionNestingLevel() > 0;
  564. }
  565. /**
  566. * Escape a parameter to be used in a LIKE query
  567. *
  568. * @param string $param
  569. * @return string
  570. */
  571. public function escapeLikeParameter($param) {
  572. return addcslashes($param, '\\_%');
  573. }
  574. /**
  575. * Check whether or not the current database support 4byte wide unicode
  576. *
  577. * @return bool
  578. * @since 11.0.0
  579. */
  580. public function supports4ByteText() {
  581. if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
  582. return true;
  583. }
  584. return $this->getParams()['charset'] === 'utf8mb4';
  585. }
  586. /**
  587. * Create the schema of the connected database
  588. *
  589. * @return Schema
  590. * @throws Exception
  591. */
  592. public function createSchema() {
  593. $migrator = $this->getMigrator();
  594. return $migrator->createSchema();
  595. }
  596. /**
  597. * Migrate the database to the given schema
  598. *
  599. * @param Schema $toSchema
  600. * @param bool $dryRun If true, will return the sql queries instead of running them.
  601. *
  602. * @throws Exception
  603. *
  604. * @return string|null Returns a string only if $dryRun is true.
  605. */
  606. public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
  607. $migrator = $this->getMigrator();
  608. if ($dryRun) {
  609. return $migrator->generateChangeScript($toSchema);
  610. } else {
  611. $migrator->migrate($toSchema);
  612. }
  613. }
  614. private function getMigrator() {
  615. // TODO properly inject those dependencies
  616. $random = \OC::$server->getSecureRandom();
  617. $platform = $this->getDatabasePlatform();
  618. $config = \OC::$server->getConfig();
  619. $dispatcher = Server::get(\OCP\EventDispatcher\IEventDispatcher::class);
  620. if ($platform instanceof SqlitePlatform) {
  621. return new SQLiteMigrator($this, $config, $dispatcher);
  622. } elseif ($platform instanceof OraclePlatform) {
  623. return new OracleMigrator($this, $config, $dispatcher);
  624. } else {
  625. return new Migrator($this, $config, $dispatcher);
  626. }
  627. }
  628. public function beginTransaction() {
  629. if (!$this->inTransaction()) {
  630. $this->transactionActiveSince = microtime(true);
  631. }
  632. return parent::beginTransaction();
  633. }
  634. public function commit() {
  635. $result = parent::commit();
  636. if ($this->getTransactionNestingLevel() === 0) {
  637. $timeTook = microtime(true) - $this->transactionActiveSince;
  638. $this->transactionActiveSince = null;
  639. if ($timeTook > 1) {
  640. $this->logger->warning('Transaction took ' . $timeTook . 's', ['exception' => new \Exception('Transaction took ' . $timeTook . 's')]);
  641. }
  642. }
  643. return $result;
  644. }
  645. public function rollBack() {
  646. $result = parent::rollBack();
  647. if ($this->getTransactionNestingLevel() === 0) {
  648. $timeTook = microtime(true) - $this->transactionActiveSince;
  649. $this->transactionActiveSince = null;
  650. if ($timeTook > 1) {
  651. $this->logger->warning('Transaction rollback took longer than 1s: ' . $timeTook, ['exception' => new \Exception('Long running transaction rollback')]);
  652. }
  653. }
  654. return $result;
  655. }
  656. private function reconnectIfNeeded(): void {
  657. if (
  658. !isset($this->lastConnectionCheck[$this->getConnectionName()]) ||
  659. time() <= $this->lastConnectionCheck[$this->getConnectionName()] + 30 ||
  660. $this->isTransactionActive()
  661. ) {
  662. return;
  663. }
  664. try {
  665. $this->_conn->query($this->getDriver()->getDatabasePlatform()->getDummySelectSQL());
  666. $this->lastConnectionCheck[$this->getConnectionName()] = time();
  667. } catch (ConnectionLost|\Exception $e) {
  668. $this->logger->warning('Exception during connectivity check, closing and reconnecting', ['exception' => $e]);
  669. $this->close();
  670. }
  671. }
  672. private function getConnectionName(): string {
  673. return $this->isConnectedToPrimary() ? 'primary' : 'replica';
  674. }
  675. }