connection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 Thomas Müller <thomas.mueller@tmit.eu>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\DB;
  28. use Doctrine\DBAL\DBALException;
  29. use Doctrine\DBAL\Driver;
  30. use Doctrine\DBAL\Configuration;
  31. use Doctrine\DBAL\Cache\QueryCacheProfile;
  32. use Doctrine\Common\EventManager;
  33. use OC\DB\QueryBuilder\QueryBuilder;
  34. use OCP\DB\QueryBuilder\IQueryBuilder;
  35. use OCP\IDBConnection;
  36. use OCP\PreconditionNotMetException;
  37. class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
  38. /**
  39. * @var string $tablePrefix
  40. */
  41. protected $tablePrefix;
  42. /**
  43. * @var \OC\DB\Adapter $adapter
  44. */
  45. protected $adapter;
  46. public function connect() {
  47. try {
  48. return parent::connect();
  49. } catch (DBALException $e) {
  50. // throw a new exception to prevent leaking info from the stacktrace
  51. throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
  52. }
  53. }
  54. /**
  55. * Returns a QueryBuilder for the connection.
  56. *
  57. * @return \OCP\DB\QueryBuilder\IQueryBuilder
  58. */
  59. public function getQueryBuilder() {
  60. return new QueryBuilder($this);
  61. }
  62. /**
  63. * Gets the QueryBuilder for the connection.
  64. *
  65. * @return \Doctrine\DBAL\Query\QueryBuilder
  66. * @deprecated please use $this->getQueryBuilder() instead
  67. */
  68. public function createQueryBuilder() {
  69. $backtrace = $this->getCallerBacktrace();
  70. \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  71. return parent::createQueryBuilder();
  72. }
  73. /**
  74. * Gets the ExpressionBuilder for the connection.
  75. *
  76. * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
  77. * @deprecated please use $this->getQueryBuilder()->expr() instead
  78. */
  79. public function getExpressionBuilder() {
  80. $backtrace = $this->getCallerBacktrace();
  81. \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
  82. return parent::getExpressionBuilder();
  83. }
  84. /**
  85. * Get the file and line that called the method where `getCallerBacktrace()` was used
  86. *
  87. * @return string
  88. */
  89. protected function getCallerBacktrace() {
  90. $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  91. // 0 is the method where we use `getCallerBacktrace`
  92. // 1 is the target method which uses the method we want to log
  93. if (isset($traces[1])) {
  94. return $traces[1]['file'] . ':' . $traces[1]['line'];
  95. }
  96. return '';
  97. }
  98. /**
  99. * @return string
  100. */
  101. public function getPrefix() {
  102. return $this->tablePrefix;
  103. }
  104. /**
  105. * Initializes a new instance of the Connection class.
  106. *
  107. * @param array $params The connection parameters.
  108. * @param \Doctrine\DBAL\Driver $driver
  109. * @param \Doctrine\DBAL\Configuration $config
  110. * @param \Doctrine\Common\EventManager $eventManager
  111. * @throws \Exception
  112. */
  113. public function __construct(array $params, Driver $driver, Configuration $config = null,
  114. EventManager $eventManager = null)
  115. {
  116. if (!isset($params['adapter'])) {
  117. throw new \Exception('adapter not set');
  118. }
  119. if (!isset($params['tablePrefix'])) {
  120. throw new \Exception('tablePrefix not set');
  121. }
  122. parent::__construct($params, $driver, $config, $eventManager);
  123. $this->adapter = new $params['adapter']($this);
  124. $this->tablePrefix = $params['tablePrefix'];
  125. parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
  126. }
  127. /**
  128. * Prepares an SQL statement.
  129. *
  130. * @param string $statement The SQL statement to prepare.
  131. * @param int $limit
  132. * @param int $offset
  133. * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
  134. */
  135. public function prepare( $statement, $limit=null, $offset=null ) {
  136. if ($limit === -1) {
  137. $limit = null;
  138. }
  139. if (!is_null($limit)) {
  140. $platform = $this->getDatabasePlatform();
  141. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  142. }
  143. $statement = $this->replaceTablePrefix($statement);
  144. $statement = $this->adapter->fixupStatement($statement);
  145. if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
  146. \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
  147. }
  148. return parent::prepare($statement);
  149. }
  150. /**
  151. * Executes an, optionally parametrized, SQL query.
  152. *
  153. * If the query is parametrized, a prepared statement is used.
  154. * If an SQLLogger is configured, the execution is logged.
  155. *
  156. * @param string $query The SQL query to execute.
  157. * @param array $params The parameters to bind to the query, if any.
  158. * @param array $types The types the previous parameters are in.
  159. * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
  160. *
  161. * @return \Doctrine\DBAL\Driver\Statement The executed statement.
  162. *
  163. * @throws \Doctrine\DBAL\DBALException
  164. */
  165. public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
  166. {
  167. $query = $this->replaceTablePrefix($query);
  168. $query = $this->adapter->fixupStatement($query);
  169. return parent::executeQuery($query, $params, $types, $qcp);
  170. }
  171. /**
  172. * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
  173. * and returns the number of affected rows.
  174. *
  175. * This method supports PDO binding types as well as DBAL mapping types.
  176. *
  177. * @param string $query The SQL query.
  178. * @param array $params The query parameters.
  179. * @param array $types The parameter types.
  180. *
  181. * @return integer The number of affected rows.
  182. *
  183. * @throws \Doctrine\DBAL\DBALException
  184. */
  185. public function executeUpdate($query, array $params = array(), array $types = array())
  186. {
  187. $query = $this->replaceTablePrefix($query);
  188. $query = $this->adapter->fixupStatement($query);
  189. return parent::executeUpdate($query, $params, $types);
  190. }
  191. /**
  192. * Returns the ID of the last inserted row, or the last value from a sequence object,
  193. * depending on the underlying driver.
  194. *
  195. * Note: This method may not return a meaningful or consistent result across different drivers,
  196. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  197. * columns or sequences.
  198. *
  199. * @param string $seqName Name of the sequence object from which the ID should be returned.
  200. * @return string A string representation of the last inserted ID.
  201. */
  202. public function lastInsertId($seqName = null) {
  203. if ($seqName) {
  204. $seqName = $this->replaceTablePrefix($seqName);
  205. }
  206. return $this->adapter->lastInsertId($seqName);
  207. }
  208. // internal use
  209. public function realLastInsertId($seqName = null) {
  210. return parent::lastInsertId($seqName);
  211. }
  212. /**
  213. * Insert a row if the matching row does not exists.
  214. *
  215. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  216. * @param array $input data that should be inserted into the table (column name => value)
  217. * @param array|null $compare List of values that should be checked for "if not exists"
  218. * If this is null or an empty array, all keys of $input will be compared
  219. * Please note: text fields (clob) must not be used in the compare array
  220. * @return int number of inserted rows
  221. * @throws \Doctrine\DBAL\DBALException
  222. */
  223. public function insertIfNotExist($table, $input, array $compare = null) {
  224. return $this->adapter->insertIfNotExist($table, $input, $compare);
  225. }
  226. private function getType($value) {
  227. if (is_bool($value)) {
  228. return IQueryBuilder::PARAM_BOOL;
  229. } else if (is_int($value)) {
  230. return IQueryBuilder::PARAM_INT;
  231. } else {
  232. return IQueryBuilder::PARAM_STR;
  233. }
  234. }
  235. /**
  236. * Insert or update a row value
  237. *
  238. * @param string $table
  239. * @param array $keys (column name => value)
  240. * @param array $values (column name => value)
  241. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  242. * @return int number of new rows
  243. * @throws \Doctrine\DBAL\DBALException
  244. * @throws PreconditionNotMetException
  245. */
  246. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  247. try {
  248. $insertQb = $this->getQueryBuilder();
  249. $insertQb->insert($table)
  250. ->values(
  251. array_map(function($value) use ($insertQb) {
  252. return $insertQb->createNamedParameter($value, $this->getType($value));
  253. }, array_merge($keys, $values))
  254. );
  255. return $insertQb->execute();
  256. } catch (\Doctrine\DBAL\Exception\ConstraintViolationException $e) {
  257. // value already exists, try update
  258. $updateQb = $this->getQueryBuilder();
  259. $updateQb->update($table);
  260. foreach ($values as $name => $value) {
  261. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  262. }
  263. $where = $updateQb->expr()->andx();
  264. $whereValues = array_merge($keys, $updatePreconditionValues);
  265. foreach ($whereValues as $name => $value) {
  266. $where->add($updateQb->expr()->eq(
  267. $name,
  268. $updateQb->createNamedParameter($value, $this->getType($value)),
  269. $this->getType($value)
  270. ));
  271. }
  272. $updateQb->where($where);
  273. $affected = $updateQb->execute();
  274. if ($affected === 0 && !empty($updatePreconditionValues)) {
  275. throw new PreconditionNotMetException();
  276. }
  277. return 0;
  278. }
  279. }
  280. /**
  281. * returns the error code and message as a string for logging
  282. * works with DoctrineException
  283. * @return string
  284. */
  285. public function getError() {
  286. $msg = $this->errorCode() . ': ';
  287. $errorInfo = $this->errorInfo();
  288. if (is_array($errorInfo)) {
  289. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  290. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  291. $msg .= 'Driver Message = '.$errorInfo[2];
  292. }
  293. return $msg;
  294. }
  295. /**
  296. * Drop a table from the database if it exists
  297. *
  298. * @param string $table table name without the prefix
  299. */
  300. public function dropTable($table) {
  301. $table = $this->tablePrefix . trim($table);
  302. $schema = $this->getSchemaManager();
  303. if($schema->tablesExist(array($table))) {
  304. $schema->dropTable($table);
  305. }
  306. }
  307. /**
  308. * Check if a table exists
  309. *
  310. * @param string $table table name without the prefix
  311. * @return bool
  312. */
  313. public function tableExists($table){
  314. $table = $this->tablePrefix . trim($table);
  315. $schema = $this->getSchemaManager();
  316. return $schema->tablesExist(array($table));
  317. }
  318. // internal use
  319. /**
  320. * @param string $statement
  321. * @return string
  322. */
  323. protected function replaceTablePrefix($statement) {
  324. return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
  325. }
  326. /**
  327. * Check if a transaction is active
  328. *
  329. * @return bool
  330. * @since 8.2.0
  331. */
  332. public function inTransaction() {
  333. return $this->getTransactionNestingLevel() > 0;
  334. }
  335. /**
  336. * Espace a parameter to be used in a LIKE query
  337. *
  338. * @param string $param
  339. * @return string
  340. */
  341. public function escapeLikeParameter($param) {
  342. return addcslashes($param, '\\_%');
  343. }
  344. }