db.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. * @author Vincent Petry <pvince81@owncloud.com>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. /**
  30. * This class manages the access to the database. It basically is a wrapper for
  31. * Doctrine with some adaptions.
  32. */
  33. class OC_DB {
  34. /**
  35. * get MDB2 schema manager
  36. *
  37. * @return \OC\DB\MDB2SchemaManager
  38. */
  39. private static function getMDB2SchemaManager() {
  40. return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
  41. }
  42. /**
  43. * Prepare a SQL query
  44. * @param string $query Query string
  45. * @param int $limit
  46. * @param int $offset
  47. * @param bool $isManipulation
  48. * @throws \OC\DatabaseException
  49. * @return OC_DB_StatementWrapper prepared SQL query
  50. *
  51. * SQL query via Doctrine prepare(), needs to be execute()'d!
  52. */
  53. static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
  54. $connection = \OC::$server->getDatabaseConnection();
  55. if ($isManipulation === null) {
  56. //try to guess, so we return the number of rows on manipulations
  57. $isManipulation = self::isManipulation($query);
  58. }
  59. // return the result
  60. try {
  61. $result =$connection->prepare($query, $limit, $offset);
  62. } catch (\Doctrine\DBAL\DBALException $e) {
  63. throw new \OC\DatabaseException($e->getMessage(), $query);
  64. }
  65. // differentiate between query and manipulation
  66. $result = new OC_DB_StatementWrapper($result, $isManipulation);
  67. return $result;
  68. }
  69. /**
  70. * tries to guess the type of statement based on the first 10 characters
  71. * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
  72. *
  73. * @param string $sql
  74. * @return bool
  75. */
  76. static public function isManipulation( $sql ) {
  77. $selectOccurrence = stripos($sql, 'SELECT');
  78. if ($selectOccurrence !== false && $selectOccurrence < 10) {
  79. return false;
  80. }
  81. $insertOccurrence = stripos($sql, 'INSERT');
  82. if ($insertOccurrence !== false && $insertOccurrence < 10) {
  83. return true;
  84. }
  85. $updateOccurrence = stripos($sql, 'UPDATE');
  86. if ($updateOccurrence !== false && $updateOccurrence < 10) {
  87. return true;
  88. }
  89. $deleteOccurrence = stripos($sql, 'DELETE');
  90. if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
  91. return true;
  92. }
  93. return false;
  94. }
  95. /**
  96. * execute a prepared statement, on error write log and throw exception
  97. * @param mixed $stmt OC_DB_StatementWrapper,
  98. * an array with 'sql' and optionally 'limit' and 'offset' keys
  99. * .. or a simple sql query string
  100. * @param array $parameters
  101. * @return OC_DB_StatementWrapper
  102. * @throws \OC\DatabaseException
  103. */
  104. static public function executeAudited( $stmt, array $parameters = null) {
  105. if (is_string($stmt)) {
  106. // convert to an array with 'sql'
  107. if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
  108. // TODO try to convert LIMIT OFFSET notation to parameters
  109. $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
  110. . ' pass an array with \'limit\' and \'offset\' instead';
  111. throw new \OC\DatabaseException($message);
  112. }
  113. $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
  114. }
  115. if (is_array($stmt)) {
  116. // convert to prepared statement
  117. if ( ! array_key_exists('sql', $stmt) ) {
  118. $message = 'statement array must at least contain key \'sql\'';
  119. throw new \OC\DatabaseException($message);
  120. }
  121. if ( ! array_key_exists('limit', $stmt) ) {
  122. $stmt['limit'] = null;
  123. }
  124. if ( ! array_key_exists('limit', $stmt) ) {
  125. $stmt['offset'] = null;
  126. }
  127. $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
  128. }
  129. self::raiseExceptionOnError($stmt, 'Could not prepare statement');
  130. if ($stmt instanceof OC_DB_StatementWrapper) {
  131. $result = $stmt->execute($parameters);
  132. self::raiseExceptionOnError($result, 'Could not execute statement');
  133. } else {
  134. if (is_object($stmt)) {
  135. $message = 'Expected a prepared statement or array got ' . get_class($stmt);
  136. } else {
  137. $message = 'Expected a prepared statement or array got ' . gettype($stmt);
  138. }
  139. throw new \OC\DatabaseException($message);
  140. }
  141. return $result;
  142. }
  143. /**
  144. * saves database schema to xml file
  145. * @param string $file name of file
  146. * @param int $mode
  147. * @return bool
  148. *
  149. * TODO: write more documentation
  150. */
  151. public static function getDbStructure($file) {
  152. $schemaManager = self::getMDB2SchemaManager();
  153. return $schemaManager->getDbStructure($file);
  154. }
  155. /**
  156. * Creates tables from XML file
  157. * @param string $file file to read structure from
  158. * @return bool
  159. *
  160. * TODO: write more documentation
  161. */
  162. public static function createDbFromStructure( $file ) {
  163. $schemaManager = self::getMDB2SchemaManager();
  164. $result = $schemaManager->createDbFromStructure($file);
  165. return $result;
  166. }
  167. /**
  168. * update the database schema
  169. * @param string $file file to read structure from
  170. * @throws Exception
  171. * @return string|boolean
  172. */
  173. public static function updateDbFromStructure($file) {
  174. $schemaManager = self::getMDB2SchemaManager();
  175. try {
  176. $result = $schemaManager->updateDbFromStructure($file);
  177. } catch (Exception $e) {
  178. \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
  179. throw $e;
  180. }
  181. return $result;
  182. }
  183. /**
  184. * remove all tables defined in a database structure xml file
  185. * @param string $file the xml file describing the tables
  186. */
  187. public static function removeDBStructure($file) {
  188. $schemaManager = self::getMDB2SchemaManager();
  189. $schemaManager->removeDBStructure($file);
  190. }
  191. /**
  192. * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
  193. * @param mixed $result
  194. * @param string $message
  195. * @return void
  196. * @throws \OC\DatabaseException
  197. */
  198. public static function raiseExceptionOnError($result, $message = null) {
  199. if($result === false) {
  200. if ($message === null) {
  201. $message = self::getErrorMessage();
  202. } else {
  203. $message .= ', Root cause:' . self::getErrorMessage();
  204. }
  205. throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
  206. }
  207. }
  208. /**
  209. * returns the error code and message as a string for logging
  210. * works with DoctrineException
  211. * @return string
  212. */
  213. public static function getErrorMessage() {
  214. $connection = \OC::$server->getDatabaseConnection();
  215. return $connection->getError();
  216. }
  217. /**
  218. * Checks if a table exists in the database - the database prefix will be prepended
  219. *
  220. * @param string $table
  221. * @return bool
  222. * @throws \OC\DatabaseException
  223. */
  224. public static function tableExists($table) {
  225. $connection = \OC::$server->getDatabaseConnection();
  226. return $connection->tableExists($table);
  227. }
  228. }