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.

452 lines
14 KiB

3 years ago
  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. if (!isset($params['adapter'])) {
  130. throw new \Exception('adapter not set');
  131. }
  132. if (!isset($params['tablePrefix'])) {
  133. throw new \Exception('tablePrefix not set');
  134. }
  135. parent::__construct($params, $driver, $config, $eventManager);
  136. $this->adapter = new $params['adapter']($this);
  137. $this->tablePrefix = $params['tablePrefix'];
  138. }
  139. /**
  140. * Prepares an SQL statement.
  141. *
  142. * @param string $statement The SQL statement to prepare.
  143. * @param int $limit
  144. * @param int $offset
  145. * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
  146. */
  147. public function prepare($statement, $limit=null, $offset=null) {
  148. if ($limit === -1) {
  149. $limit = null;
  150. }
  151. if (!is_null($limit)) {
  152. $platform = $this->getDatabasePlatform();
  153. $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
  154. }
  155. $statement = $this->replaceTablePrefix($statement);
  156. $statement = $this->adapter->fixupStatement($statement);
  157. return parent::prepare($statement);
  158. }
  159. /**
  160. * Executes an, optionally parametrized, SQL query.
  161. *
  162. * If the query is parametrized, a prepared statement is used.
  163. * If an SQLLogger is configured, the execution is logged.
  164. *
  165. * @param string $query The SQL query to execute.
  166. * @param array $params The parameters to bind to the query, if any.
  167. * @param array $types The types the previous parameters are in.
  168. * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
  169. *
  170. * @return \Doctrine\DBAL\Driver\Statement The executed statement.
  171. *
  172. * @throws \Doctrine\DBAL\DBALException
  173. */
  174. public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) {
  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 $types = []) {
  194. $query = $this->replaceTablePrefix($query);
  195. $query = $this->adapter->fixupStatement($query);
  196. return parent::executeUpdate($query, $params, $types);
  197. }
  198. /**
  199. * Returns the ID of the last inserted row, or the last value from a sequence object,
  200. * depending on the underlying driver.
  201. *
  202. * Note: This method may not return a meaningful or consistent result across different drivers,
  203. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  204. * columns or sequences.
  205. *
  206. * @param string $seqName Name of the sequence object from which the ID should be returned.
  207. * @return string A string representation of the last inserted ID.
  208. */
  209. public function lastInsertId($seqName = null) {
  210. if ($seqName) {
  211. $seqName = $this->replaceTablePrefix($seqName);
  212. }
  213. return $this->adapter->lastInsertId($seqName);
  214. }
  215. // internal use
  216. public function realLastInsertId($seqName = null) {
  217. return parent::lastInsertId($seqName);
  218. }
  219. /**
  220. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  221. * it is needed that there is also a unique constraint on the values. Then this method will
  222. * catch the exception and return 0.
  223. *
  224. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  225. * @param array $input data that should be inserted into the table (column name => value)
  226. * @param array|null $compare List of values that should be checked for "if not exists"
  227. * If this is null or an empty array, all keys of $input will be compared
  228. * Please note: text fields (clob) must not be used in the compare array
  229. * @return int number of inserted rows
  230. * @throws \Doctrine\DBAL\DBALException
  231. * @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
  232. */
  233. public function insertIfNotExist($table, $input, array $compare = null) {
  234. return $this->adapter->insertIfNotExist($table, $input, $compare);
  235. }
  236. public function insertIgnoreConflict(string $table, array $values) : int {
  237. return $this->adapter->insertIgnoreConflict($table, $values);
  238. }
  239. private function getType($value) {
  240. if (is_bool($value)) {
  241. return IQueryBuilder::PARAM_BOOL;
  242. } elseif (is_int($value)) {
  243. return IQueryBuilder::PARAM_INT;
  244. } else {
  245. return IQueryBuilder::PARAM_STR;
  246. }
  247. }
  248. /**
  249. * Insert or update a row value
  250. *
  251. * @param string $table
  252. * @param array $keys (column name => value)
  253. * @param array $values (column name => value)
  254. * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
  255. * @return int number of new rows
  256. * @throws \Doctrine\DBAL\DBALException
  257. * @throws PreConditionNotMetException
  258. */
  259. public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
  260. try {
  261. $insertQb = $this->getQueryBuilder();
  262. $insertQb->insert($table)
  263. ->values(
  264. array_map(function ($value) use ($insertQb) {
  265. return $insertQb->createNamedParameter($value, $this->getType($value));
  266. }, array_merge($keys, $values))
  267. );
  268. return $insertQb->execute();
  269. } catch (ConstraintViolationException $e) {
  270. // value already exists, try update
  271. $updateQb = $this->getQueryBuilder();
  272. $updateQb->update($table);
  273. foreach ($values as $name => $value) {
  274. $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
  275. }
  276. $where = $updateQb->expr()->andX();
  277. $whereValues = array_merge($keys, $updatePreconditionValues);
  278. foreach ($whereValues as $name => $value) {
  279. $where->add($updateQb->expr()->eq(
  280. $name,
  281. $updateQb->createNamedParameter($value, $this->getType($value)),
  282. $this->getType($value)
  283. ));
  284. }
  285. $updateQb->where($where);
  286. $affected = $updateQb->execute();
  287. if ($affected === 0 && !empty($updatePreconditionValues)) {
  288. throw new PreConditionNotMetException();
  289. }
  290. return 0;
  291. }
  292. }
  293. /**
  294. * Create an exclusive read+write lock on a table
  295. *
  296. * @param string $tableName
  297. * @throws \BadMethodCallException When trying to acquire a second lock
  298. * @since 9.1.0
  299. */
  300. public function lockTable($tableName) {
  301. if ($this->lockedTable !== null) {
  302. throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
  303. }
  304. $tableName = $this->tablePrefix . $tableName;
  305. $this->lockedTable = $tableName;
  306. $this->adapter->lockTable($tableName);
  307. }
  308. /**
  309. * Release a previous acquired lock again
  310. *
  311. * @since 9.1.0
  312. */
  313. public function unlockTable() {
  314. $this->adapter->unlockTable();
  315. $this->lockedTable = null;
  316. }
  317. /**
  318. * returns the error code and message as a string for logging
  319. * works with DoctrineException
  320. * @return string
  321. */
  322. public function getError() {
  323. $msg = $this->errorCode() . ': ';
  324. $errorInfo = $this->errorInfo();
  325. if (is_array($errorInfo)) {
  326. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  327. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  328. $msg .= 'Driver Message = '.$errorInfo[2];
  329. }
  330. return $msg;
  331. }
  332. /**
  333. * Drop a table from the database if it exists
  334. *
  335. * @param string $table table name without the prefix
  336. */
  337. public function dropTable($table) {
  338. $table = $this->tablePrefix . trim($table);
  339. $schema = $this->getSchemaManager();
  340. if ($schema->tablesExist([$table])) {
  341. $schema->dropTable($table);
  342. }
  343. }
  344. /**
  345. * Check if a table exists
  346. *
  347. * @param string $table table name without the prefix
  348. * @return bool
  349. */
  350. public function tableExists($table) {
  351. $table = $this->tablePrefix . trim($table);
  352. $schema = $this->getSchemaManager();
  353. return $schema->tablesExist([$table]);
  354. }
  355. // internal use
  356. /**
  357. * @param string $statement
  358. * @return string
  359. */
  360. protected function replaceTablePrefix($statement) {
  361. return str_replace('*PREFIX*', $this->tablePrefix, $statement);
  362. }
  363. /**
  364. * Check if a transaction is active
  365. *
  366. * @return bool
  367. * @since 8.2.0
  368. */
  369. public function inTransaction() {
  370. return $this->getTransactionNestingLevel() > 0;
  371. }
  372. /**
  373. * Escape a parameter to be used in a LIKE query
  374. *
  375. * @param string $param
  376. * @return string
  377. */
  378. public function escapeLikeParameter($param) {
  379. return addcslashes($param, '\\_%');
  380. }
  381. /**
  382. * Check whether or not the current database support 4byte wide unicode
  383. *
  384. * @return bool
  385. * @since 11.0.0
  386. */
  387. public function supports4ByteText() {
  388. if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
  389. return true;
  390. }
  391. return $this->getParams()['charset'] === 'utf8mb4';
  392. }
  393. /**
  394. * Create the schema of the connected database
  395. *
  396. * @return Schema
  397. */
  398. public function createSchema() {
  399. $schemaManager = new MDB2SchemaManager($this);
  400. $migrator = $schemaManager->getMigrator();
  401. return $migrator->createSchema();
  402. }
  403. /**
  404. * Migrate the database to the given schema
  405. *
  406. * @param Schema $toSchema
  407. */
  408. public function migrateToSchema(Schema $toSchema) {
  409. $schemaManager = new MDB2SchemaManager($this);
  410. $migrator = $schemaManager->getMigrator();
  411. $migrator->migrate($toSchema);
  412. }
  413. }