Connection.php 17 KB

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