1
0

Connection.php 14 KB

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