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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Robin McCorkell <robin@mccorkell.me.uk>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\DB;
  29. use Doctrine\DBAL\DBALException;
  30. use Doctrine\DBAL\Driver;
  31. use Doctrine\DBAL\Configuration;
  32. use Doctrine\DBAL\Cache\QueryCacheProfile;
  33. use Doctrine\Common\EventManager;
  34. use Doctrine\DBAL\Platforms\MySqlPlatform;
  35. use Doctrine\DBAL\Exception\ConstraintViolationException;
  36. use OC\DB\QueryBuilder\QueryBuilder;
  37. use OCP\DB\QueryBuilder\IQueryBuilder;
  38. use OCP\IDBConnection;
  39. use OCP\PreConditionNotMetException;
  40. class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
  41. /**
  42. * @var string $tablePrefix
  43. */
  44. protected $tablePrefix;
  45. /**
  46. * @var \OC\DB\Adapter $adapter
  47. */
  48. protected $adapter;
  49. protected $lockedTable = null;
  50. public function connect() {
  51. try {
  52. return parent::connect();
  53. } catch (DBALException $e) {
  54. // throw a new exception to prevent leaking info from the stacktrace
  55. throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
  56. }
  57. }
  58. /**
  59. * Returns a QueryBuilder for the connection.
  60. *
  61. * @return \OCP\DB\QueryBuilder\IQueryBuilder
  62. */
  63. public function getQueryBuilder() {
  64. return new QueryBuilder(
  65. $this,
  66. \OC::$server->getSystemConfig(),
  67. \OC::$server->getLogger()
  68. );
  69. }
  70. /**
  71. * Gets the QueryBuilder for the connection.
  72. *
  73. * @return \Doctrine\DBAL\Query\QueryBuilder
  74. * @deprecated please use $this->getQueryBuilder() instead
  75. */
  76. public function createQueryBuilder() {
  77. $backtrace = $this->getCallerBacktrace();
  78. \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  79. return parent::createQueryBuilder();
  80. }
  81. /**
  82. * Gets the ExpressionBuilder for the connection.
  83. *
  84. * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
  85. * @deprecated please use $this->getQueryBuilder()->expr() instead
  86. */
  87. public function getExpressionBuilder() {
  88. $backtrace = $this->getCallerBacktrace();
  89. \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  90. return parent::getExpressionBuilder();
  91. }
  92. /**
  93. * Get the file and line that called the method where `getCallerBacktrace()` was used
  94. *
  95. * @return string
  96. */
  97. protected function getCallerBacktrace() {
  98. $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  99. // 0 is the method where we use `getCallerBacktrace`
  100. // 1 is the target method which uses the method we want to log
  101. if (isset($traces[1])) {
  102. return $traces[1]['file'] . ':' . $traces[1]['line'];
  103. }
  104. return '';
  105. }
  106. /**
  107. * @return string
  108. */
  109. public function getPrefix() {
  110. return $this->tablePrefix;
  111. }
  112. /**
  113. * Initializes a new instance of the Connection class.
  114. *
  115. * @param array $params The connection parameters.
  116. * @param \Doctrine\DBAL\Driver $driver
  117. * @param \Doctrine\DBAL\Configuration $config
  118. * @param \Doctrine\Common\EventManager $eventManager
  119. * @throws \Exception
  120. */
  121. public function __construct(array $params, Driver $driver, Configuration $config = null,
  122. EventManager $eventManager = null)
  123. {
  124. if (!isset($params['adapter'])) {
  125. throw new \Exception('adapter not set');
  126. }
  127. if (!isset($params['tablePrefix'])) {
  128. throw new \Exception('tablePrefix not set');
  129. }
  130. parent::__construct($params, $driver, $config, $eventManager);
  131. $this->adapter = new $params['adapter']($this);
  132. $this->tablePrefix = $params['tablePrefix'];
  133. parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
  134. }
  135. /**
  136. * Prepares an SQL statement.
  137. *
  138. * @param string $statement The SQL statement to prepare.
  139. * @param int $limit
  140. * @param int $offset
  141. * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
  142. */
  143. public function prepare( $statement, $limit=null, $offset=null ) {
  144. if ($limit === -1) {
  145. $limit = null;
  146. }
  147. if (!is_null($limit)) {
  148. $platform = $this->getDatabasePlatform();
  149. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  150. }
  151. $statement = $this->replaceTablePrefix($statement);
  152. $statement = $this->adapter->fixupStatement($statement);
  153. if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
  154. \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
  155. }
  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.
  222. *
  223. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  224. * @param array $input data that should be inserted into the table (column name => value)
  225. * @param array|null $compare List of values that should be checked for "if not exists"
  226. * If this is null or an empty array, all keys of $input will be compared
  227. * Please note: text fields (clob) must not be used in the compare array
  228. * @return int number of inserted rows
  229. * @throws \Doctrine\DBAL\DBALException
  230. */
  231. public function insertIfNotExist($table, $input, array $compare = null) {
  232. return $this->adapter->insertIfNotExist($table, $input, $compare);
  233. }
  234. private function getType($value) {
  235. if (is_bool($value)) {
  236. return IQueryBuilder::PARAM_BOOL;
  237. } else if (is_int($value)) {
  238. return IQueryBuilder::PARAM_INT;
  239. } else {
  240. return IQueryBuilder::PARAM_STR;
  241. }
  242. }
  243. /**
  244. * Insert or update a row value
  245. *
  246. * @param string $table
  247. * @param array $keys (column name => value)
  248. * @param array $values (column name => value)
  249. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  250. * @return int number of new rows
  251. * @throws \Doctrine\DBAL\DBALException
  252. * @throws PreConditionNotMetException
  253. */
  254. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  255. try {
  256. $insertQb = $this->getQueryBuilder();
  257. $insertQb->insert($table)
  258. ->values(
  259. array_map(function($value) use ($insertQb) {
  260. return $insertQb->createNamedParameter($value, $this->getType($value));
  261. }, array_merge($keys, $values))
  262. );
  263. return $insertQb->execute();
  264. } catch (ConstraintViolationException $e) {
  265. // value already exists, try update
  266. $updateQb = $this->getQueryBuilder();
  267. $updateQb->update($table);
  268. foreach ($values as $name => $value) {
  269. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  270. }
  271. $where = $updateQb->expr()->andX();
  272. $whereValues = array_merge($keys, $updatePreconditionValues);
  273. foreach ($whereValues as $name => $value) {
  274. $where->add($updateQb->expr()->eq(
  275. $name,
  276. $updateQb->createNamedParameter($value, $this->getType($value)),
  277. $this->getType($value)
  278. ));
  279. }
  280. $updateQb->where($where);
  281. $affected = $updateQb->execute();
  282. if ($affected === 0 && !empty($updatePreconditionValues)) {
  283. throw new PreConditionNotMetException();
  284. }
  285. return 0;
  286. }
  287. }
  288. /**
  289. * Create an exclusive read+write lock on a table
  290. *
  291. * @param string $tableName
  292. * @throws \BadMethodCallException When trying to acquire a second lock
  293. * @since 9.1.0
  294. */
  295. public function lockTable($tableName) {
  296. if ($this->lockedTable !== null) {
  297. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  298. }
  299. $tableName = $this->tablePrefix . $tableName;
  300. $this->lockedTable = $tableName;
  301. $this->adapter->lockTable($tableName);
  302. }
  303. /**
  304. * Release a previous acquired lock again
  305. *
  306. * @since 9.1.0
  307. */
  308. public function unlockTable() {
  309. $this->adapter->unlockTable();
  310. $this->lockedTable = null;
  311. }
  312. /**
  313. * returns the error code and message as a string for logging
  314. * works with DoctrineException
  315. * @return string
  316. */
  317. public function getError() {
  318. $msg = $this->errorCode() . ': ';
  319. $errorInfo = $this->errorInfo();
  320. if (is_array($errorInfo)) {
  321. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  322. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  323. $msg .= 'Driver Message = '.$errorInfo[2];
  324. }
  325. return $msg;
  326. }
  327. /**
  328. * Drop a table from the database if it exists
  329. *
  330. * @param string $table table name without the prefix
  331. */
  332. public function dropTable($table) {
  333. $table = $this->tablePrefix . trim($table);
  334. $schema = $this->getSchemaManager();
  335. if($schema->tablesExist(array($table))) {
  336. $schema->dropTable($table);
  337. }
  338. }
  339. /**
  340. * Check if a table exists
  341. *
  342. * @param string $table table name without the prefix
  343. * @return bool
  344. */
  345. public function tableExists($table){
  346. $table = $this->tablePrefix . trim($table);
  347. $schema = $this->getSchemaManager();
  348. return $schema->tablesExist(array($table));
  349. }
  350. // internal use
  351. /**
  352. * @param string $statement
  353. * @return string
  354. */
  355. protected function replaceTablePrefix($statement) {
  356. return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
  357. }
  358. /**
  359. * Check if a transaction is active
  360. *
  361. * @return bool
  362. * @since 8.2.0
  363. */
  364. public function inTransaction() {
  365. return $this->getTransactionNestingLevel() > 0;
  366. }
  367. /**
  368. * Espace a parameter to be used in a LIKE query
  369. *
  370. * @param string $param
  371. * @return string
  372. */
  373. public function escapeLikeParameter($param) {
  374. return addcslashes($param, '\\_%');
  375. }
  376. /**
  377. * Check whether or not the current database support 4byte wide unicode
  378. *
  379. * @return bool
  380. * @since 11.0.0
  381. */
  382. public function supports4ByteText() {
  383. return ! ($this->getDatabasePlatform() instanceof MySqlPlatform && $this->getParams()['charset'] !== 'utf8mb4');
  384. }
  385. }