Connection.php 21 KB

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