Connection.php 24 KB

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