Connection.php 22 KB

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