You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Connection.php 16KB

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