PageRenderTime 99ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/db.php

https://github.com/sezuan/core
PHP | 711 lines | 464 code | 56 blank | 191 comment | 96 complexity | ef13d3d15053f7fc5a157b5d1fe6d2cf MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  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. define('MDB2_SCHEMA_DUMP_STRUCTURE', '1');
  23. class DatabaseException extends Exception {
  24. private $query;
  25. //FIXME getQuery seems to be unused, maybe use parent constructor with $message, $code and $previous
  26. public function __construct($message, $query = null){
  27. parent::__construct($message);
  28. $this->query = $query;
  29. }
  30. public function getQuery() {
  31. return $this->query;
  32. }
  33. }
  34. /**
  35. * This class manages the access to the database. It basically is a wrapper for
  36. * Doctrine with some adaptions.
  37. */
  38. class OC_DB {
  39. const BACKEND_DOCTRINE=2;
  40. static private $preparedQueries = array();
  41. static private $cachingEnabled = true;
  42. /**
  43. * @var \Doctrine\DBAL\Connection
  44. */
  45. static private $connection; //the preferred connection to use, only Doctrine
  46. static private $backend=null;
  47. /**
  48. * @var \Doctrine\DBAL\Connection
  49. */
  50. static private $DOCTRINE=null;
  51. static private $inTransaction=false;
  52. static private $prefix=null;
  53. static private $type=null;
  54. /**
  55. * check which backend we should use
  56. * @return int BACKEND_DOCTRINE
  57. */
  58. private static function getDBBackend() {
  59. return self::BACKEND_DOCTRINE;
  60. }
  61. /**
  62. * @brief connects to the database
  63. * @param int $backend
  64. * @return bool true if connection can be established or false on error
  65. *
  66. * Connects to the database as specified in config.php
  67. */
  68. public static function connect($backend=null) {
  69. if(self::$connection) {
  70. return true;
  71. }
  72. if(is_null($backend)) {
  73. $backend=self::getDBBackend();
  74. }
  75. if($backend==self::BACKEND_DOCTRINE) {
  76. $success = self::connectDoctrine();
  77. self::$connection=self::$DOCTRINE;
  78. self::$backend=self::BACKEND_DOCTRINE;
  79. }
  80. return $success;
  81. }
  82. /**
  83. * connect to the database using doctrine
  84. *
  85. * @return bool
  86. */
  87. public static function connectDoctrine() {
  88. if(self::$connection) {
  89. if(self::$backend!=self::BACKEND_DOCTRINE) {
  90. self::disconnect();
  91. } else {
  92. return true;
  93. }
  94. }
  95. self::$preparedQueries = array();
  96. // The global data we need
  97. $name = OC_Config::getValue( "dbname", "owncloud" );
  98. $host = OC_Config::getValue( "dbhost", "" );
  99. $user = OC_Config::getValue( "dbuser", "" );
  100. $pass = OC_Config::getValue( "dbpassword", "" );
  101. $type = OC_Config::getValue( "dbtype", "sqlite" );
  102. if(strpos($host, ':')) {
  103. list($host, $port)=explode(':', $host, 2);
  104. } else {
  105. $port=false;
  106. }
  107. // do nothing if the connection already has been established
  108. if(!self::$DOCTRINE) {
  109. $config = new \Doctrine\DBAL\Configuration();
  110. switch($type) {
  111. case 'sqlite':
  112. case 'sqlite3':
  113. $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' );
  114. $connectionParams = array(
  115. 'user' => $user,
  116. 'password' => $pass,
  117. 'path' => $datadir.'/'.$name.'.db',
  118. 'driver' => 'pdo_sqlite',
  119. );
  120. break;
  121. case 'mysql':
  122. $connectionParams = array(
  123. 'user' => $user,
  124. 'password' => $pass,
  125. 'host' => $host,
  126. 'port' => $port,
  127. 'dbname' => $name,
  128. 'charset' => 'UTF8',
  129. 'driver' => 'pdo_mysql',
  130. );
  131. break;
  132. case 'pgsql':
  133. $connectionParams = array(
  134. 'user' => $user,
  135. 'password' => $pass,
  136. 'host' => $host,
  137. 'port' => $port,
  138. 'dbname' => $name,
  139. 'driver' => 'pdo_pgsql',
  140. );
  141. break;
  142. case 'oci':
  143. $connectionParams = array(
  144. 'user' => $user,
  145. 'password' => $pass,
  146. 'host' => $host,
  147. 'dbname' => $name,
  148. 'charset' => 'AL32UTF8',
  149. 'driver' => 'oci8',
  150. );
  151. if (!empty($port)) {
  152. $connectionParams['port'] = $port;
  153. }
  154. break;
  155. case 'mssql':
  156. $connectionParams = array(
  157. 'user' => $user,
  158. 'password' => $pass,
  159. 'host' => $host,
  160. 'port' => $port,
  161. 'dbname' => $name,
  162. 'charset' => 'UTF8',
  163. 'driver' => 'pdo_sqlsrv',
  164. );
  165. break;
  166. default:
  167. return false;
  168. }
  169. try {
  170. self::$DOCTRINE = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
  171. } catch(\Doctrine\DBAL\DBALException $e) {
  172. OC_Log::write('core', $e->getMessage(), OC_Log::FATAL);
  173. OC_User::setUserId(null);
  174. // send http status 503
  175. header('HTTP/1.1 503 Service Temporarily Unavailable');
  176. header('Status: 503 Service Temporarily Unavailable');
  177. OC_Template::printErrorPage('Failed to connect to database');
  178. die();
  179. }
  180. }
  181. return true;
  182. }
  183. /**
  184. * @brief Prepare a SQL query
  185. * @param string $query Query string
  186. * @param int $limit
  187. * @param int $offset
  188. * @param bool $isManipulation
  189. * @throws DatabaseException
  190. * @return \Doctrine\DBAL\Statement prepared SQL query
  191. *
  192. * SQL query via Doctrine prepare(), needs to be execute()'d!
  193. */
  194. static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
  195. if (!is_null($limit) && $limit != -1) {
  196. if ($limit === -1) {
  197. $limit = null;
  198. }
  199. $platform = self::$connection->getDatabasePlatform();
  200. $query = $platform->modifyLimitQuery($query, $limit, $offset);
  201. } else {
  202. if (isset(self::$preparedQueries[$query]) and self::$cachingEnabled) {
  203. return self::$preparedQueries[$query];
  204. }
  205. }
  206. $rawQuery = $query;
  207. // Optimize the query
  208. $query = self::processQuery( $query );
  209. if(OC_Config::getValue( "log_query", false)) {
  210. OC_Log::write('core', 'DB prepare : '.$query, OC_Log::DEBUG);
  211. }
  212. self::connect();
  213. if ($isManipulation === null) {
  214. //try to guess, so we return the number of rows on manipulations
  215. $isManipulation = self::isManipulation($query);
  216. }
  217. // return the result
  218. if (self::$backend == self::BACKEND_DOCTRINE) {
  219. try {
  220. $result=self::$connection->prepare($query);
  221. } catch(\Doctrine\DBAL\DBALException $e) {
  222. throw new \DatabaseException($e->getMessage(), $query);
  223. }
  224. // differentiate between query and manipulation
  225. $result=new OC_DB_StatementWrapper($result, $isManipulation);
  226. }
  227. if ((is_null($limit) || $limit == -1) and self::$cachingEnabled ) {
  228. $type = OC_Config::getValue( "dbtype", "sqlite" );
  229. if( $type != 'sqlite' && $type != 'sqlite3' ) {
  230. self::$preparedQueries[$rawQuery] = $result;
  231. }
  232. }
  233. return $result;
  234. }
  235. /**
  236. * tries to guess the type of statement based on the first 10 characters
  237. * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
  238. *
  239. * @param string $sql
  240. */
  241. static public function isManipulation( $sql ) {
  242. $selectOccurence = stripos ($sql, "SELECT");
  243. if ($selectOccurence !== false && $selectOccurence < 10) {
  244. return false;
  245. }
  246. $insertOccurence = stripos ($sql, "INSERT");
  247. if ($insertOccurence !== false && $insertOccurence < 10) {
  248. return true;
  249. }
  250. $updateOccurence = stripos ($sql, "UPDATE");
  251. if ($updateOccurence !== false && $updateOccurence < 10) {
  252. return true;
  253. }
  254. $deleteOccurance = stripos ($sql, "DELETE");
  255. if ($deleteOccurance !== false && $deleteOccurance < 10) {
  256. return true;
  257. }
  258. return false;
  259. }
  260. /**
  261. * @brief execute a prepared statement, on error write log and throw exception
  262. * @param mixed $stmt OC_DB_StatementWrapper,
  263. * an array with 'sql' and optionally 'limit' and 'offset' keys
  264. * .. or a simple sql query string
  265. * @param array $parameters
  266. * @return result
  267. * @throws DatabaseException
  268. */
  269. static public function executeAudited( $stmt, array $parameters = null) {
  270. if (is_string($stmt)) {
  271. // convert to an array with 'sql'
  272. if (stripos($stmt,'LIMIT') !== false) { //OFFSET requires LIMIT, se we only neet to check for LIMIT
  273. // TODO try to convert LIMIT OFFSET notation to parameters, see fixLimitClauseForMSSQL
  274. $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
  275. . ' pass an array with \'limit\' and \'offset\' instead';
  276. throw new DatabaseException($message);
  277. }
  278. $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
  279. }
  280. if (is_array($stmt)){
  281. // convert to prepared statement
  282. if ( ! array_key_exists('sql', $stmt) ) {
  283. $message = 'statement array must at least contain key \'sql\'';
  284. throw new DatabaseException($message);
  285. }
  286. if ( ! array_key_exists('limit', $stmt) ) {
  287. $stmt['limit'] = null;
  288. }
  289. if ( ! array_key_exists('limit', $stmt) ) {
  290. $stmt['offset'] = null;
  291. }
  292. $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
  293. }
  294. self::raiseExceptionOnError($stmt, 'Could not prepare statement');
  295. if ($stmt instanceof OC_DB_StatementWrapper) {
  296. $result = $stmt->execute($parameters);
  297. self::raiseExceptionOnError($result, 'Could not execute statement');
  298. } else {
  299. if (is_object($stmt)) {
  300. $message = 'Expected a prepared statement or array got ' . get_class($stmt);
  301. } else {
  302. $message = 'Expected a prepared statement or array got ' . gettype($stmt);
  303. }
  304. throw new DatabaseException($message);
  305. }
  306. return $result;
  307. }
  308. /**
  309. * @brief gets last value of autoincrement
  310. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix
  311. * @return int id
  312. * @throws DatabaseException
  313. *
  314. * \Doctrine\DBAL\Connection lastInsertId
  315. *
  316. * Call this method right after the insert command or other functions may
  317. * cause trouble!
  318. */
  319. public static function insertid($table=null) {
  320. self::connect();
  321. $type = OC_Config::getValue( "dbtype", "sqlite" );
  322. if( $type === 'pgsql' ) {
  323. $result = self::executeAudited('SELECT lastval() AS id');
  324. $row = $result->fetchRow();
  325. self::raiseExceptionOnError($row, 'fetching row for insertid failed');
  326. return $row['id'];
  327. } else if( $type === 'mssql') {
  328. if($table !== null) {
  329. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  330. $table = str_replace( '*PREFIX*', $prefix, $table );
  331. }
  332. return self::$connection->lastInsertId($table);
  333. }
  334. if( $type === 'oci' ) {
  335. if($table !== null) {
  336. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  337. $suffix = '_SEQ';
  338. $table = '"'.str_replace( '*PREFIX*', $prefix, $table ).$suffix.'"';
  339. }
  340. return self::$connection->lastInsertId($table);
  341. } else {
  342. if($table !== null) {
  343. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  344. $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" );
  345. $table = str_replace( '*PREFIX*', $prefix, $table ).$suffix;
  346. }
  347. $result = self::$connection->lastInsertId($table);
  348. }
  349. self::raiseExceptionOnError($result, 'insertid failed');
  350. return $result;
  351. }
  352. /**
  353. * @brief Disconnect
  354. * @return bool
  355. *
  356. * This is good bye, good bye, yeah!
  357. */
  358. public static function disconnect() {
  359. // Cut connection if required
  360. if(self::$connection) {
  361. self::$connection=false;
  362. self::$DOCTRINE=false;
  363. }
  364. return true;
  365. }
  366. /** else {
  367. * @brief saves database scheme to xml file
  368. * @param string $file name of file
  369. * @param int $mode
  370. * @return bool
  371. *
  372. * TODO: write more documentation
  373. */
  374. public static function getDbStructure( $file, $mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
  375. self::connectDoctrine();
  376. return OC_DB_Schema::getDbStructure(self::$DOCTRINE, $file);
  377. }
  378. /**
  379. * @brief Creates tables from XML file
  380. * @param string $file file to read structure from
  381. * @return bool
  382. *
  383. * TODO: write more documentation
  384. */
  385. public static function createDbFromStructure( $file ) {
  386. self::connectDoctrine();
  387. return OC_DB_Schema::createDbFromStructure(self::$DOCTRINE, $file);
  388. }
  389. /**
  390. * @brief update the database scheme
  391. * @param string $file file to read structure from
  392. * @throws Exception
  393. * @return bool
  394. */
  395. public static function updateDbFromStructure($file) {
  396. self::connectDoctrine();
  397. try {
  398. $result = OC_DB_Schema::updateDbFromStructure(self::$DOCTRINE, $file);
  399. } catch (Exception $e) {
  400. OC_Log::write('core', 'Failed to update database structure ('.$e.')', OC_Log::FATAL);
  401. throw $e;
  402. }
  403. return $result;
  404. }
  405. /**
  406. * @brief Insert a row if a matching row doesn't exists.
  407. * @param string $table. The table to insert into in the form '*PREFIX*tableName'
  408. * @param array $input. An array of fieldname/value pairs
  409. * @returns int number of updated rows
  410. */
  411. public static function insertIfNotExist($table, $input) {
  412. self::connect();
  413. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  414. $table = str_replace( '*PREFIX*', $prefix, $table );
  415. if(is_null(self::$type)) {
  416. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  417. }
  418. $type = self::$type;
  419. $query = '';
  420. $inserts = array_values($input);
  421. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  422. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  423. // NOTE: For SQLite we have to use this clumsy approach
  424. // otherwise all fieldnames used must have a unique key.
  425. $query = 'SELECT * FROM `' . $table . '` WHERE ';
  426. foreach($input as $key => $value) {
  427. $query .= '`' . $key . '` = ? AND ';
  428. }
  429. $query = substr($query, 0, strlen($query) - 5);
  430. try {
  431. $result = self::executeAudited($query, $inserts);
  432. } catch(DatabaseException $e) {
  433. OC_Template::printExceptionErrorPage( $e );
  434. }
  435. if((int)$result->numRows() === 0) {
  436. $query = 'INSERT INTO `' . $table . '` (`'
  437. . implode('`,`', array_keys($input)) . '`) VALUES('
  438. . str_repeat('?,', count($input)-1).'? ' . ')';
  439. } else {
  440. return 0; //no rows updated
  441. }
  442. } elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql' || $type == 'mssql') {
  443. $query = 'INSERT INTO `' .$table . '` (`'
  444. . implode('`,`', array_keys($input)) . '`) SELECT '
  445. . str_repeat('?,', count($input)-1).'? ' // Is there a prettier alternative?
  446. . 'FROM `' . $table . '` WHERE ';
  447. foreach($input as $key => $value) {
  448. $query .= '`' . $key . '` = ? AND ';
  449. }
  450. $query = substr($query, 0, strlen($query) - 5);
  451. $query .= ' HAVING COUNT(*) = 0';
  452. $inserts = array_merge($inserts, $inserts);
  453. }
  454. try {
  455. $result = self::executeAudited($query, $inserts);
  456. } catch(\Doctrine\DBAL\DBALException $e) {
  457. OC_Template::printExceptionErrorPage( $e );
  458. }
  459. return $result;
  460. }
  461. /**
  462. * @brief does minor changes to query
  463. * @param string $query Query string
  464. * @return string corrected query string
  465. *
  466. * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
  467. * and replaces the ` with ' or " according to the database driver.
  468. */
  469. private static function processQuery( $query ) {
  470. self::connect();
  471. // We need Database type and table prefix
  472. if(is_null(self::$type)) {
  473. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  474. }
  475. $type = self::$type;
  476. if(is_null(self::$prefix)) {
  477. self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" );
  478. }
  479. $prefix = self::$prefix;
  480. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  481. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  482. $query = str_replace( '`', '"', $query );
  483. $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query );
  484. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query );
  485. } elseif( $type == 'pgsql' ) {
  486. $query = str_replace( '`', '"', $query );
  487. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)',
  488. $query );
  489. } elseif( $type == 'oci' ) {
  490. $query = str_replace( '`', '"', $query );
  491. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  492. $query = str_ireplace( 'UNIX_TIMESTAMP()', "(cast(sys_extract_utc(systimestamp) as date) - date'1970-01-01') * 86400", $query );
  493. }elseif( $type == 'mssql' ) {
  494. $query = preg_replace( "/\`(.*?)`/", "[$1]", $query );
  495. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  496. $query = str_replace( 'LENGTH(', 'LEN(', $query );
  497. $query = str_replace( 'SUBSTR(', 'SUBSTRING(', $query );
  498. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'DATEDIFF(second,{d \'1970-01-01\'},GETDATE())', $query );
  499. $query = self::fixLimitClauseForMSSQL($query);
  500. }
  501. // replace table name prefix
  502. $query = str_replace( '*PREFIX*', $prefix, $query );
  503. return $query;
  504. }
  505. private static function fixLimitClauseForMSSQL($query) {
  506. $limitLocation = stripos ($query, "LIMIT");
  507. if ( $limitLocation === false ) {
  508. return $query;
  509. }
  510. // total == 0 means all results - not zero results
  511. //
  512. // First number is either total or offset, locate it by first space
  513. //
  514. $offset = substr ($query, $limitLocation + 5);
  515. $offset = substr ($offset, 0, stripos ($offset, ' '));
  516. $offset = trim ($offset);
  517. // check for another parameter
  518. if (stripos ($offset, ',') === false) {
  519. // no more parameters
  520. $offset = 0;
  521. $total = intval ($offset);
  522. } else {
  523. // found another parameter
  524. $offset = intval ($offset);
  525. $total = substr ($query, $limitLocation + 5);
  526. $total = substr ($total, stripos ($total, ','));
  527. $total = substr ($total, 0, stripos ($total, ' '));
  528. $total = intval ($total);
  529. }
  530. $query = trim (substr ($query, 0, $limitLocation));
  531. if ($offset == 0 && $total !== 0) {
  532. if (strpos($query, "SELECT") === false) {
  533. $query = "TOP {$total} " . $query;
  534. } else {
  535. $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
  536. }
  537. } else if ($offset > 0) {
  538. $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
  539. $query = 'SELECT *
  540. FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
  541. FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3';
  542. if ($total > 0) {
  543. $query .= ' WHERE line3 BETWEEN ' . ($offset + 1) . ' AND ' . ($offset + $total);
  544. } else {
  545. $query .= ' WHERE line3 > ' . $offset;
  546. }
  547. }
  548. return $query;
  549. }
  550. /**
  551. * @brief drop a table
  552. * @param string $tableName the table to drop
  553. */
  554. public static function dropTable($tableName) {
  555. self::connectDoctrine();
  556. OC_DB_Schema::dropTable(self::$DOCTRINE, $tableName);
  557. }
  558. /**
  559. * remove all tables defined in a database structure xml file
  560. * @param string $file the xml file describing the tables
  561. */
  562. public static function removeDBStructure($file) {
  563. self::connectDoctrine();
  564. OC_DB_Schema::removeDBStructure(self::$DOCTRINE, $file);
  565. }
  566. /**
  567. * @brief replaces the ownCloud tables with a new set
  568. * @param $file string path to the MDB2 xml db export file
  569. */
  570. public static function replaceDB( $file ) {
  571. self::connectDoctrine();
  572. OC_DB_Schema::replaceDB(self::$DOCTRINE, $file);
  573. }
  574. /**
  575. * Start a transaction
  576. * @return bool
  577. */
  578. public static function beginTransaction() {
  579. self::connect();
  580. self::$connection->beginTransaction();
  581. self::$inTransaction=true;
  582. return true;
  583. }
  584. /**
  585. * Commit the database changes done during a transaction that is in progress
  586. * @return bool
  587. */
  588. public static function commit() {
  589. self::connect();
  590. if(!self::$inTransaction) {
  591. return false;
  592. }
  593. self::$connection->commit();
  594. self::$inTransaction=false;
  595. return true;
  596. }
  597. /**
  598. * check if a result is an error, works with Doctrine
  599. * @param mixed $result
  600. * @return bool
  601. */
  602. public static function isError($result) {
  603. //Doctrine returns false on error (and throws an exception)
  604. return $result === false;
  605. }
  606. /**
  607. * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
  608. * @param mixed $result
  609. * @param string $message
  610. * @return void
  611. * @throws DatabaseException
  612. */
  613. public static function raiseExceptionOnError($result, $message = null) {
  614. if(self::isError($result)) {
  615. if ($message === null) {
  616. $message = self::getErrorMessage($result);
  617. } else {
  618. $message .= ', Root cause:' . self::getErrorMessage($result);
  619. }
  620. throw new DatabaseException($message, self::getErrorCode($result));
  621. }
  622. }
  623. public static function getErrorCode($error) {
  624. $code = self::$connection->errorCode();
  625. return $code;
  626. }
  627. /**
  628. * returns the error code and message as a string for logging
  629. * works with DoctrineException
  630. * @param mixed $error
  631. * @return string
  632. */
  633. public static function getErrorMessage($error) {
  634. if (self::$backend==self::BACKEND_DOCTRINE and self::$DOCTRINE) {
  635. $msg = self::$DOCTRINE->errorCode() . ': ';
  636. $errorInfo = self::$DOCTRINE->errorInfo();
  637. if (is_array($errorInfo)) {
  638. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  639. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  640. $msg .= 'Driver Message = '.$errorInfo[2];
  641. }
  642. return $msg;
  643. }
  644. return '';
  645. }
  646. /**
  647. * @param bool $enabled
  648. */
  649. static public function enableCaching($enabled) {
  650. if (!$enabled) {
  651. self::$preparedQueries = array();
  652. }
  653. self::$cachingEnabled = $enabled;
  654. }
  655. }