1
0

Connection.php 28 KB

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