Connection.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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\Driver;
  39. use Doctrine\DBAL\Exception;
  40. use Doctrine\DBAL\Exception\ConstraintViolationException;
  41. use Doctrine\DBAL\Exception\NotNullConstraintViolationException;
  42. use Doctrine\DBAL\Platforms\MySQLPlatform;
  43. use Doctrine\DBAL\Platforms\OraclePlatform;
  44. use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
  45. use Doctrine\DBAL\Platforms\SqlitePlatform;
  46. use Doctrine\DBAL\Result;
  47. use Doctrine\DBAL\Schema\Schema;
  48. use Doctrine\DBAL\Statement;
  49. use OCP\DB\QueryBuilder\IQueryBuilder;
  50. use OCP\Diagnostics\IEventLogger;
  51. use OCP\IRequestId;
  52. use OCP\PreConditionNotMetException;
  53. use OCP\Profiler\IProfiler;
  54. use OC\DB\QueryBuilder\QueryBuilder;
  55. use OC\SystemConfig;
  56. use Psr\Log\LoggerInterface;
  57. class Connection extends \Doctrine\DBAL\Connection {
  58. /** @var string */
  59. protected $tablePrefix;
  60. /** @var \OC\DB\Adapter $adapter */
  61. protected $adapter;
  62. /** @var SystemConfig */
  63. private $systemConfig;
  64. private LoggerInterface $logger;
  65. protected $lockedTable = null;
  66. /** @var int */
  67. protected $queriesBuilt = 0;
  68. /** @var int */
  69. protected $queriesExecuted = 0;
  70. /** @var DbDataCollector|null */
  71. protected $dbDataCollector = null;
  72. /**
  73. * Initializes a new instance of the Connection class.
  74. *
  75. * @throws \Exception
  76. */
  77. public function __construct(
  78. array $params,
  79. Driver $driver,
  80. ?Configuration $config = null,
  81. ?EventManager $eventManager = null
  82. ) {
  83. if (!isset($params['adapter'])) {
  84. throw new \Exception('adapter not set');
  85. }
  86. if (!isset($params['tablePrefix'])) {
  87. throw new \Exception('tablePrefix not set');
  88. }
  89. /**
  90. * @psalm-suppress InternalMethod
  91. */
  92. parent::__construct($params, $driver, $config, $eventManager);
  93. $this->adapter = new $params['adapter']($this);
  94. $this->tablePrefix = $params['tablePrefix'];
  95. $this->systemConfig = \OC::$server->getSystemConfig();
  96. $this->logger = \OC::$server->get(LoggerInterface::class);
  97. /** @var \OCP\Profiler\IProfiler */
  98. $profiler = \OC::$server->get(IProfiler::class);
  99. if ($profiler->isEnabled()) {
  100. $this->dbDataCollector = new DbDataCollector($this);
  101. $profiler->add($this->dbDataCollector);
  102. $debugStack = new BacktraceDebugStack();
  103. $this->dbDataCollector->setDebugStack($debugStack);
  104. $this->_config->setSQLLogger($debugStack);
  105. }
  106. }
  107. /**
  108. * @throws Exception
  109. */
  110. public function connect() {
  111. try {
  112. if ($this->_conn) {
  113. /** @psalm-suppress InternalMethod */
  114. return parent::connect();
  115. }
  116. // Only trigger the event logger for the initial connect call
  117. $eventLogger = \OC::$server->get(IEventLogger::class);
  118. $eventLogger->start('connect:db', 'db connection opened');
  119. /** @psalm-suppress InternalMethod */
  120. $status = parent::connect();
  121. $eventLogger->end('connect:db');
  122. return $status;
  123. } catch (Exception $e) {
  124. // throw a new exception to prevent leaking info from the stacktrace
  125. throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
  126. }
  127. }
  128. public function getStats(): array {
  129. return [
  130. 'built' => $this->queriesBuilt,
  131. 'executed' => $this->queriesExecuted,
  132. ];
  133. }
  134. /**
  135. * Returns a QueryBuilder for the connection.
  136. */
  137. public function getQueryBuilder(): IQueryBuilder {
  138. $this->queriesBuilt++;
  139. return new QueryBuilder(
  140. new ConnectionAdapter($this),
  141. $this->systemConfig,
  142. $this->logger
  143. );
  144. }
  145. /**
  146. * Gets the QueryBuilder for the connection.
  147. *
  148. * @return \Doctrine\DBAL\Query\QueryBuilder
  149. * @deprecated please use $this->getQueryBuilder() instead
  150. */
  151. public function createQueryBuilder() {
  152. $backtrace = $this->getCallerBacktrace();
  153. $this->logger->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  154. $this->queriesBuilt++;
  155. return parent::createQueryBuilder();
  156. }
  157. /**
  158. * Gets the ExpressionBuilder for the connection.
  159. *
  160. * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
  161. * @deprecated please use $this->getQueryBuilder()->expr() instead
  162. */
  163. public function getExpressionBuilder() {
  164. $backtrace = $this->getCallerBacktrace();
  165. $this->logger->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  166. $this->queriesBuilt++;
  167. return parent::getExpressionBuilder();
  168. }
  169. /**
  170. * Get the file and line that called the method where `getCallerBacktrace()` was used
  171. *
  172. * @return string
  173. */
  174. protected function getCallerBacktrace() {
  175. $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  176. // 0 is the method where we use `getCallerBacktrace`
  177. // 1 is the target method which uses the method we want to log
  178. if (isset($traces[1])) {
  179. return $traces[1]['file'] . ':' . $traces[1]['line'];
  180. }
  181. return '';
  182. }
  183. /**
  184. * @return string
  185. */
  186. public function getPrefix() {
  187. return $this->tablePrefix;
  188. }
  189. /**
  190. * Prepares an SQL statement.
  191. *
  192. * @param string $statement The SQL statement to prepare.
  193. * @param int|null $limit
  194. * @param int|null $offset
  195. *
  196. * @return Statement The prepared statement.
  197. * @throws Exception
  198. */
  199. public function prepare($statement, $limit = null, $offset = null): Statement {
  200. if ($limit === -1 || $limit === null) {
  201. $limit = null;
  202. } else {
  203. $limit = (int) $limit;
  204. }
  205. if ($offset !== null) {
  206. $offset = (int) $offset;
  207. }
  208. if (!is_null($limit)) {
  209. $platform = $this->getDatabasePlatform();
  210. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  211. }
  212. $statement = $this->replaceTablePrefix($statement);
  213. $statement = $this->adapter->fixupStatement($statement);
  214. return parent::prepare($statement);
  215. }
  216. /**
  217. * Executes an, optionally parametrized, SQL query.
  218. *
  219. * If the query is parametrized, a prepared statement is used.
  220. * If an SQLLogger is configured, the execution is logged.
  221. *
  222. * @param string $sql The SQL query to execute.
  223. * @param array $params The parameters to bind to the query, if any.
  224. * @param array $types The types the previous parameters are in.
  225. * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
  226. *
  227. * @return Result The executed statement.
  228. *
  229. * @throws \Doctrine\DBAL\Exception
  230. */
  231. public function executeQuery(string $sql, array $params = [], $types = [], QueryCacheProfile $qcp = null): Result {
  232. $sql = $this->replaceTablePrefix($sql);
  233. $sql = $this->adapter->fixupStatement($sql);
  234. $this->queriesExecuted++;
  235. $this->logQueryToFile($sql);
  236. return parent::executeQuery($sql, $params, $types, $qcp);
  237. }
  238. /**
  239. * @throws Exception
  240. */
  241. public function executeUpdate(string $sql, array $params = [], array $types = []): int {
  242. $sql = $this->replaceTablePrefix($sql);
  243. $sql = $this->adapter->fixupStatement($sql);
  244. $this->queriesExecuted++;
  245. $this->logQueryToFile($sql);
  246. return parent::executeUpdate($sql, $params, $types);
  247. }
  248. /**
  249. * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
  250. * and returns the number of affected rows.
  251. *
  252. * This method supports PDO binding types as well as DBAL mapping types.
  253. *
  254. * @param string $sql The SQL query.
  255. * @param array $params The query parameters.
  256. * @param array $types The parameter types.
  257. *
  258. * @return int The number of affected rows.
  259. *
  260. * @throws \Doctrine\DBAL\Exception
  261. */
  262. public function executeStatement($sql, array $params = [], array $types = []): int {
  263. $sql = $this->replaceTablePrefix($sql);
  264. $sql = $this->adapter->fixupStatement($sql);
  265. $this->queriesExecuted++;
  266. $this->logQueryToFile($sql);
  267. return (int)parent::executeStatement($sql, $params, $types);
  268. }
  269. protected function logQueryToFile(string $sql): void {
  270. $logFile = $this->systemConfig->getValue('query_log_file');
  271. if ($logFile !== '' && is_writable(dirname($logFile)) && (!file_exists($logFile) || is_writable($logFile))) {
  272. $prefix = '';
  273. if ($this->systemConfig->getValue('query_log_file_requestid') === 'yes') {
  274. $prefix .= \OC::$server->get(IRequestId::class)->getId() . "\t";
  275. }
  276. file_put_contents(
  277. $this->systemConfig->getValue('query_log_file', ''),
  278. $prefix . $sql . "\n",
  279. FILE_APPEND
  280. );
  281. }
  282. }
  283. /**
  284. * Returns the ID of the last inserted row, or the last value from a sequence object,
  285. * depending on the underlying driver.
  286. *
  287. * Note: This method may not return a meaningful or consistent result across different drivers,
  288. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  289. * columns or sequences.
  290. *
  291. * @param string $seqName Name of the sequence object from which the ID should be returned.
  292. *
  293. * @return string the last inserted ID.
  294. * @throws Exception
  295. */
  296. public function lastInsertId($seqName = null) {
  297. if ($seqName) {
  298. $seqName = $this->replaceTablePrefix($seqName);
  299. }
  300. return $this->adapter->lastInsertId($seqName);
  301. }
  302. /**
  303. * @internal
  304. * @throws Exception
  305. */
  306. public function realLastInsertId($seqName = null) {
  307. return parent::lastInsertId($seqName);
  308. }
  309. /**
  310. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  311. * it is needed that there is also a unique constraint on the values. Then this method will
  312. * catch the exception and return 0.
  313. *
  314. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  315. * @param array $input data that should be inserted into the table (column name => value)
  316. * @param array|null $compare List of values that should be checked for "if not exists"
  317. * If this is null or an empty array, all keys of $input will be compared
  318. * Please note: text fields (clob) must not be used in the compare array
  319. * @return int number of inserted rows
  320. * @throws \Doctrine\DBAL\Exception
  321. * @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
  322. */
  323. public function insertIfNotExist($table, $input, array $compare = null) {
  324. return $this->adapter->insertIfNotExist($table, $input, $compare);
  325. }
  326. public function insertIgnoreConflict(string $table, array $values) : int {
  327. return $this->adapter->insertIgnoreConflict($table, $values);
  328. }
  329. private function getType($value) {
  330. if (is_bool($value)) {
  331. return IQueryBuilder::PARAM_BOOL;
  332. } elseif (is_int($value)) {
  333. return IQueryBuilder::PARAM_INT;
  334. } else {
  335. return IQueryBuilder::PARAM_STR;
  336. }
  337. }
  338. /**
  339. * Insert or update a row value
  340. *
  341. * @param string $table
  342. * @param array $keys (column name => value)
  343. * @param array $values (column name => value)
  344. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  345. * @return int number of new rows
  346. * @throws \Doctrine\DBAL\Exception
  347. * @throws PreConditionNotMetException
  348. */
  349. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  350. try {
  351. $insertQb = $this->getQueryBuilder();
  352. $insertQb->insert($table)
  353. ->values(
  354. array_map(function ($value) use ($insertQb) {
  355. return $insertQb->createNamedParameter($value, $this->getType($value));
  356. }, array_merge($keys, $values))
  357. );
  358. return $insertQb->executeStatement();
  359. } catch (NotNullConstraintViolationException $e) {
  360. throw $e;
  361. } catch (ConstraintViolationException $e) {
  362. // value already exists, try update
  363. $updateQb = $this->getQueryBuilder();
  364. $updateQb->update($table);
  365. foreach ($values as $name => $value) {
  366. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  367. }
  368. $where = $updateQb->expr()->andX();
  369. $whereValues = array_merge($keys, $updatePreconditionValues);
  370. foreach ($whereValues as $name => $value) {
  371. if ($value === '') {
  372. $where->add($updateQb->expr()->emptyString(
  373. $name
  374. ));
  375. } else {
  376. $where->add($updateQb->expr()->eq(
  377. $name,
  378. $updateQb->createNamedParameter($value, $this->getType($value)),
  379. $this->getType($value)
  380. ));
  381. }
  382. }
  383. $updateQb->where($where);
  384. $affected = $updateQb->executeStatement();
  385. if ($affected === 0 && !empty($updatePreconditionValues)) {
  386. throw new PreConditionNotMetException();
  387. }
  388. return 0;
  389. }
  390. }
  391. /**
  392. * Create an exclusive read+write lock on a table
  393. *
  394. * @param string $tableName
  395. *
  396. * @throws \BadMethodCallException When trying to acquire a second lock
  397. * @throws Exception
  398. * @since 9.1.0
  399. */
  400. public function lockTable($tableName) {
  401. if ($this->lockedTable !== null) {
  402. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  403. }
  404. $tableName = $this->tablePrefix . $tableName;
  405. $this->lockedTable = $tableName;
  406. $this->adapter->lockTable($tableName);
  407. }
  408. /**
  409. * Release a previous acquired lock again
  410. *
  411. * @throws Exception
  412. * @since 9.1.0
  413. */
  414. public function unlockTable() {
  415. $this->adapter->unlockTable();
  416. $this->lockedTable = null;
  417. }
  418. /**
  419. * returns the error code and message as a string for logging
  420. * works with DoctrineException
  421. * @return string
  422. */
  423. public function getError() {
  424. $msg = $this->errorCode() . ': ';
  425. $errorInfo = $this->errorInfo();
  426. if (!empty($errorInfo)) {
  427. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  428. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  429. $msg .= 'Driver Message = '.$errorInfo[2];
  430. }
  431. return $msg;
  432. }
  433. public function errorCode() {
  434. return -1;
  435. }
  436. public function errorInfo() {
  437. return [];
  438. }
  439. /**
  440. * Drop a table from the database if it exists
  441. *
  442. * @param string $table table name without the prefix
  443. *
  444. * @throws Exception
  445. */
  446. public function dropTable($table) {
  447. $table = $this->tablePrefix . trim($table);
  448. $schema = $this->getSchemaManager();
  449. if ($schema->tablesExist([$table])) {
  450. $schema->dropTable($table);
  451. }
  452. }
  453. /**
  454. * Check if a table exists
  455. *
  456. * @param string $table table name without the prefix
  457. *
  458. * @return bool
  459. * @throws Exception
  460. */
  461. public function tableExists($table) {
  462. $table = $this->tablePrefix . trim($table);
  463. $schema = $this->getSchemaManager();
  464. return $schema->tablesExist([$table]);
  465. }
  466. // internal use
  467. /**
  468. * @param string $statement
  469. * @return string
  470. */
  471. protected function replaceTablePrefix($statement) {
  472. return str_replace('*PREFIX*', $this->tablePrefix, $statement);
  473. }
  474. /**
  475. * Check if a transaction is active
  476. *
  477. * @return bool
  478. * @since 8.2.0
  479. */
  480. public function inTransaction() {
  481. return $this->getTransactionNestingLevel() > 0;
  482. }
  483. /**
  484. * Escape a parameter to be used in a LIKE query
  485. *
  486. * @param string $param
  487. * @return string
  488. */
  489. public function escapeLikeParameter($param) {
  490. return addcslashes($param, '\\_%');
  491. }
  492. /**
  493. * Check whether or not the current database support 4byte wide unicode
  494. *
  495. * @return bool
  496. * @since 11.0.0
  497. */
  498. public function supports4ByteText() {
  499. if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
  500. return true;
  501. }
  502. return $this->getParams()['charset'] === 'utf8mb4';
  503. }
  504. /**
  505. * Create the schema of the connected database
  506. *
  507. * @return Schema
  508. * @throws Exception
  509. */
  510. public function createSchema() {
  511. $migrator = $this->getMigrator();
  512. return $migrator->createSchema();
  513. }
  514. /**
  515. * Migrate the database to the given schema
  516. *
  517. * @param Schema $toSchema
  518. * @param bool $dryRun If true, will return the sql queries instead of running them.
  519. *
  520. * @throws Exception
  521. *
  522. * @return string|null Returns a string only if $dryRun is true.
  523. */
  524. public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
  525. $migrator = $this->getMigrator();
  526. if ($dryRun) {
  527. return $migrator->generateChangeScript($toSchema);
  528. } else {
  529. $migrator->migrate($toSchema);
  530. }
  531. }
  532. private function getMigrator() {
  533. // TODO properly inject those dependencies
  534. $random = \OC::$server->getSecureRandom();
  535. $platform = $this->getDatabasePlatform();
  536. $config = \OC::$server->getConfig();
  537. $dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class);
  538. if ($platform instanceof SqlitePlatform) {
  539. return new SQLiteMigrator($this, $config, $dispatcher);
  540. } elseif ($platform instanceof OraclePlatform) {
  541. return new OracleMigrator($this, $config, $dispatcher);
  542. } elseif ($platform instanceof MySQLPlatform) {
  543. return new MySQLMigrator($this, $config, $dispatcher);
  544. } elseif ($platform instanceof PostgreSQL94Platform) {
  545. return new PostgreSqlMigrator($this, $config, $dispatcher);
  546. } else {
  547. return new Migrator($this, $config, $dispatcher);
  548. }
  549. }
  550. }