Connection.php 21 KB

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