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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Ole Ostergaard <ole.c.ostergaard@gmail.com>
  11. * @author Ole Ostergaard <ole.ostergaard@knime.com>
  12. * @author Philipp Schaffrath <github@philipp.schaffrath.email>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Robin McCorkell <robin@mccorkell.me.uk>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\DB;
  34. use Doctrine\Common\EventManager;
  35. use Doctrine\DBAL\Cache\QueryCacheProfile;
  36. use Doctrine\DBAL\Configuration;
  37. use Doctrine\DBAL\DBALException;
  38. use Doctrine\DBAL\Driver;
  39. use Doctrine\DBAL\Exception\ConstraintViolationException;
  40. use Doctrine\DBAL\Platforms\MySqlPlatform;
  41. use Doctrine\DBAL\Schema\Schema;
  42. use OC\DB\QueryBuilder\QueryBuilder;
  43. use OCP\DB\QueryBuilder\IQueryBuilder;
  44. use OCP\IDBConnection;
  45. use OCP\PreConditionNotMetException;
  46. class Connection extends ReconnectWrapper implements IDBConnection {
  47. /**
  48. * @var string $tablePrefix
  49. */
  50. protected $tablePrefix;
  51. /**
  52. * @var \OC\DB\Adapter $adapter
  53. */
  54. protected $adapter;
  55. protected $lockedTable = null;
  56. public function connect() {
  57. try {
  58. return parent::connect();
  59. } catch (DBALException $e) {
  60. // throw a new exception to prevent leaking info from the stacktrace
  61. throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
  62. }
  63. }
  64. /**
  65. * Returns a QueryBuilder for the connection.
  66. *
  67. * @return \OCP\DB\QueryBuilder\IQueryBuilder
  68. */
  69. public function getQueryBuilder() {
  70. return new QueryBuilder(
  71. $this,
  72. \OC::$server->getSystemConfig(),
  73. \OC::$server->getLogger()
  74. );
  75. }
  76. /**
  77. * Gets the QueryBuilder for the connection.
  78. *
  79. * @return \Doctrine\DBAL\Query\QueryBuilder
  80. * @deprecated please use $this->getQueryBuilder() instead
  81. */
  82. public function createQueryBuilder() {
  83. $backtrace = $this->getCallerBacktrace();
  84. \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  85. return parent::createQueryBuilder();
  86. }
  87. /**
  88. * Gets the ExpressionBuilder for the connection.
  89. *
  90. * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
  91. * @deprecated please use $this->getQueryBuilder()->expr() instead
  92. */
  93. public function getExpressionBuilder() {
  94. $backtrace = $this->getCallerBacktrace();
  95. \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  96. return parent::getExpressionBuilder();
  97. }
  98. /**
  99. * Get the file and line that called the method where `getCallerBacktrace()` was used
  100. *
  101. * @return string
  102. */
  103. protected function getCallerBacktrace() {
  104. $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  105. // 0 is the method where we use `getCallerBacktrace`
  106. // 1 is the target method which uses the method we want to log
  107. if (isset($traces[1])) {
  108. return $traces[1]['file'] . ':' . $traces[1]['line'];
  109. }
  110. return '';
  111. }
  112. /**
  113. * @return string
  114. */
  115. public function getPrefix() {
  116. return $this->tablePrefix;
  117. }
  118. /**
  119. * Initializes a new instance of the Connection class.
  120. *
  121. * @param array $params The connection parameters.
  122. * @param \Doctrine\DBAL\Driver $driver
  123. * @param \Doctrine\DBAL\Configuration $config
  124. * @param \Doctrine\Common\EventManager $eventManager
  125. * @throws \Exception
  126. */
  127. public function __construct(array $params, Driver $driver, Configuration $config = null,
  128. EventManager $eventManager = null)
  129. {
  130. if (!isset($params['adapter'])) {
  131. throw new \Exception('adapter not set');
  132. }
  133. if (!isset($params['tablePrefix'])) {
  134. throw new \Exception('tablePrefix not set');
  135. }
  136. parent::__construct($params, $driver, $config, $eventManager);
  137. $this->adapter = new $params['adapter']($this);
  138. $this->tablePrefix = $params['tablePrefix'];
  139. }
  140. /**
  141. * Prepares an SQL statement.
  142. *
  143. * @param string $statement The SQL statement to prepare.
  144. * @param int $limit
  145. * @param int $offset
  146. * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
  147. */
  148. public function prepare( $statement, $limit=null, $offset=null ) {
  149. if ($limit === -1) {
  150. $limit = null;
  151. }
  152. if (!is_null($limit)) {
  153. $platform = $this->getDatabasePlatform();
  154. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  155. }
  156. $statement = $this->replaceTablePrefix($statement);
  157. $statement = $this->adapter->fixupStatement($statement);
  158. return parent::prepare($statement);
  159. }
  160. /**
  161. * Executes an, optionally parametrized, SQL query.
  162. *
  163. * If the query is parametrized, a prepared statement is used.
  164. * If an SQLLogger is configured, the execution is logged.
  165. *
  166. * @param string $query The SQL query to execute.
  167. * @param array $params The parameters to bind to the query, if any.
  168. * @param array $types The types the previous parameters are in.
  169. * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
  170. *
  171. * @return \Doctrine\DBAL\Driver\Statement The executed statement.
  172. *
  173. * @throws \Doctrine\DBAL\DBALException
  174. */
  175. public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null)
  176. {
  177. $query = $this->replaceTablePrefix($query);
  178. $query = $this->adapter->fixupStatement($query);
  179. return parent::executeQuery($query, $params, $types, $qcp);
  180. }
  181. /**
  182. * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
  183. * and returns the number of affected rows.
  184. *
  185. * This method supports PDO binding types as well as DBAL mapping types.
  186. *
  187. * @param string $query The SQL query.
  188. * @param array $params The query parameters.
  189. * @param array $types The parameter types.
  190. *
  191. * @return integer The number of affected rows.
  192. *
  193. * @throws \Doctrine\DBAL\DBALException
  194. */
  195. public function executeUpdate($query, array $params = [], array $types = [])
  196. {
  197. $query = $this->replaceTablePrefix($query);
  198. $query = $this->adapter->fixupStatement($query);
  199. return parent::executeUpdate($query, $params, $types);
  200. }
  201. /**
  202. * Returns the ID of the last inserted row, or the last value from a sequence object,
  203. * depending on the underlying driver.
  204. *
  205. * Note: This method may not return a meaningful or consistent result across different drivers,
  206. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  207. * columns or sequences.
  208. *
  209. * @param string $seqName Name of the sequence object from which the ID should be returned.
  210. * @return string A string representation of the last inserted ID.
  211. */
  212. public function lastInsertId($seqName = null) {
  213. if ($seqName) {
  214. $seqName = $this->replaceTablePrefix($seqName);
  215. }
  216. return $this->adapter->lastInsertId($seqName);
  217. }
  218. // internal use
  219. public function realLastInsertId($seqName = null) {
  220. return parent::lastInsertId($seqName);
  221. }
  222. /**
  223. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  224. * it is needed that there is also a unique constraint on the values. Then this method will
  225. * catch the exception and return 0.
  226. *
  227. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  228. * @param array $input data that should be inserted into the table (column name => value)
  229. * @param array|null $compare List of values that should be checked for "if not exists"
  230. * If this is null or an empty array, all keys of $input will be compared
  231. * Please note: text fields (clob) must not be used in the compare array
  232. * @return int number of inserted rows
  233. * @throws \Doctrine\DBAL\DBALException
  234. * @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
  235. */
  236. public function insertIfNotExist($table, $input, array $compare = null) {
  237. return $this->adapter->insertIfNotExist($table, $input, $compare);
  238. }
  239. public function insertIgnoreConflict(string $table, array $values) : int {
  240. return $this->adapter->insertIgnoreConflict($table, $values);
  241. }
  242. private function getType($value) {
  243. if (is_bool($value)) {
  244. return IQueryBuilder::PARAM_BOOL;
  245. } else if (is_int($value)) {
  246. return IQueryBuilder::PARAM_INT;
  247. } else {
  248. return IQueryBuilder::PARAM_STR;
  249. }
  250. }
  251. /**
  252. * Insert or update a row value
  253. *
  254. * @param string $table
  255. * @param array $keys (column name => value)
  256. * @param array $values (column name => value)
  257. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  258. * @return int number of new rows
  259. * @throws \Doctrine\DBAL\DBALException
  260. * @throws PreConditionNotMetException
  261. * @suppress SqlInjectionChecker
  262. */
  263. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  264. try {
  265. $insertQb = $this->getQueryBuilder();
  266. $insertQb->insert($table)
  267. ->values(
  268. array_map(function($value) use ($insertQb) {
  269. return $insertQb->createNamedParameter($value, $this->getType($value));
  270. }, array_merge($keys, $values))
  271. );
  272. return $insertQb->execute();
  273. } catch (ConstraintViolationException $e) {
  274. // value already exists, try update
  275. $updateQb = $this->getQueryBuilder();
  276. $updateQb->update($table);
  277. foreach ($values as $name => $value) {
  278. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  279. }
  280. $where = $updateQb->expr()->andX();
  281. $whereValues = array_merge($keys, $updatePreconditionValues);
  282. foreach ($whereValues as $name => $value) {
  283. $where->add($updateQb->expr()->eq(
  284. $name,
  285. $updateQb->createNamedParameter($value, $this->getType($value)),
  286. $this->getType($value)
  287. ));
  288. }
  289. $updateQb->where($where);
  290. $affected = $updateQb->execute();
  291. if ($affected === 0 && !empty($updatePreconditionValues)) {
  292. throw new PreConditionNotMetException();
  293. }
  294. return 0;
  295. }
  296. }
  297. /**
  298. * Create an exclusive read+write lock on a table
  299. *
  300. * @param string $tableName
  301. * @throws \BadMethodCallException When trying to acquire a second lock
  302. * @since 9.1.0
  303. */
  304. public function lockTable($tableName) {
  305. if ($this->lockedTable !== null) {
  306. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  307. }
  308. $tableName = $this->tablePrefix . $tableName;
  309. $this->lockedTable = $tableName;
  310. $this->adapter->lockTable($tableName);
  311. }
  312. /**
  313. * Release a previous acquired lock again
  314. *
  315. * @since 9.1.0
  316. */
  317. public function unlockTable() {
  318. $this->adapter->unlockTable();
  319. $this->lockedTable = null;
  320. }
  321. /**
  322. * returns the error code and message as a string for logging
  323. * works with DoctrineException
  324. * @return string
  325. */
  326. public function getError() {
  327. $msg = $this->errorCode() . ': ';
  328. $errorInfo = $this->errorInfo();
  329. if (is_array($errorInfo)) {
  330. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  331. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  332. $msg .= 'Driver Message = '.$errorInfo[2];
  333. }
  334. return $msg;
  335. }
  336. /**
  337. * Drop a table from the database if it exists
  338. *
  339. * @param string $table table name without the prefix
  340. */
  341. public function dropTable($table) {
  342. $table = $this->tablePrefix . trim($table);
  343. $schema = $this->getSchemaManager();
  344. if($schema->tablesExist([$table])) {
  345. $schema->dropTable($table);
  346. }
  347. }
  348. /**
  349. * Check if a table exists
  350. *
  351. * @param string $table table name without the prefix
  352. * @return bool
  353. */
  354. public function tableExists($table){
  355. $table = $this->tablePrefix . trim($table);
  356. $schema = $this->getSchemaManager();
  357. return $schema->tablesExist([$table]);
  358. }
  359. // internal use
  360. /**
  361. * @param string $statement
  362. * @return string
  363. */
  364. protected function replaceTablePrefix($statement) {
  365. return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
  366. }
  367. /**
  368. * Check if a transaction is active
  369. *
  370. * @return bool
  371. * @since 8.2.0
  372. */
  373. public function inTransaction() {
  374. return $this->getTransactionNestingLevel() > 0;
  375. }
  376. /**
  377. * Escape a parameter to be used in a LIKE query
  378. *
  379. * @param string $param
  380. * @return string
  381. */
  382. public function escapeLikeParameter($param) {
  383. return addcslashes($param, '\\_%');
  384. }
  385. /**
  386. * Check whether or not the current database support 4byte wide unicode
  387. *
  388. * @return bool
  389. * @since 11.0.0
  390. */
  391. public function supports4ByteText() {
  392. if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
  393. return true;
  394. }
  395. return $this->getParams()['charset'] === 'utf8mb4';
  396. }
  397. /**
  398. * Create the schema of the connected database
  399. *
  400. * @return Schema
  401. */
  402. public function createSchema() {
  403. $schemaManager = new MDB2SchemaManager($this);
  404. $migrator = $schemaManager->getMigrator();
  405. return $migrator->createSchema();
  406. }
  407. /**
  408. * Migrate the database to the given schema
  409. *
  410. * @param Schema $toSchema
  411. */
  412. public function migrateToSchema(Schema $toSchema) {
  413. $schemaManager = new MDB2SchemaManager($this);
  414. $migrator = $schemaManager->getMigrator();
  415. $migrator->migrate($toSchema);
  416. }
  417. }