1
0

db.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  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. use OCP\ILogger;
  31. /**
  32. * This class manages the access to the database. It basically is a wrapper for
  33. * Doctrine with some adaptions.
  34. */
  35. class OC_DB {
  36. /**
  37. * get MDB2 schema manager
  38. *
  39. * @return \OC\DB\MDB2SchemaManager
  40. */
  41. private static function getMDB2SchemaManager() {
  42. return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
  43. }
  44. /**
  45. * Prepare a SQL query
  46. * @param string $query Query string
  47. * @param int|null $limit
  48. * @param int|null $offset
  49. * @param bool|null $isManipulation
  50. * @throws \OC\DatabaseException
  51. * @return OC_DB_StatementWrapper prepared SQL query
  52. *
  53. * SQL query via Doctrine prepare(), needs to be execute()'d!
  54. */
  55. static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
  56. $connection = \OC::$server->getDatabaseConnection();
  57. if ($isManipulation === null) {
  58. //try to guess, so we return the number of rows on manipulations
  59. $isManipulation = self::isManipulation($query);
  60. }
  61. // return the result
  62. try {
  63. $result =$connection->prepare($query, $limit, $offset);
  64. } catch (\Doctrine\DBAL\DBALException $e) {
  65. throw new \OC\DatabaseException($e->getMessage());
  66. }
  67. // differentiate between query and manipulation
  68. $result = new OC_DB_StatementWrapper($result, $isManipulation);
  69. return $result;
  70. }
  71. /**
  72. * tries to guess the type of statement based on the first 10 characters
  73. * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
  74. *
  75. * @param string $sql
  76. * @return bool
  77. */
  78. static public function isManipulation( $sql ) {
  79. $selectOccurrence = stripos($sql, 'SELECT');
  80. if ($selectOccurrence !== false && $selectOccurrence < 10) {
  81. return false;
  82. }
  83. $insertOccurrence = stripos($sql, 'INSERT');
  84. if ($insertOccurrence !== false && $insertOccurrence < 10) {
  85. return true;
  86. }
  87. $updateOccurrence = stripos($sql, 'UPDATE');
  88. if ($updateOccurrence !== false && $updateOccurrence < 10) {
  89. return true;
  90. }
  91. $deleteOccurrence = stripos($sql, 'DELETE');
  92. if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
  93. return true;
  94. }
  95. return false;
  96. }
  97. /**
  98. * execute a prepared statement, on error write log and throw exception
  99. * @param mixed $stmt OC_DB_StatementWrapper,
  100. * an array with 'sql' and optionally 'limit' and 'offset' keys
  101. * .. or a simple sql query string
  102. * @param array $parameters
  103. * @return OC_DB_StatementWrapper
  104. * @throws \OC\DatabaseException
  105. */
  106. static public function executeAudited( $stmt, array $parameters = []) {
  107. if (is_string($stmt)) {
  108. // convert to an array with 'sql'
  109. if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
  110. // TODO try to convert LIMIT OFFSET notation to parameters
  111. $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
  112. . ' pass an array with \'limit\' and \'offset\' instead';
  113. throw new \OC\DatabaseException($message);
  114. }
  115. $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
  116. }
  117. if (is_array($stmt)) {
  118. // convert to prepared statement
  119. if ( ! array_key_exists('sql', $stmt) ) {
  120. $message = 'statement array must at least contain key \'sql\'';
  121. throw new \OC\DatabaseException($message);
  122. }
  123. if ( ! array_key_exists('limit', $stmt) ) {
  124. $stmt['limit'] = null;
  125. }
  126. if ( ! array_key_exists('limit', $stmt) ) {
  127. $stmt['offset'] = null;
  128. }
  129. $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
  130. }
  131. self::raiseExceptionOnError($stmt, 'Could not prepare statement');
  132. if ($stmt instanceof OC_DB_StatementWrapper) {
  133. $result = $stmt->execute($parameters);
  134. self::raiseExceptionOnError($result, 'Could not execute statement');
  135. } else {
  136. if (is_object($stmt)) {
  137. $message = 'Expected a prepared statement or array got ' . get_class($stmt);
  138. } else {
  139. $message = 'Expected a prepared statement or array got ' . gettype($stmt);
  140. }
  141. throw new \OC\DatabaseException($message);
  142. }
  143. return $result;
  144. }
  145. /**
  146. * saves database schema to xml file
  147. * @param string $file name of file
  148. * @return bool
  149. *
  150. * TODO: write more documentation
  151. */
  152. public static function getDbStructure($file) {
  153. $schemaManager = self::getMDB2SchemaManager();
  154. return $schemaManager->getDbStructure($file);
  155. }
  156. /**
  157. * Creates tables from XML file
  158. * @param string $file file to read structure from
  159. * @return bool
  160. *
  161. * TODO: write more documentation
  162. */
  163. public static function createDbFromStructure( $file ) {
  164. $schemaManager = self::getMDB2SchemaManager();
  165. return $schemaManager->createDbFromStructure($file);
  166. }
  167. /**
  168. * update the database schema
  169. * @param string $file file to read structure from
  170. * @throws Exception
  171. * @return string|boolean
  172. * @suppress PhanDeprecatedFunction
  173. */
  174. public static function updateDbFromStructure($file) {
  175. $schemaManager = self::getMDB2SchemaManager();
  176. try {
  177. $result = $schemaManager->updateDbFromStructure($file);
  178. } catch (Exception $e) {
  179. \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
  180. throw $e;
  181. }
  182. return $result;
  183. }
  184. /**
  185. * remove all tables defined in a database structure xml file
  186. * @param string $file the xml file describing the tables
  187. */
  188. public static function removeDBStructure($file) {
  189. $schemaManager = self::getMDB2SchemaManager();
  190. $schemaManager->removeDBStructure($file);
  191. }
  192. /**
  193. * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
  194. * @param mixed $result
  195. * @param string $message
  196. * @return void
  197. * @throws \OC\DatabaseException
  198. */
  199. public static function raiseExceptionOnError($result, $message = null) {
  200. if($result === false) {
  201. if ($message === null) {
  202. $message = self::getErrorMessage();
  203. } else {
  204. $message .= ', Root cause:' . self::getErrorMessage();
  205. }
  206. throw new \OC\DatabaseException($message);
  207. }
  208. }
  209. /**
  210. * returns the error code and message as a string for logging
  211. * works with DoctrineException
  212. * @return string
  213. */
  214. public static function getErrorMessage() {
  215. $connection = \OC::$server->getDatabaseConnection();
  216. return $connection->getError();
  217. }
  218. /**
  219. * Checks if a table exists in the database - the database prefix will be prepended
  220. *
  221. * @param string $table
  222. * @return bool
  223. * @throws \OC\DatabaseException
  224. */
  225. public static function tableExists($table) {
  226. $connection = \OC::$server->getDatabaseConnection();
  227. return $connection->tableExists($table);
  228. }
  229. }