1
0

Connection.php 24 KB

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