Connection.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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.
  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. * @suppress SqlInjectionChecker
  254. */
  255. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  256. try {
  257. $insertQb = $this->getQueryBuilder();
  258. $insertQb->insert($table)
  259. ->values(
  260. array_map(function($value) use ($insertQb) {
  261. return $insertQb->createNamedParameter($value, $this->getType($value));
  262. }, array_merge($keys, $values))
  263. );
  264. return $insertQb->execute();
  265. } catch (ConstraintViolationException $e) {
  266. // value already exists, try update
  267. $updateQb = $this->getQueryBuilder();
  268. $updateQb->update($table);
  269. foreach ($values as $name => $value) {
  270. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  271. }
  272. $where = $updateQb->expr()->andX();
  273. $whereValues = array_merge($keys, $updatePreconditionValues);
  274. foreach ($whereValues as $name => $value) {
  275. $where->add($updateQb->expr()->eq(
  276. $name,
  277. $updateQb->createNamedParameter($value, $this->getType($value)),
  278. $this->getType($value)
  279. ));
  280. }
  281. $updateQb->where($where);
  282. $affected = $updateQb->execute();
  283. if ($affected === 0 && !empty($updatePreconditionValues)) {
  284. throw new PreConditionNotMetException();
  285. }
  286. return 0;
  287. }
  288. }
  289. /**
  290. * Create an exclusive read+write lock on a table
  291. *
  292. * @param string $tableName
  293. * @throws \BadMethodCallException When trying to acquire a second lock
  294. * @since 9.1.0
  295. */
  296. public function lockTable($tableName) {
  297. if ($this->lockedTable !== null) {
  298. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  299. }
  300. $tableName = $this->tablePrefix . $tableName;
  301. $this->lockedTable = $tableName;
  302. $this->adapter->lockTable($tableName);
  303. }
  304. /**
  305. * Release a previous acquired lock again
  306. *
  307. * @since 9.1.0
  308. */
  309. public function unlockTable() {
  310. $this->adapter->unlockTable();
  311. $this->lockedTable = null;
  312. }
  313. /**
  314. * returns the error code and message as a string for logging
  315. * works with DoctrineException
  316. * @return string
  317. */
  318. public function getError() {
  319. $msg = $this->errorCode() . ': ';
  320. $errorInfo = $this->errorInfo();
  321. if (is_array($errorInfo)) {
  322. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  323. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  324. $msg .= 'Driver Message = '.$errorInfo[2];
  325. }
  326. return $msg;
  327. }
  328. /**
  329. * Drop a table from the database if it exists
  330. *
  331. * @param string $table table name without the prefix
  332. */
  333. public function dropTable($table) {
  334. $table = $this->tablePrefix . trim($table);
  335. $schema = $this->getSchemaManager();
  336. if($schema->tablesExist(array($table))) {
  337. $schema->dropTable($table);
  338. }
  339. }
  340. /**
  341. * Check if a table exists
  342. *
  343. * @param string $table table name without the prefix
  344. * @return bool
  345. */
  346. public function tableExists($table){
  347. $table = $this->tablePrefix . trim($table);
  348. $schema = $this->getSchemaManager();
  349. return $schema->tablesExist(array($table));
  350. }
  351. // internal use
  352. /**
  353. * @param string $statement
  354. * @return string
  355. */
  356. protected function replaceTablePrefix($statement) {
  357. return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
  358. }
  359. /**
  360. * Check if a transaction is active
  361. *
  362. * @return bool
  363. * @since 8.2.0
  364. */
  365. public function inTransaction() {
  366. return $this->getTransactionNestingLevel() > 0;
  367. }
  368. /**
  369. * Escape a parameter to be used in a LIKE query
  370. *
  371. * @param string $param
  372. * @return string
  373. */
  374. public function escapeLikeParameter($param) {
  375. return addcslashes($param, '\\_%');
  376. }
  377. /**
  378. * Check whether or not the current database support 4byte wide unicode
  379. *
  380. * @return bool
  381. * @since 11.0.0
  382. */
  383. public function supports4ByteText() {
  384. if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
  385. return true;
  386. }
  387. return $this->getParams()['charset'] === 'utf8mb4';
  388. }
  389. /**
  390. * Create the schema of the connected database
  391. *
  392. * @return Schema
  393. */
  394. public function createSchema() {
  395. $schemaManager = new MDB2SchemaManager($this);
  396. $migrator = $schemaManager->getMigrator();
  397. return $migrator->createSchema();
  398. }
  399. /**
  400. * Migrate the database to the given schema
  401. *
  402. * @param Schema $toSchema
  403. */
  404. public function migrateToSchema(Schema $toSchema) {
  405. $schemaManager = new MDB2SchemaManager($this);
  406. $migrator = $schemaManager->getMigrator();
  407. $migrator->migrate($toSchema);
  408. }
  409. }