Connection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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\IRequestId;
  51. use OCP\PreConditionNotMetException;
  52. use OC\DB\QueryBuilder\QueryBuilder;
  53. use OC\SystemConfig;
  54. use Psr\Log\LoggerInterface;
  55. use OCP\Profiler\IProfiler;
  56. class Connection extends \Doctrine\DBAL\Connection {
  57. /** @var string */
  58. protected $tablePrefix;
  59. /** @var \OC\DB\Adapter $adapter */
  60. protected $adapter;
  61. /** @var SystemConfig */
  62. private $systemConfig;
  63. private LoggerInterface $logger;
  64. protected $lockedTable = null;
  65. /** @var int */
  66. protected $queriesBuilt = 0;
  67. /** @var int */
  68. protected $queriesExecuted = 0;
  69. /** @var DbDataCollector|null */
  70. protected $dbDataCollector = null;
  71. /**
  72. * Initializes a new instance of the Connection class.
  73. *
  74. * @throws \Exception
  75. */
  76. public function __construct(
  77. array $params,
  78. Driver $driver,
  79. ?Configuration $config = null,
  80. ?EventManager $eventManager = null
  81. ) {
  82. if (!isset($params['adapter'])) {
  83. throw new \Exception('adapter not set');
  84. }
  85. if (!isset($params['tablePrefix'])) {
  86. throw new \Exception('tablePrefix not set');
  87. }
  88. /**
  89. * @psalm-suppress InternalMethod
  90. */
  91. parent::__construct($params, $driver, $config, $eventManager);
  92. $this->adapter = new $params['adapter']($this);
  93. $this->tablePrefix = $params['tablePrefix'];
  94. $this->systemConfig = \OC::$server->getSystemConfig();
  95. $this->logger = \OC::$server->get(LoggerInterface::class);
  96. /** @var \OCP\Profiler\IProfiler */
  97. $profiler = \OC::$server->get(IProfiler::class);
  98. if ($profiler->isEnabled()) {
  99. $this->dbDataCollector = new DbDataCollector($this);
  100. $profiler->add($this->dbDataCollector);
  101. $debugStack = new BacktraceDebugStack();
  102. $this->dbDataCollector->setDebugStack($debugStack);
  103. $this->_config->setSQLLogger($debugStack);
  104. }
  105. }
  106. /**
  107. * @throws Exception
  108. */
  109. public function connect() {
  110. try {
  111. if ($this->_conn) {
  112. return parent::connect();
  113. }
  114. // Only trigger the event logger for the initial connect call
  115. $eventLogger = \OC::$server->getEventLogger();
  116. $eventLogger->start('connect:db', 'db connection opened');
  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($statement, $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. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  208. }
  209. $statement = $this->replaceTablePrefix($statement);
  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 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 string the last inserted ID.
  291. * @throws Exception
  292. */
  293. public function lastInsertId($seqName = null) {
  294. if ($seqName) {
  295. $seqName = $this->replaceTablePrefix($seqName);
  296. }
  297. return $this->adapter->lastInsertId($seqName);
  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 \Doctrine\DBAL\Exception
  344. * @throws PreConditionNotMetException
  345. */
  346. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  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->execute();
  356. } catch (NotNullConstraintViolationException $e) {
  357. throw $e;
  358. } catch (ConstraintViolationException $e) {
  359. // value already exists, try update
  360. $updateQb = $this->getQueryBuilder();
  361. $updateQb->update($table);
  362. foreach ($values as $name => $value) {
  363. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  364. }
  365. $where = $updateQb->expr()->andX();
  366. $whereValues = array_merge($keys, $updatePreconditionValues);
  367. foreach ($whereValues as $name => $value) {
  368. if ($value === '') {
  369. $where->add($updateQb->expr()->emptyString(
  370. $name
  371. ));
  372. } else {
  373. $where->add($updateQb->expr()->eq(
  374. $name,
  375. $updateQb->createNamedParameter($value, $this->getType($value)),
  376. $this->getType($value)
  377. ));
  378. }
  379. }
  380. $updateQb->where($where);
  381. $affected = $updateQb->execute();
  382. if ($affected === 0 && !empty($updatePreconditionValues)) {
  383. throw new PreConditionNotMetException();
  384. }
  385. return 0;
  386. }
  387. }
  388. /**
  389. * Create an exclusive read+write lock on a table
  390. *
  391. * @param string $tableName
  392. *
  393. * @throws \BadMethodCallException When trying to acquire a second lock
  394. * @throws Exception
  395. * @since 9.1.0
  396. */
  397. public function lockTable($tableName) {
  398. if ($this->lockedTable !== null) {
  399. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  400. }
  401. $tableName = $this->tablePrefix . $tableName;
  402. $this->lockedTable = $tableName;
  403. $this->adapter->lockTable($tableName);
  404. }
  405. /**
  406. * Release a previous acquired lock again
  407. *
  408. * @throws Exception
  409. * @since 9.1.0
  410. */
  411. public function unlockTable() {
  412. $this->adapter->unlockTable();
  413. $this->lockedTable = null;
  414. }
  415. /**
  416. * returns the error code and message as a string for logging
  417. * works with DoctrineException
  418. * @return string
  419. */
  420. public function getError() {
  421. $msg = $this->errorCode() . ': ';
  422. $errorInfo = $this->errorInfo();
  423. if (!empty($errorInfo)) {
  424. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  425. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  426. $msg .= 'Driver Message = '.$errorInfo[2];
  427. }
  428. return $msg;
  429. }
  430. public function errorCode() {
  431. return -1;
  432. }
  433. public function errorInfo() {
  434. return [];
  435. }
  436. /**
  437. * Drop a table from the database if it exists
  438. *
  439. * @param string $table table name without the prefix
  440. *
  441. * @throws Exception
  442. */
  443. public function dropTable($table) {
  444. $table = $this->tablePrefix . trim($table);
  445. $schema = $this->getSchemaManager();
  446. if ($schema->tablesExist([$table])) {
  447. $schema->dropTable($table);
  448. }
  449. }
  450. /**
  451. * Check if a table exists
  452. *
  453. * @param string $table table name without the prefix
  454. *
  455. * @return bool
  456. * @throws Exception
  457. */
  458. public function tableExists($table) {
  459. $table = $this->tablePrefix . trim($table);
  460. $schema = $this->getSchemaManager();
  461. return $schema->tablesExist([$table]);
  462. }
  463. // internal use
  464. /**
  465. * @param string $statement
  466. * @return string
  467. */
  468. protected function replaceTablePrefix($statement) {
  469. return str_replace('*PREFIX*', $this->tablePrefix, $statement);
  470. }
  471. /**
  472. * Check if a transaction is active
  473. *
  474. * @return bool
  475. * @since 8.2.0
  476. */
  477. public function inTransaction() {
  478. return $this->getTransactionNestingLevel() > 0;
  479. }
  480. /**
  481. * Escape a parameter to be used in a LIKE query
  482. *
  483. * @param string $param
  484. * @return string
  485. */
  486. public function escapeLikeParameter($param) {
  487. return addcslashes($param, '\\_%');
  488. }
  489. /**
  490. * Check whether or not the current database support 4byte wide unicode
  491. *
  492. * @return bool
  493. * @since 11.0.0
  494. */
  495. public function supports4ByteText() {
  496. if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
  497. return true;
  498. }
  499. return $this->getParams()['charset'] === 'utf8mb4';
  500. }
  501. /**
  502. * Create the schema of the connected database
  503. *
  504. * @return Schema
  505. * @throws Exception
  506. */
  507. public function createSchema() {
  508. $migrator = $this->getMigrator();
  509. return $migrator->createSchema();
  510. }
  511. /**
  512. * Migrate the database to the given schema
  513. *
  514. * @param Schema $toSchema
  515. * @param bool $dryRun If true, will return the sql queries instead of running them.
  516. *
  517. * @throws Exception
  518. *
  519. * @return string|null Returns a string only if $dryRun is true.
  520. */
  521. public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
  522. $migrator = $this->getMigrator();
  523. if ($dryRun) {
  524. return $migrator->generateChangeScript($toSchema);
  525. } else {
  526. $migrator->migrate($toSchema);
  527. }
  528. }
  529. private function getMigrator() {
  530. // TODO properly inject those dependencies
  531. $random = \OC::$server->getSecureRandom();
  532. $platform = $this->getDatabasePlatform();
  533. $config = \OC::$server->getConfig();
  534. $dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class);
  535. if ($platform instanceof SqlitePlatform) {
  536. return new SQLiteMigrator($this, $config, $dispatcher);
  537. } elseif ($platform instanceof OraclePlatform) {
  538. return new OracleMigrator($this, $config, $dispatcher);
  539. } elseif ($platform instanceof MySQLPlatform) {
  540. return new MySQLMigrator($this, $config, $dispatcher);
  541. } elseif ($platform instanceof PostgreSQL94Platform) {
  542. return new PostgreSqlMigrator($this, $config, $dispatcher);
  543. } else {
  544. return new Migrator($this, $config, $dispatcher);
  545. }
  546. }
  547. }