diff options
author | Bart Visscher <bartv@thisnet.nl> | 2013-07-18 14:24:27 -0700 |
---|---|---|
committer | Bart Visscher <bartv@thisnet.nl> | 2013-07-18 14:24:27 -0700 |
commit | 084cf0c202c2430938f5c061d8e8616dda10e2df (patch) | |
tree | 78467cf4bc8202545274d3f123527e4861928140 /lib/db.php | |
parent | 279a71acb37ac373703ed05050771ef971b5d9a1 (diff) | |
parent | e2b6781cf9a97e4ad10e4824e38ccdaf3c2dc676 (diff) | |
download | nextcloud-server-084cf0c202c2430938f5c061d8e8616dda10e2df.tar.gz nextcloud-server-084cf0c202c2430938f5c061d8e8616dda10e2df.zip |
Merge pull request #2221 from owncloud/doctrine
OC6: Implement Doctrine as the backend for OC_DB
Diffstat (limited to 'lib/db.php')
-rw-r--r-- | lib/db.php | 751 |
1 files changed, 134 insertions, 617 deletions
diff --git a/lib/db.php b/lib/db.php index 66627856461..e70d66fc2ba 100644 --- a/lib/db.php +++ b/lib/db.php @@ -20,7 +20,9 @@ * */ -class DatabaseException extends Exception{ +define('MDB2_SCHEMA_DUMP_STRUCTURE', '1'); + +class DatabaseException extends Exception { private $query; //FIXME getQuery seems to be unused, maybe use parent constructor with $message, $code and $previous @@ -29,61 +31,41 @@ class DatabaseException extends Exception{ $this->query = $query; } - public function getQuery(){ + public function getQuery() { return $this->query; } } /** * This class manages the access to the database. It basically is a wrapper for - * MDB2 with some adaptions. + * Doctrine with some adaptions. */ class OC_DB { - const BACKEND_PDO=0; - const BACKEND_MDB2=1; + const BACKEND_DOCTRINE=2; static private $preparedQueries = array(); static private $cachingEnabled = true; /** - * @var MDB2_Driver_Common + * @var \Doctrine\DBAL\Connection */ - static private $connection; //the prefered connection to use, either PDO or MDB2 + static private $connection; //the preferred connection to use, only Doctrine static private $backend=null; /** - * @var MDB2_Driver_Common - */ - static private $MDB2=null; - /** - * @var PDO + * @var \Doctrine\DBAL\Connection */ - static private $PDO=null; - /** - * @var MDB2_Schema - */ - static private $schema=null; + static private $DOCTRINE=null; + static private $inTransaction=false; static private $prefix=null; static private $type=null; /** * check which backend we should use - * @return int BACKEND_MDB2 or BACKEND_PDO + * @return int BACKEND_DOCTRINE */ private static function getDBBackend() { - //check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2) - if(class_exists('PDO') && OC_Config::getValue('installed', false)) { - $type = OC_Config::getValue( "dbtype", "sqlite" ); - if($type=='oci') { //oracle also always needs mdb2 - return self::BACKEND_MDB2; - } - if($type=='sqlite3') $type='sqlite'; - $drivers=PDO::getAvailableDrivers(); - if(array_search($type, $drivers)!==false) { - return self::BACKEND_PDO; - } - } - return self::BACKEND_MDB2; + return self::BACKEND_DOCTRINE; } /** @@ -100,28 +82,24 @@ class OC_DB { if(is_null($backend)) { $backend=self::getDBBackend(); } - if($backend==self::BACKEND_PDO) { - $success = self::connectPDO(); - self::$connection=self::$PDO; - self::$backend=self::BACKEND_PDO; - }else{ - $success = self::connectMDB2(); - self::$connection=self::$MDB2; - self::$backend=self::BACKEND_MDB2; + if($backend==self::BACKEND_DOCTRINE) { + $success = self::connectDoctrine(); + self::$connection=self::$DOCTRINE; + self::$backend=self::BACKEND_DOCTRINE; } return $success; } /** - * connect to the database using pdo + * connect to the database using doctrine * * @return bool */ - public static function connectPDO() { + public static function connectDoctrine() { if(self::$connection) { - if(self::$backend==self::BACKEND_MDB2) { + if(self::$backend!=self::BACKEND_DOCTRINE) { self::disconnect(); - }else{ + } else { return true; } } @@ -134,169 +112,85 @@ class OC_DB { $type = OC_Config::getValue( "dbtype", "sqlite" ); if(strpos($host, ':')) { list($host, $port)=explode(':', $host, 2); - }else{ + } else { $port=false; } - $opts = array(); - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' ); - - // do nothing if the connection already has been established - if(!self::$PDO) { - // Add the dsn according to the database type - switch($type) { - case 'sqlite': - $dsn='sqlite2:'.$datadir.'/'.$name.'.db'; - break; - case 'sqlite3': - $dsn='sqlite:'.$datadir.'/'.$name.'.db'; - break; - case 'mysql': - if($port) { - $dsn='mysql:dbname='.$name.';host='.$host.';port='.$port; - }else{ - $dsn='mysql:dbname='.$name.';host='.$host; - } - $opts[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'"; - break; - case 'pgsql': - if($port) { - $dsn='pgsql:dbname='.$name.';host='.$host.';port='.$port; - }else{ - $dsn='pgsql:dbname='.$name.';host='.$host; - } - /** - * Ugly fix for pg connections pbm when password use spaces - */ - $e_user = addslashes($user); - $e_password = addslashes($pass); - $pass = $user = null; - $dsn .= ";user='$e_user';password='$e_password'"; - /** END OF FIX***/ - break; - case 'oci': // Oracle with PDO is unsupported - if ($port) { - $dsn = 'oci:dbname=//' . $host . ':' . $port . '/' . $name; - } else { - $dsn = 'oci:dbname=//' . $host . '/' . $name; - } - break; - case 'mssql': - if ($port) { - $dsn='sqlsrv:Server='.$host.','.$port.';Database='.$name; - } else { - $dsn='sqlsrv:Server='.$host.';Database='.$name; - } - break; - default: - return false; - } - self::$PDO=new PDO($dsn, $user, $pass, $opts); - - // We always, really always want associative arrays - self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - self::$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - return true; - } - - /** - * connect to the database using mdb2 - */ - public static function connectMDB2() { - if(self::$connection) { - if(self::$backend==self::BACKEND_PDO) { - self::disconnect(); - }else{ - return true; - } - } - self::$preparedQueries = array(); - // The global data we need - $name = OC_Config::getValue( "dbname", "owncloud" ); - $host = OC_Config::getValue( "dbhost", "" ); - $user = OC_Config::getValue( "dbuser", "" ); - $pass = OC_Config::getValue( "dbpassword", "" ); - $type = OC_Config::getValue( "dbtype", "sqlite" ); - $SERVERROOT=OC::$SERVERROOT; - $datadir=OC_Config::getValue( "datadirectory", "$SERVERROOT/data" ); // do nothing if the connection already has been established - if(!self::$MDB2) { - // Require MDB2.php (not required in the head of the file so we only load it when needed) - require_once 'MDB2.php'; - - // Prepare options array - $options = array( - 'portability' => MDB2_PORTABILITY_ALL - MDB2_PORTABILITY_FIX_CASE, - 'log_line_break' => '<br>', - 'idxname_format' => '%s', - 'debug' => true, - 'quote_identifier' => true - ); - - // Add the dsn according to the database type + if(!self::$DOCTRINE) { + $config = new \Doctrine\DBAL\Configuration(); switch($type) { case 'sqlite': case 'sqlite3': - $dsn = array( - 'phptype' => $type, - 'database' => "$datadir/$name.db", - 'mode' => '0644' + $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' ); + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'path' => $datadir.'/'.$name.'.db', + 'driver' => 'pdo_sqlite', ); break; case 'mysql': - $dsn = array( - 'phptype' => 'mysql', - 'username' => $user, - 'password' => $pass, - 'hostspec' => $host, - 'database' => $name + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'host' => $host, + 'port' => $port, + 'dbname' => $name, + 'charset' => 'UTF8', + 'driver' => 'pdo_mysql', ); break; case 'pgsql': - $dsn = array( - 'phptype' => 'pgsql', - 'username' => $user, - 'password' => $pass, - 'hostspec' => $host, - 'database' => $name + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'host' => $host, + 'port' => $port, + 'dbname' => $name, + 'driver' => 'pdo_pgsql', ); break; case 'oci': - $dsn = array( - 'phptype' => 'oci8', - 'username' => $user, - 'password' => $pass, - 'service' => $name, - 'hostspec' => $host, - 'charset' => 'AL32UTF8', + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'host' => $host, + 'dbname' => $name, + 'charset' => 'AL32UTF8', + 'driver' => 'oci8', ); + if (!empty($port)) { + $connectionParams['port'] = $port; + } break; case 'mssql': - $dsn = array( - 'phptype' => 'sqlsrv', - 'username' => $user, - 'password' => $pass, - 'hostspec' => $host, - 'database' => $name, - 'charset' => 'UTF-8' + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'host' => $host, + 'port' => $port, + 'dbname' => $name, + 'charset' => 'UTF8', + 'driver' => 'pdo_sqlsrv', ); - $options['portability'] = $options['portability'] - MDB2_PORTABILITY_EMPTY_TO_NULL; break; default: return false; } + try { + self::$DOCTRINE = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); + } catch(\Doctrine\DBAL\DBALException $e) { + OC_Log::write('core', $e->getMessage(), OC_Log::FATAL); + OC_User::setUserId(null); - // Try to establish connection - self::$MDB2 = MDB2::factory( $dsn, $options ); - - self::raiseExceptionOnError( self::$MDB2 ); - - // We always, really always want associative arrays - self::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC); + // send http status 503 + header('HTTP/1.1 503 Service Temporarily Unavailable'); + header('Status: 503 Service Temporarily Unavailable'); + OC_Template::printErrorPage('Failed to connect to database'); + die(); + } } - - // we are done. great! return true; } @@ -306,34 +200,19 @@ class OC_DB { * @param int $limit * @param int $offset * @param bool $isManipulation - * @return MDB2_Statement_Common prepared SQL query + * @throws DatabaseException + * @return \Doctrine\DBAL\Statement prepared SQL query * - * SQL query via MDB2 prepare(), needs to be execute()'d! + * SQL query via Doctrine prepare(), needs to be execute()'d! */ static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) { if (!is_null($limit) && $limit != -1) { - if (self::$backend == self::BACKEND_MDB2) { - //MDB2 uses or emulates limits & offset internally - self::$MDB2->setLimit($limit, $offset); - } else { - //PDO does not handle limit and offset. - //FIXME: check limit notation for other dbs - //the following sql thus might needs to take into account db ways of representing it - //(oracle has no LIMIT / OFFSET) - $limit = (int)$limit; - $limitsql = ' LIMIT ' . $limit; - if (!is_null($offset)) { - $offset = (int)$offset; - $limitsql .= ' OFFSET ' . $offset; - } - //insert limitsql - if (substr($query, -1) == ';') { //if query ends with ; - $query = substr($query, 0, -1) . $limitsql . ';'; - } else { - $query.=$limitsql; - } + if ($limit === -1) { + $limit = null; } + $platform = self::$connection->getDatabasePlatform(); + $query = $platform->modifyLimitQuery($query, $limit, $offset); } else { if (isset(self::$preparedQueries[$query]) and self::$cachingEnabled) { return self::$preparedQueries[$query]; @@ -354,26 +233,14 @@ class OC_DB { } // return the result - if(self::$backend==self::BACKEND_MDB2) { - // differentiate between query and manipulation - if ($isManipulation) { - $result = self::$connection->prepare( $query, null, MDB2_PREPARE_MANIP ); - } else { - $result = self::$connection->prepare( $query, null, MDB2_PREPARE_RESULT ); - } - - // Die if we have an error (error means: bad query, not 0 results!) - if( self::isError($result)) { - throw new DatabaseException($result->getMessage(), $query); - } - }else{ - try{ + if (self::$backend == self::BACKEND_DOCTRINE) { + try { $result=self::$connection->prepare($query); - }catch(PDOException $e) { - throw new DatabaseException($e->getMessage(), $query); + } catch(\Doctrine\DBAL\DBALException $e) { + throw new \DatabaseException($e->getMessage(), $query); } // differentiate between query and manipulation - $result = new PDOStatementWrapper($result, $isManipulation); + $result=new OC_DB_StatementWrapper($result, $isManipulation); } if ((is_null($limit) || $limit == -1) and self::$cachingEnabled ) { $type = OC_Config::getValue( "dbtype", "sqlite" ); @@ -412,7 +279,7 @@ class OC_DB { /** * @brief execute a prepared statement, on error write log and throw exception - * @param mixed $stmt PDOStatementWrapper | MDB2_Statement_Common , + * @param mixed $stmt OC_DB_StatementWrapper, * an array with 'sql' and optionally 'limit' and 'offset' keys * .. or a simple sql query string * @param array $parameters @@ -445,7 +312,7 @@ class OC_DB { $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']); } self::raiseExceptionOnError($stmt, 'Could not prepare statement'); - if ($stmt instanceof PDOStatementWrapper || $stmt instanceof MDB2_Statement_Common) { + if ($stmt instanceof OC_DB_StatementWrapper) { $result = $stmt->execute($parameters); self::raiseExceptionOnError($result, 'Could not execute statement'); } else { @@ -465,7 +332,7 @@ class OC_DB { * @return int id * @throws DatabaseException * - * MDB2 lastInsertID() + * \Doctrine\DBAL\Connection lastInsertId * * Call this method right after the insert command or other functions may * cause trouble! @@ -478,12 +345,20 @@ class OC_DB { $row = $result->fetchRow(); self::raiseExceptionOnError($row, 'fetching row for insertid failed'); return $row['id']; - } else if( $type === 'mssql' || $type === 'oci') { + } else if( $type === 'mssql') { if($table !== null) { $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); $table = str_replace( '*PREFIX*', $prefix, $table ); } - $result = self::$connection->lastInsertId($table); + return self::$connection->lastInsertId($table); + } + if( $type === 'oci' ) { + if($table !== null) { + $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); + $suffix = '_SEQ'; + $table = '"'.str_replace( '*PREFIX*', $prefix, $table ).$suffix.'"'; + } + return self::$connection->lastInsertId($table); } else { if($table !== null) { $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); @@ -505,18 +380,14 @@ class OC_DB { public static function disconnect() { // Cut connection if required if(self::$connection) { - if(self::$backend==self::BACKEND_MDB2) { - self::$connection->disconnect(); - } self::$connection=false; - self::$MDB2=false; - self::$PDO=false; + self::$DOCTRINE=false; } return true; } - /** + /** else { * @brief saves database scheme to xml file * @param string $file name of file * @param int $mode @@ -525,18 +396,8 @@ class OC_DB { * TODO: write more documentation */ public static function getDbStructure( $file, $mode=MDB2_SCHEMA_DUMP_STRUCTURE) { - self::connectScheme(); - - // write the scheme - $definition = self::$schema->getDefinitionFromDatabase(); - $dump_options = array( - 'output_mode' => 'file', - 'output' => $file, - 'end_of_line' => "\n" - ); - self::$schema->dumpDatabase( $definition, $dump_options, $mode ); - - return true; + self::connectDoctrine(); + return OC_DB_Schema::getDbStructure(self::$DOCTRINE, $file); } /** @@ -547,134 +408,25 @@ class OC_DB { * TODO: write more documentation */ public static function createDbFromStructure( $file ) { - $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" ); - $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); - $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" ); - - // cleanup the cached queries - self::$preparedQueries = array(); - - self::connectScheme(); - - // read file - $content = file_get_contents( $file ); - - // Make changes and save them to an in-memory file - $file2 = 'static://db_scheme'; - $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); - $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); - /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1] - * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere - * [1] http://bugs.mysql.com/bug.php?id=27645 - * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html - * http://www.postgresql.org/docs/8.1/static/functions-datetime.html - * http://www.sqlite.org/lang_createtable.html - * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm - */ - if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't - $content = str_replace( '<default>0000-00-00 00:00:00</default>', - '<default>CURRENT_TIMESTAMP</default>', $content ); - } - - file_put_contents( $file2, $content ); - - // Try to create tables - $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - - //clean up memory - unlink( $file2 ); - - self::raiseExceptionOnError($definition,'Failed to parse the database definition'); - - if(OC_Config::getValue('dbtype', 'sqlite')==='oci') { - unset($definition['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE - $oldname = $definition['name']; - $definition['name']=OC_Config::getValue( "dbuser", $oldname ); - } - - // we should never drop a database - $definition['overwrite'] = false; - - $ret=self::$schema->createDatabase( $definition ); - - self::raiseExceptionOnError($ret,'Failed to create the database structure'); - - return true; + self::connectDoctrine(); + return OC_DB_Schema::createDbFromStructure(self::$DOCTRINE, $file); } /** * @brief update the database scheme * @param string $file file to read structure from + * @throws Exception * @return bool */ public static function updateDbFromStructure($file) { - $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); - $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" ); - - self::connectScheme(); - - if(OC_Config::getValue('dbtype', 'sqlite')==='oci') { - //set dbname, it is unset because oci uses 'service' to connect - self::$schema->db->database_name=self::$schema->db->dsn['username']; - } - - // read file - $content = file_get_contents( $file ); - - $previousSchema = self::$schema->getDefinitionFromDatabase(); - self::raiseExceptionOnError($previousSchema,'Failed to get existing database structure for updating'); - - // Make changes and save them to an in-memory file - $file2 = 'static://db_scheme'; - $content = str_replace( '*dbname*', $previousSchema['name'], $content ); - $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); - /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1] - * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere - * [1] http://bugs.mysql.com/bug.php?id=27645 - * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html - * http://www.postgresql.org/docs/8.1/static/functions-datetime.html - * http://www.sqlite.org/lang_createtable.html - * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm - */ - if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't - $content = str_replace( '<default>0000-00-00 00:00:00</default>', - '<default>CURRENT_TIMESTAMP</default>', $content ); - } - if(OC_Config::getValue('dbtype', 'sqlite')==='oci') { - unset($previousSchema['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE - $oldname = $previousSchema['name']; - $previousSchema['name']=OC_Config::getValue( "dbuser", $oldname ); - //TODO check identifiers are at most 30 chars long - } - file_put_contents( $file2, $content ); - $op = self::$schema->updateDatabase($file2, $previousSchema, array(), false); - - //clean up memory - unlink( $file2 ); - - self::raiseExceptionOnError($op,'Failed to update database structure'); - return true; - } - - /** - * @brief connects to a MDB2 database scheme - * @returns bool - * - * Connects to a MDB2 database scheme - */ - private static function connectScheme() { - // We need a mdb2 database connection - self::connectMDB2(); - self::$MDB2->loadModule('Manager'); - self::$MDB2->loadModule('Reverse'); - - // Connect if this did not happen before - if(!self::$schema) { - require_once 'MDB2/Schema.php'; - self::$schema=MDB2_Schema::factory(self::$MDB2); + self::connectDoctrine(); + try { + $result = OC_DB_Schema::updateDbFromStructure(self::$DOCTRINE, $file); + } catch (Exception $e) { + OC_Log::write('core', 'Failed to update database structure ('.$e.')', OC_Log::FATAL); + throw $e; } - - return true; + return $result; } /** @@ -733,7 +485,7 @@ class OC_DB { try { $result = self::executeAudited($query, $inserts); - } catch(PDOException $e) { + } catch(\Doctrine\DBAL\DBALException $e) { OC_Template::printExceptionErrorPage( $e ); } @@ -765,14 +517,14 @@ class OC_DB { $query = str_replace( '`', '"', $query ); $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query ); $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query ); - }elseif( $type == 'pgsql' ) { + } elseif( $type == 'pgsql' ) { $query = str_replace( '`', '"', $query ); $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)', $query ); - }elseif( $type == 'oci' ) { + } elseif( $type == 'oci' ) { $query = str_replace( '`', '"', $query ); $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query ); - $query = str_ireplace( 'UNIX_TIMESTAMP()', '((CAST(SYS_EXTRACT_UTC(systimestamp) AS DATE))-TO_DATE(\'1970101000000\',\'YYYYMMDDHH24MiSS\'))*24*3600', $query ); + $query = str_ireplace( 'UNIX_TIMESTAMP()', "(cast(sys_extract_utc(systimestamp) as date) - date'1970-01-01') * 86400", $query ); }elseif( $type == 'mssql' ) { $query = preg_replace( "/\`(.*?)`/", "[$1]", $query ); $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query ); @@ -848,9 +600,8 @@ class OC_DB { * @param string $tableName the table to drop */ public static function dropTable($tableName) { - self::connectMDB2(); - self::$MDB2->loadModule('Manager'); - self::$MDB2->dropTable($tableName); + self::connectDoctrine(); + OC_DB_Schema::dropTable(self::$DOCTRINE, $tableName); } /** @@ -858,50 +609,17 @@ class OC_DB { * @param string $file the xml file describing the tables */ public static function removeDBStructure($file) { - $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" ); - $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); - self::connectScheme(); - - // read file - $content = file_get_contents( $file ); - - // Make changes and save them to a temporary file - $file2 = tempnam( get_temp_dir(), 'oc_db_scheme_' ); - $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); - $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); - file_put_contents( $file2, $content ); - - // get the tables - $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - - // Delete our temporary file - unlink( $file2 ); - $tables=array_keys($definition['tables']); - foreach($tables as $table) { - self::dropTable($table); - } + self::connectDoctrine(); + OC_DB_Schema::removeDBStructure(self::$DOCTRINE, $file); } /** - * @brief replaces the owncloud tables with a new set + * @brief replaces the ownCloud tables with a new set * @param $file string path to the MDB2 xml db export file */ public static function replaceDB( $file ) { - $apps = OC_App::getAllApps(); - self::beginTransaction(); - // Delete the old tables - self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' ); - - foreach($apps as $app) { - $path = OC_App::getAppPath($app).'/appinfo/database.xml'; - if(file_exists($path)) { - self::removeDBStructure( $path ); - } - } - - // Create new tables - self::createDBFromStructure( $file ); - self::commit(); + self::connectDoctrine(); + OC_DB_Schema::replaceDB(self::$DOCTRINE, $file); } /** @@ -910,9 +628,6 @@ class OC_DB { */ public static function beginTransaction() { self::connect(); - if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) { - return false; - } self::$connection->beginTransaction(); self::$inTransaction=true; return true; @@ -933,24 +648,16 @@ class OC_DB { } /** - * check if a result is an error, works with MDB2 and PDOException + * check if a result is an error, works with Doctrine * @param mixed $result * @return bool */ public static function isError($result) { - //MDB2 returns an MDB2_Error object - if (class_exists('PEAR') === true && PEAR::isError($result)) { - return true; - } - //PDO returns false on error (and throws an exception) - if (self::$backend===self::BACKEND_PDO and $result === false) { - return true; - } - - return false; + //Doctrine returns false on error (and throws an exception) + return $result === false; } /** - * check if a result is an error and throws an exception, works with MDB2 and PDOException + * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException * @param mixed $result * @param string $message * @return void @@ -968,32 +675,19 @@ class OC_DB { } public static function getErrorCode($error) { - if ( class_exists('PEAR') === true && PEAR::isError($error) ) { - /** @var $error PEAR_Error */ - return $error->getCode(); - } - if ( self::$backend==self::BACKEND_PDO and self::$PDO ) { - return self::$PDO->errorCode(); - } - - return -1; + $code = self::$connection->errorCode(); + return $code; } /** * returns the error code and message as a string for logging - * works with MDB2 and PDOException + * works with DoctrineException * @param mixed $error * @return string */ public static function getErrorMessage($error) { - if ( class_exists('PEAR') === true && PEAR::isError($error) ) { - $msg = $error->getCode() . ': ' . $error->getMessage(); - $msg .= ' (' . $error->getDebugInfo() . ')'; - - return $msg; - } - if (self::$backend==self::BACKEND_PDO and self::$PDO) { - $msg = self::$PDO->errorCode() . ': '; - $errorInfo = self::$PDO->errorInfo(); + if (self::$backend==self::BACKEND_DOCTRINE and self::$DOCTRINE) { + $msg = self::$DOCTRINE->errorCode() . ': '; + $errorInfo = self::$DOCTRINE->errorInfo(); if (is_array($errorInfo)) { $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; $msg .= 'Driver Code = '.$errorInfo[1] . ', '; @@ -1015,180 +709,3 @@ class OC_DB { self::$cachingEnabled = $enabled; } } - -/** - * small wrapper around PDOStatement to make it behave ,more like an MDB2 Statement - */ -class PDOStatementWrapper{ - /** - * @var PDOStatement - */ - private $statement = null; - private $isManipulation = false; - private $lastArguments = array(); - - public function __construct($statement, $isManipulation = false) { - $this->statement = $statement; - $this->isManipulation = $isManipulation; - } - - /** - * make execute return the result or updated row count instead of a bool - */ - public function execute($input=array()) { - if(OC_Config::getValue( "log_query", false)) { - $params_str = str_replace("\n"," ",var_export($input,true)); - OC_Log::write('core', 'DB execute with arguments : '.$params_str, OC_Log::DEBUG); - } - $this->lastArguments = $input; - if (count($input) > 0) { - - if (!isset($type)) { - $type = OC_Config::getValue( "dbtype", "sqlite" ); - } - - if ($type == 'mssql') { - $input = $this->tryFixSubstringLastArgumentDataForMSSQL($input); - } - - $result = $this->statement->execute($input); - } else { - $result = $this->statement->execute(); - } - - if ($result === false) { - return false; - } - if ($this->isManipulation) { - return $this->statement->rowCount(); - } else { - return $this; - } - } - - private function tryFixSubstringLastArgumentDataForMSSQL($input) { - $query = $this->statement->queryString; - $pos = stripos ($query, 'SUBSTRING'); - - if ( $pos === false) { - return; - } - - try { - $newQuery = ''; - - $cArg = 0; - - $inSubstring = false; - - // Create new query - for ($i = 0; $i < strlen ($query); $i++) { - if ($inSubstring == false) { - // Defines when we should start inserting values - if (substr ($query, $i, 9) == 'SUBSTRING') { - $inSubstring = true; - } - } else { - // Defines when we should stop inserting values - if (substr ($query, $i, 1) == ')') { - $inSubstring = false; - } - } - - if (substr ($query, $i, 1) == '?') { - // We found a question mark - if ($inSubstring) { - $newQuery .= $input[$cArg]; - - // - // Remove from input array - // - array_splice ($input, $cArg, 1); - } else { - $newQuery .= substr ($query, $i, 1); - $cArg++; - } - } else { - $newQuery .= substr ($query, $i, 1); - } - } - - // The global data we need - $name = OC_Config::getValue( "dbname", "owncloud" ); - $host = OC_Config::getValue( "dbhost", "" ); - $user = OC_Config::getValue( "dbuser", "" ); - $pass = OC_Config::getValue( "dbpassword", "" ); - if (strpos($host,':')) { - list($host, $port) = explode(':', $host, 2); - } else { - $port = false; - } - $opts = array(); - - if ($port) { - $dsn = 'sqlsrv:Server='.$host.','.$port.';Database='.$name; - } else { - $dsn = 'sqlsrv:Server='.$host.';Database='.$name; - } - - $PDO = new PDO($dsn, $user, $pass, $opts); - $PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - $this->statement = $PDO->prepare($newQuery); - - $this->lastArguments = $input; - - return $input; - } catch (PDOException $e){ - $entry = 'PDO DB Error: "'.$e->getMessage().'"<br />'; - $entry .= 'Offending command was: '.$this->statement->queryString .'<br />'; - $entry .= 'Input parameters: ' .print_r($input, true).'<br />'; - $entry .= 'Stack trace: ' .$e->getTraceAsString().'<br />'; - OC_Log::write('core', $entry, OC_Log::FATAL); - OC_User::setUserId(null); - - // send http status 503 - header('HTTP/1.1 503 Service Temporarily Unavailable'); - header('Status: 503 Service Temporarily Unavailable'); - OC_Template::printErrorPage('Failed to connect to database'); - die ($entry); - } - } - - /** - * provide numRows - */ - public function numRows() { - $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; - if (preg_match($regex, $this->statement->queryString, $output) > 0) { - $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}"); - return $query->execute($this->lastArguments)->fetchColumn(); - }else{ - return $this->statement->rowCount(); - } - } - - /** - * provide an alias for fetch - */ - public function fetchRow() { - return $this->statement->fetch(); - } - - /** - * pass all other function directly to the PDOStatement - */ - public function __call($name, $arguments) { - return call_user_func_array(array($this->statement, $name), $arguments); - } - - /** - * Provide a simple fetchOne. - * fetch single column from the next row - * @param int $colnum the column number to fetch - */ - public function fetchOne($colnum = 0) { - return $this->statement->fetchColumn($colnum); - } -} |