db.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. /**
  3. * @author Andreas Fischer <bantu@owncloud.com>
  4. * @author Bart Visscher <bartv@thisnet.nl>
  5. * @author Dan Bartram <daneybartram@gmail.com>
  6. * @author Joas Schilling <nickvergessen@owncloud.com>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <icewind@owncloud.com>
  10. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. * @author Tom Needham <tom@owncloud.com>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @copyright Copyright (c) 2015, ownCloud, Inc.
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  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. * @return \OCP\IDBConnection
  38. */
  39. static public function getConnection() {
  40. return \OC::$server->getDatabaseConnection();
  41. }
  42. /**
  43. * get MDB2 schema manager
  44. *
  45. * @return \OC\DB\MDB2SchemaManager
  46. */
  47. private static function getMDB2SchemaManager() {
  48. return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
  49. }
  50. /**
  51. * Prepare a SQL query
  52. * @param string $query Query string
  53. * @param int $limit
  54. * @param int $offset
  55. * @param bool $isManipulation
  56. * @throws \OC\DatabaseException
  57. * @return OC_DB_StatementWrapper prepared SQL query
  58. *
  59. * SQL query via Doctrine prepare(), needs to be execute()'d!
  60. */
  61. static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
  62. $connection = \OC::$server->getDatabaseConnection();
  63. if ($isManipulation === null) {
  64. //try to guess, so we return the number of rows on manipulations
  65. $isManipulation = self::isManipulation($query);
  66. }
  67. // return the result
  68. try {
  69. $result =$connection->prepare($query, $limit, $offset);
  70. } catch (\Doctrine\DBAL\DBALException $e) {
  71. throw new \OC\DatabaseException($e->getMessage(), $query);
  72. }
  73. // differentiate between query and manipulation
  74. $result = new OC_DB_StatementWrapper($result, $isManipulation);
  75. return $result;
  76. }
  77. /**
  78. * tries to guess the type of statement based on the first 10 characters
  79. * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
  80. *
  81. * @param string $sql
  82. * @return bool
  83. */
  84. static public function isManipulation( $sql ) {
  85. $selectOccurrence = stripos($sql, 'SELECT');
  86. if ($selectOccurrence !== false && $selectOccurrence < 10) {
  87. return false;
  88. }
  89. $insertOccurrence = stripos($sql, 'INSERT');
  90. if ($insertOccurrence !== false && $insertOccurrence < 10) {
  91. return true;
  92. }
  93. $updateOccurrence = stripos($sql, 'UPDATE');
  94. if ($updateOccurrence !== false && $updateOccurrence < 10) {
  95. return true;
  96. }
  97. $deleteOccurrence = stripos($sql, 'DELETE');
  98. if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
  99. return true;
  100. }
  101. return false;
  102. }
  103. /**
  104. * execute a prepared statement, on error write log and throw exception
  105. * @param mixed $stmt OC_DB_StatementWrapper,
  106. * an array with 'sql' and optionally 'limit' and 'offset' keys
  107. * .. or a simple sql query string
  108. * @param array $parameters
  109. * @return OC_DB_StatementWrapper
  110. * @throws \OC\DatabaseException
  111. */
  112. static public function executeAudited( $stmt, array $parameters = null) {
  113. if (is_string($stmt)) {
  114. // convert to an array with 'sql'
  115. if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
  116. // TODO try to convert LIMIT OFFSET notation to parameters
  117. $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
  118. . ' pass an array with \'limit\' and \'offset\' instead';
  119. throw new \OC\DatabaseException($message);
  120. }
  121. $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
  122. }
  123. if (is_array($stmt)) {
  124. // convert to prepared statement
  125. if ( ! array_key_exists('sql', $stmt) ) {
  126. $message = 'statement array must at least contain key \'sql\'';
  127. throw new \OC\DatabaseException($message);
  128. }
  129. if ( ! array_key_exists('limit', $stmt) ) {
  130. $stmt['limit'] = null;
  131. }
  132. if ( ! array_key_exists('limit', $stmt) ) {
  133. $stmt['offset'] = null;
  134. }
  135. $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
  136. }
  137. self::raiseExceptionOnError($stmt, 'Could not prepare statement');
  138. if ($stmt instanceof OC_DB_StatementWrapper) {
  139. $result = $stmt->execute($parameters);
  140. self::raiseExceptionOnError($result, 'Could not execute statement');
  141. } else {
  142. if (is_object($stmt)) {
  143. $message = 'Expected a prepared statement or array got ' . get_class($stmt);
  144. } else {
  145. $message = 'Expected a prepared statement or array got ' . gettype($stmt);
  146. }
  147. throw new \OC\DatabaseException($message);
  148. }
  149. return $result;
  150. }
  151. /**
  152. * gets last value of autoincrement
  153. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix
  154. * @return string id
  155. * @throws \OC\DatabaseException
  156. *
  157. * \Doctrine\DBAL\Connection lastInsertId
  158. *
  159. * Call this method right after the insert command or other functions may
  160. * cause trouble!
  161. */
  162. public static function insertid($table=null) {
  163. return \OC::$server->getDatabaseConnection()->lastInsertId($table);
  164. }
  165. /**
  166. * Start a transaction
  167. */
  168. public static function beginTransaction() {
  169. return \OC::$server->getDatabaseConnection()->beginTransaction();
  170. }
  171. /**
  172. * Commit the database changes done during a transaction that is in progress
  173. */
  174. public static function commit() {
  175. return \OC::$server->getDatabaseConnection()->commit();
  176. }
  177. /**
  178. * Rollback the database changes done during a transaction that is in progress
  179. */
  180. public static function rollback() {
  181. return \OC::$server->getDatabaseConnection()->rollback();
  182. }
  183. /**
  184. * saves database schema to xml file
  185. * @param string $file name of file
  186. * @param int $mode
  187. * @return bool
  188. *
  189. * TODO: write more documentation
  190. */
  191. public static function getDbStructure($file) {
  192. $schemaManager = self::getMDB2SchemaManager();
  193. return $schemaManager->getDbStructure($file);
  194. }
  195. /**
  196. * Creates tables from XML file
  197. * @param string $file file to read structure from
  198. * @return bool
  199. *
  200. * TODO: write more documentation
  201. */
  202. public static function createDbFromStructure( $file ) {
  203. $schemaManager = self::getMDB2SchemaManager();
  204. $result = $schemaManager->createDbFromStructure($file);
  205. return $result;
  206. }
  207. /**
  208. * update the database schema
  209. * @param string $file file to read structure from
  210. * @throws Exception
  211. * @return string|boolean
  212. */
  213. public static function updateDbFromStructure($file) {
  214. $schemaManager = self::getMDB2SchemaManager();
  215. try {
  216. $result = $schemaManager->updateDbFromStructure($file);
  217. } catch (Exception $e) {
  218. \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
  219. throw $e;
  220. }
  221. return $result;
  222. }
  223. /**
  224. * simulate the database schema update
  225. * @param string $file file to read structure from
  226. * @throws Exception
  227. * @return string|boolean
  228. */
  229. public static function simulateUpdateDbFromStructure($file) {
  230. $schemaManager = self::getMDB2SchemaManager();
  231. try {
  232. $result = $schemaManager->simulateUpdateDbFromStructure($file);
  233. } catch (Exception $e) {
  234. \OCP\Util::writeLog('core', 'Simulated database structure update failed ('.$e.')', \OCP\Util::FATAL);
  235. throw $e;
  236. }
  237. return $result;
  238. }
  239. /**
  240. * drop a table - the database prefix will be prepended
  241. * @param string $tableName the table to drop
  242. */
  243. public static function dropTable($tableName) {
  244. $connection = \OC::$server->getDatabaseConnection();
  245. $connection->dropTable($tableName);
  246. }
  247. /**
  248. * remove all tables defined in a database structure xml file
  249. * @param string $file the xml file describing the tables
  250. */
  251. public static function removeDBStructure($file) {
  252. $schemaManager = self::getMDB2SchemaManager();
  253. $schemaManager->removeDBStructure($file);
  254. }
  255. /**
  256. * check if a result is an error, works with Doctrine
  257. * @param mixed $result
  258. * @return bool
  259. */
  260. public static function isError($result) {
  261. //Doctrine returns false on error (and throws an exception)
  262. return $result === false;
  263. }
  264. /**
  265. * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
  266. * @param mixed $result
  267. * @param string $message
  268. * @return void
  269. * @throws \OC\DatabaseException
  270. */
  271. public static function raiseExceptionOnError($result, $message = null) {
  272. if(self::isError($result)) {
  273. if ($message === null) {
  274. $message = self::getErrorMessage();
  275. } else {
  276. $message .= ', Root cause:' . self::getErrorMessage();
  277. }
  278. throw new \OC\DatabaseException($message, self::getErrorCode());
  279. }
  280. }
  281. public static function getErrorCode() {
  282. $connection = \OC::$server->getDatabaseConnection();
  283. return $connection->errorCode();
  284. }
  285. /**
  286. * returns the error code and message as a string for logging
  287. * works with DoctrineException
  288. * @return string
  289. */
  290. public static function getErrorMessage() {
  291. $connection = \OC::$server->getDatabaseConnection();
  292. return $connection->getError();
  293. }
  294. /**
  295. * Checks if a table exists in the database - the database prefix will be prepended
  296. *
  297. * @param string $table
  298. * @return bool
  299. * @throws \OC\DatabaseException
  300. */
  301. public static function tableExists($table) {
  302. $connection = \OC::$server->getDatabaseConnection();
  303. return $connection->tableExists($table);
  304. }
  305. }