db.php 9.4 KB

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