diff options
author | Thomas Müller <thomas.mueller@tmit.eu> | 2013-09-25 13:36:30 +0200 |
---|---|---|
committer | Thomas Müller <thomas.mueller@tmit.eu> | 2013-09-30 16:36:59 +0200 |
commit | 9c9dc276b7a1d2592c4fb0a887888632dc1f1e29 (patch) | |
tree | bbe3aed3e09c31c68806bdb8acffef70ba08f51c /lib/db | |
parent | a711399e62d5a9f14d4b748efe4354ee37e61f13 (diff) | |
download | nextcloud-server-9c9dc276b7a1d2592c4fb0a887888632dc1f1e29.tar.gz nextcloud-server-9c9dc276b7a1d2592c4fb0a887888632dc1f1e29.zip |
move the private namespace OC into lib/private - OCP will stay in lib/public
Conflicts:
lib/private/vcategories.php
Diffstat (limited to 'lib/db')
-rw-r--r-- | lib/db/adapter.php | 72 | ||||
-rw-r--r-- | lib/db/adapteroci8.php | 28 | ||||
-rw-r--r-- | lib/db/adapterpgsql.php | 23 | ||||
-rw-r--r-- | lib/db/adaptersqlite.php | 60 | ||||
-rw-r--r-- | lib/db/adaptersqlsrv.php | 28 | ||||
-rw-r--r-- | lib/db/connection.php | 197 | ||||
-rw-r--r-- | lib/db/mdb2schemamanager.php | 150 | ||||
-rw-r--r-- | lib/db/mdb2schemareader.php | 305 | ||||
-rw-r--r-- | lib/db/mdb2schemawriter.php | 133 | ||||
-rw-r--r-- | lib/db/oracleconnection.php | 50 | ||||
-rw-r--r-- | lib/db/statementwrapper.php | 191 |
11 files changed, 0 insertions, 1237 deletions
diff --git a/lib/db/adapter.php b/lib/db/adapter.php deleted file mode 100644 index 6b31f37dd98..00000000000 --- a/lib/db/adapter.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace OC\DB; - -/** - * This handles the way we use to write queries, into something that can be - * handled by the database abstraction layer. - */ -class Adapter { - - /** - * @var \OC\DB\Connection $conn - */ - protected $conn; - - public function __construct($conn) { - $this->conn = $conn; - } - - /** - * @param string $table name - * @return int id of last insert statement - */ - public function lastInsertId($table) { - return $this->conn->realLastInsertId($table); - } - - /** - * @param string $statement that needs to be changed so the db can handle it - * @return string changed statement - */ - public function fixupStatement($statement) { - return $statement; - } - - /** - * @brief insert the @input values when they do not exist yet - * @param string $table name - * @param array $input key->value pairs - * @return int count of inserted rows - */ - public function insertIfNotExist($table, $input) { - $query = 'INSERT INTO `' .$table . '` (`' - . implode('`,`', array_keys($input)) . '`) SELECT ' - . str_repeat('?,', count($input)-1).'? ' // Is there a prettier alternative? - . 'FROM `' . $table . '` WHERE '; - - foreach($input as $key => $value) { - $query .= '`' . $key . '` = ? AND '; - } - $query = substr($query, 0, strlen($query) - 5); - $query .= ' HAVING COUNT(*) = 0'; - $inserts = array_values($input); - $inserts = array_merge($inserts, $inserts); - - try { - return $this->conn->executeUpdate($query, $inserts); - } catch(\Doctrine\DBAL\DBALException $e) { - $entry = 'DB Error: "'.$e->getMessage() . '"<br />'; - $entry .= 'Offending command was: ' . $query.'<br />'; - \OC_Log::write('core', $entry, \OC_Log::FATAL); - error_log('DB error: ' . $entry); - \OC_Template::printErrorPage( $entry ); - } - } -} diff --git a/lib/db/adapteroci8.php b/lib/db/adapteroci8.php deleted file mode 100644 index bc226e979ec..00000000000 --- a/lib/db/adapteroci8.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - - -namespace OC\DB; - -class AdapterOCI8 extends Adapter { - public function lastInsertId($table) { - if($table !== null) { - $suffix = '_SEQ'; - $table = '"'.$table.$suffix.'"'; - } - return $this->conn->realLastInsertId($table); - } - - const UNIX_TIMESTAMP_REPLACEMENT = "(cast(sys_extract_utc(systimestamp) as date) - date'1970-01-01') * 86400"; - public function fixupStatement($statement) { - $statement = str_replace( '`', '"', $statement ); - $statement = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $statement ); - $statement = str_ireplace( 'UNIX_TIMESTAMP()', self::UNIX_TIMESTAMP_REPLACEMENT, $statement ); - return $statement; - } -} diff --git a/lib/db/adapterpgsql.php b/lib/db/adapterpgsql.php deleted file mode 100644 index 990d71c9f29..00000000000 --- a/lib/db/adapterpgsql.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - - -namespace OC\DB; - -class AdapterPgSql extends Adapter { - public function lastInsertId($table) { - return $this->conn->fetchColumn('SELECT lastval()'); - } - - const UNIX_TIMESTAMP_REPLACEMENT = 'cast(extract(epoch from current_timestamp) as integer)'; - public function fixupStatement($statement) { - $statement = str_replace( '`', '"', $statement ); - $statement = str_ireplace( 'UNIX_TIMESTAMP()', self::UNIX_TIMESTAMP_REPLACEMENT, $statement ); - return $statement; - } -} diff --git a/lib/db/adaptersqlite.php b/lib/db/adaptersqlite.php deleted file mode 100644 index fa6d308ae32..00000000000 --- a/lib/db/adaptersqlite.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - - -namespace OC\DB; - -class AdapterSqlite extends Adapter { - public function fixupStatement($statement) { - $statement = str_replace( '`', '"', $statement ); - $statement = str_ireplace( 'NOW()', 'datetime(\'now\')', $statement ); - $statement = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $statement ); - return $statement; - } - - public function insertIfNotExist($table, $input) { - // NOTE: For SQLite we have to use this clumsy approach - // otherwise all fieldnames used must have a unique key. - $query = 'SELECT COUNT(*) FROM `' . $table . '` WHERE '; - foreach($input as $key => $value) { - $query .= '`' . $key . '` = ? AND '; - } - $query = substr($query, 0, strlen($query) - 5); - try { - $stmt = $this->conn->prepare($query); - $result = $stmt->execute(array_values($input)); - } catch(\Doctrine\DBAL\DBALException $e) { - $entry = 'DB Error: "'.$e->getMessage() . '"<br />'; - $entry .= 'Offending command was: ' . $query . '<br />'; - \OC_Log::write('core', $entry, \OC_Log::FATAL); - error_log('DB error: '.$entry); - \OC_Template::printErrorPage( $entry ); - } - - if ($stmt->fetchColumn() === '0') { - $query = 'INSERT INTO `' . $table . '` (`' - . implode('`,`', array_keys($input)) . '`) VALUES(' - . str_repeat('?,', count($input)-1).'? ' . ')'; - } else { - return 0; //no rows updated - } - - try { - $statement = $this->conn->prepare($query); - $result = $statement->execute(array_values($input)); - } catch(\Doctrine\DBAL\DBALException $e) { - $entry = 'DB Error: "'.$e->getMessage() . '"<br />'; - $entry .= 'Offending command was: ' . $query.'<br />'; - \OC_Log::write('core', $entry, \OC_Log::FATAL); - error_log('DB error: ' . $entry); - \OC_Template::printErrorPage( $entry ); - } - - return $result; - } -} diff --git a/lib/db/adaptersqlsrv.php b/lib/db/adaptersqlsrv.php deleted file mode 100644 index d0a67af28a7..00000000000 --- a/lib/db/adaptersqlsrv.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - - -namespace OC\DB; - -class AdapterSQLSrv extends Adapter { - public function lastInsertId($table) { - if($table !== null) { - $table = $this->conn->replaceTablePrefix( $table ); - } - return $this->conn->lastInsertId($table); - } - - public function fixupStatement($statement) { - $statement = preg_replace( "/\`(.*?)`/", "[$1]", $statement ); - $statement = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $statement ); - $statement = str_replace( 'LENGTH(', 'LEN(', $statement ); - $statement = str_replace( 'SUBSTR(', 'SUBSTRING(', $statement ); - $statement = str_ireplace( 'UNIX_TIMESTAMP()', 'DATEDIFF(second,{d \'1970-01-01\'},GETDATE())', $statement ); - return $statement; - } -} diff --git a/lib/db/connection.php b/lib/db/connection.php deleted file mode 100644 index 2d3193a148a..00000000000 --- a/lib/db/connection.php +++ /dev/null @@ -1,197 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace OC\DB; -use Doctrine\DBAL\Driver; -use Doctrine\DBAL\Configuration; -use Doctrine\DBAL\Cache\QueryCacheProfile; -use Doctrine\Common\EventManager; - -class Connection extends \Doctrine\DBAL\Connection implements \OCP\IDBConnection { - /** - * @var string $tablePrefix - */ - protected $tablePrefix; - - /** - * @var \OC\DB\Adapter $adapter - */ - protected $adapter; - - /** - * @var \Doctrine\DBAL\Driver\Statement[] $preparedQueries - */ - protected $preparedQueries = array(); - - protected $cachingQueryStatementEnabled = true; - - /** - * Initializes a new instance of the Connection class. - * - * @param array $params The connection parameters. - * @param \Doctrine\DBAL\Driver $driver - * @param \Doctrine\DBAL\Configuration $config - * @param \Doctrine\Common\EventManager $eventManager - * @throws \Exception - */ - public function __construct(array $params, Driver $driver, Configuration $config = null, - EventManager $eventManager = null) - { - if (!isset($params['adapter'])) { - throw new \Exception('adapter not set'); - } - if (!isset($params['tablePrefix'])) { - throw new \Exception('tablePrefix not set'); - } - parent::__construct($params, $driver, $config, $eventManager); - $this->adapter = new $params['adapter']($this); - $this->tablePrefix = $params['tablePrefix']; - } - - /** - * Prepares an SQL statement. - * - * @param string $statement The SQL statement to prepare. - * @param int $limit - * @param int $offset - * @return \Doctrine\DBAL\Driver\Statement The prepared statement. - */ - public function prepare( $statement, $limit=null, $offset=null ) { - if ($limit === -1) { - $limit = null; - } - if (!is_null($limit)) { - $platform = $this->getDatabasePlatform(); - $statement = $platform->modifyLimitQuery($statement, $limit, $offset); - } else { - if (isset($this->preparedQueries[$statement]) && $this->cachingQueryStatementEnabled) { - return $this->preparedQueries[$statement]; - } - $origStatement = $statement; - } - $statement = $this->replaceTablePrefix($statement); - $statement = $this->adapter->fixupStatement($statement); - - if(\OC_Config::getValue( 'log_query', false)) { - \OC_Log::write('core', 'DB prepare : '.$statement, \OC_Log::DEBUG); - } - $result = parent::prepare($statement); - if (is_null($limit) && $this->cachingQueryStatementEnabled) { - $this->preparedQueries[$origStatement] = $result; - } - return $result; - } - - /** - * Executes an, optionally parameterized, SQL query. - * - * If the query is parameterized, a prepared statement is used. - * If an SQLLogger is configured, the execution is logged. - * - * @param string $query The SQL query to execute. - * @param array $params The parameters to bind to the query, if any. - * @param array $types The types the previous parameters are in. - * @param QueryCacheProfile $qcp - * @return \Doctrine\DBAL\Driver\Statement The executed statement. - * @internal PERF: Directly prepares a driver statement, not a wrapper. - */ - public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) - { - $query = $this->replaceTablePrefix($query); - $query = $this->adapter->fixupStatement($query); - return parent::executeQuery($query, $params, $types, $qcp); - } - - /** - * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters - * and returns the number of affected rows. - * - * This method supports PDO binding types as well as DBAL mapping types. - * - * @param string $query The SQL query. - * @param array $params The query parameters. - * @param array $types The parameter types. - * @return integer The number of affected rows. - * @internal PERF: Directly prepares a driver statement, not a wrapper. - */ - public function executeUpdate($query, array $params = array(), array $types = array()) - { - $query = $this->replaceTablePrefix($query); - $query = $this->adapter->fixupStatement($query); - return parent::executeUpdate($query, $params, $types); - } - - /** - * Returns the ID of the last inserted row, or the last value from a sequence object, - * depending on the underlying driver. - * - * Note: This method may not return a meaningful or consistent result across different drivers, - * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY - * columns or sequences. - * - * @param string $seqName Name of the sequence object from which the ID should be returned. - * @return string A string representation of the last inserted ID. - */ - public function lastInsertId($seqName = null) - { - if ($seqName) { - $seqName = $this->replaceTablePrefix($seqName); - } - return $this->adapter->lastInsertId($seqName); - } - - // internal use - public function realLastInsertId($seqName = null) - { - return parent::lastInsertId($seqName); - } - - /** - * @brief Insert a row if a matching row doesn't exists. - * @param string $table. The table to insert into in the form '*PREFIX*tableName' - * @param array $input. An array of fieldname/value pairs - * @return bool The return value from execute() - */ - public function insertIfNotExist($table, $input) { - return $this->adapter->insertIfNotExist($table, $input); - } - - /** - * returns the error code and message as a string for logging - * works with DoctrineException - * @return string - */ - public function getError() { - $msg = $this->errorCode() . ': '; - $errorInfo = $this->errorInfo(); - if (is_array($errorInfo)) { - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; - $msg .= 'Driver Message = '.$errorInfo[2]; - } - return $msg; - } - - // internal use - /** - * @param string $statement - * @return string - */ - protected function replaceTablePrefix($statement) { - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); - } - - public function enableQueryStatementCaching() { - $this->cachingQueryStatementEnabled = true; - } - - public function disableQueryStatementCaching() { - $this->cachingQueryStatementEnabled = false; - $this->preparedQueries = array(); - } -} diff --git a/lib/db/mdb2schemamanager.php b/lib/db/mdb2schemamanager.php deleted file mode 100644 index 8e76f46c78f..00000000000 --- a/lib/db/mdb2schemamanager.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php -/** - * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace OC\DB; - -class MDB2SchemaManager { - /** - * @var \OC\DB\Connection $conn - */ - protected $conn; - - /** - * @param \OC\DB\Connection $conn - */ - public function __construct($conn) { - $this->conn = $conn; - } - - /** - * @brief saves database scheme to xml file - * @param string $file name of file - * @param int|string $mode - * @return bool - * - * TODO: write more documentation - */ - public function getDbStructure( $file, $mode = MDB2_SCHEMA_DUMP_STRUCTURE) { - $sm = $this->conn->getSchemaManager(); - - return \OC_DB_MDB2SchemaWriter::saveSchemaToFile($file, $sm); - } - - /** - * @brief Creates tables from XML file - * @param string $file file to read structure from - * @return bool - * - * TODO: write more documentation - */ - public function createDbFromStructure( $file ) { - $schemaReader = new MDB2SchemaReader(\OC_Config::getObject(), $this->conn->getDatabasePlatform()); - $toSchema = $schemaReader->loadSchemaFromFile($file); - return $this->executeSchemaChange($toSchema); - } - - /** - * @brief update the database scheme - * @param string $file file to read structure from - * @return bool - */ - public function updateDbFromStructure($file) { - $sm = $this->conn->getSchemaManager(); - $fromSchema = $sm->createSchema(); - - $schemaReader = new MDB2SchemaReader(\OC_Config::getObject(), $this->conn->getDatabasePlatform()); - $toSchema = $schemaReader->loadSchemaFromFile($file); - - // remove tables we don't know about - foreach($fromSchema->getTables() as $table) { - if (!$toSchema->hasTable($table->getName())) { - $fromSchema->dropTable($table->getName()); - } - } - // remove sequences we don't know about - foreach($fromSchema->getSequences() as $table) { - if (!$toSchema->hasSequence($table->getName())) { - $fromSchema->dropSequence($table->getName()); - } - } - - $comparator = new \Doctrine\DBAL\Schema\Comparator(); - $schemaDiff = $comparator->compare($fromSchema, $toSchema); - - $platform = $this->conn->getDatabasePlatform(); - $tables = $schemaDiff->newTables + $schemaDiff->changedTables + $schemaDiff->removedTables; - foreach($tables as $tableDiff) { - $tableDiff->name = $platform->quoteIdentifier($tableDiff->name); - } - - return $this->executeSchemaChange($schemaDiff); - } - - /** - * @brief drop a table - * @param string $tableName the table to drop - */ - public function dropTable($tableName) { - $sm = $this->conn->getSchemaManager(); - $fromSchema = $sm->createSchema(); - $toSchema = clone $fromSchema; - $toSchema->dropTable($tableName); - $sql = $fromSchema->getMigrateToSql($toSchema, $this->conn->getDatabasePlatform()); - $this->conn->executeQuery($sql); - } - - /** - * remove all tables defined in a database structure xml file - * @param string $file the xml file describing the tables - */ - public function removeDBStructure($file) { - $schemaReader = new MDB2SchemaReader(\OC_Config::getObject(), $this->conn->getDatabasePlatform()); - $fromSchema = $schemaReader->loadSchemaFromFile($file); - $toSchema = clone $fromSchema; - foreach($toSchema->getTables() as $table) { - $toSchema->dropTable($table->getName()); - } - $comparator = new \Doctrine\DBAL\Schema\Comparator(); - $schemaDiff = $comparator->compare($fromSchema, $toSchema); - $this->executeSchemaChange($schemaDiff); - } - - /** - * @brief replaces the ownCloud tables with a new set - * @param $file string path to the MDB2 xml db export file - */ - public function replaceDB( $file ) { - $apps = \OC_App::getAllApps(); - $this->conn->beginTransaction(); - // Delete the old tables - $this->removeDBStructure( \OC::$SERVERROOT . '/db_structure.xml' ); - - foreach($apps as $app) { - $path = \OC_App::getAppPath($app).'/appinfo/database.xml'; - if(file_exists($path)) { - $this->removeDBStructure( $path ); - } - } - - // Create new tables - $this->conn->commit(); - } - - /** - * @param \Doctrine\DBAL\Schema\Schema $schema - * @return bool - */ - private function executeSchemaChange($schema) { - $this->conn->beginTransaction(); - foreach($schema->toSql($this->conn->getDatabasePlatform()) as $sql) { - $this->conn->query($sql); - } - $this->conn->commit(); - return true; - } -} diff --git a/lib/db/mdb2schemareader.php b/lib/db/mdb2schemareader.php deleted file mode 100644 index b7128a2f176..00000000000 --- a/lib/db/mdb2schemareader.php +++ /dev/null @@ -1,305 +0,0 @@ -<?php -/** - * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace OC\DB; - -class MDB2SchemaReader { - /** - * @var string $DBNAME - */ - protected $DBNAME; - - /** - * @var string $DBTABLEPREFIX - */ - protected $DBTABLEPREFIX; - - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ - protected $platform; - - /** - * @param \OC\Config $config - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ - public function __construct($config, $platform) { - $this->platform = $platform; - $this->DBNAME = $config->getValue('dbname', 'owncloud'); - $this->DBTABLEPREFIX = $config->getValue('dbtableprefix', 'oc_'); - } - - /** - * @param string $file - * @return \Doctrine\DBAL\Schema\Schema - * @throws \DomainException - */ - public function loadSchemaFromFile($file) { - $schema = new \Doctrine\DBAL\Schema\Schema(); - $xml = simplexml_load_file($file); - foreach ($xml->children() as $child) { - /** - * @var \SimpleXMLElement $child - */ - switch ($child->getName()) { - case 'name': - case 'create': - case 'overwrite': - case 'charset': - break; - case 'table': - $this->loadTable($schema, $child); - break; - default: - throw new \DomainException('Unknown element: ' . $child->getName()); - - } - } - return $schema; - } - - /** - * @param\Doctrine\DBAL\Schema\Schema $schema - * @param \SimpleXMLElement $xml - * @throws \DomainException - */ - private function loadTable($schema, $xml) { - $table = null; - foreach ($xml->children() as $child) { - /** - * @var \SimpleXMLElement $child - */ - switch ($child->getName()) { - case 'name': - $name = (string)$child; - $name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name); - $name = $this->platform->quoteIdentifier($name); - $table = $schema->createTable($name); - break; - case 'create': - case 'overwrite': - case 'charset': - break; - case 'declaration': - if (is_null($table)) { - throw new \DomainException('Table declaration before table name'); - } - $this->loadDeclaration($table, $child); - break; - default: - throw new \DomainException('Unknown element: ' . $child->getName()); - - } - } - } - - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \SimpleXMLElement $xml - * @throws \DomainException - */ - private function loadDeclaration($table, $xml) { - foreach ($xml->children() as $child) { - /** - * @var \SimpleXMLElement $child - */ - switch ($child->getName()) { - case 'field': - $this->loadField($table, $child); - break; - case 'index': - $this->loadIndex($table, $child); - break; - default: - throw new \DomainException('Unknown element: ' . $child->getName()); - - } - } - } - - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \SimpleXMLElement $xml - * @throws \DomainException - */ - private function loadField($table, $xml) { - $options = array(); - foreach ($xml->children() as $child) { - /** - * @var \SimpleXMLElement $child - */ - switch ($child->getName()) { - case 'name': - $name = (string)$child; - $name = $this->platform->quoteIdentifier($name); - break; - case 'type': - $type = (string)$child; - switch ($type) { - case 'text': - $type = 'string'; - break; - case 'clob': - $type = 'text'; - break; - case 'timestamp': - $type = 'datetime'; - break; - } - break; - case 'length': - $length = (string)$child; - $options['length'] = $length; - break; - case 'unsigned': - $unsigned = $this->asBool($child); - $options['unsigned'] = $unsigned; - break; - case 'notnull': - $notnull = $this->asBool($child); - $options['notnull'] = $notnull; - break; - case 'autoincrement': - $autoincrement = $this->asBool($child); - $options['autoincrement'] = $autoincrement; - break; - case 'default': - $default = (string)$child; - $options['default'] = $default; - break; - case 'comments': - $comment = (string)$child; - $options['comment'] = $comment; - break; - case 'primary': - $primary = $this->asBool($child); - $options['primary'] = $primary; - break; - default: - throw new \DomainException('Unknown element: ' . $child->getName()); - - } - } - if (isset($name) && isset($type)) { - if (empty($options['default'])) { - if (empty($options['notnull']) || !$options['notnull']) { - unset($options['default']); - $options['notnull'] = false; - } else { - $options['default'] = ''; - } - if ($type == 'integer') { - $options['default'] = 0; - } elseif ($type == 'boolean') { - $options['default'] = false; - } - if (!empty($options['autoincrement']) && $options['autoincrement']) { - unset($options['default']); - } - } - if ($type === 'integer' && isset($options['default'])) { - $options['default'] = (int)$options['default']; - } - if ($type === 'integer' && isset($options['length'])) { - $length = $options['length']; - if ($length < 4) { - $type = 'smallint'; - } else if ($length > 4) { - $type = 'bigint'; - } - } - if ($type === 'boolean' && isset($options['default'])) { - $options['default'] = $this->asBool($options['default']); - } - if (!empty($options['autoincrement']) - && !empty($options['notnull']) - ) { - $options['primary'] = true; - } - $table->addColumn($name, $type, $options); - if (!empty($options['primary']) && $options['primary']) { - $table->setPrimaryKey(array($name)); - } - } - } - - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \SimpleXMLElement $xml - * @throws \DomainException - */ - private function loadIndex($table, $xml) { - $name = null; - $fields = array(); - foreach ($xml->children() as $child) { - /** - * @var \SimpleXMLElement $child - */ - switch ($child->getName()) { - case 'name': - $name = (string)$child; - break; - case 'primary': - $primary = $this->asBool($child); - break; - case 'unique': - $unique = $this->asBool($child); - break; - case 'field': - foreach ($child->children() as $field) { - /** - * @var \SimpleXMLElement $field - */ - switch ($field->getName()) { - case 'name': - $field_name = (string)$field; - $field_name = $this->platform->quoteIdentifier($field_name); - $fields[] = $field_name; - break; - case 'sorting': - break; - default: - throw new \DomainException('Unknown element: ' . $field->getName()); - - } - } - break; - default: - throw new \DomainException('Unknown element: ' . $child->getName()); - - } - } - if (!empty($fields)) { - if (isset($primary) && $primary) { - $table->setPrimaryKey($fields, $name); - } else - if (isset($unique) && $unique) { - $table->addUniqueIndex($fields, $name); - } else { - $table->addIndex($fields, $name); - } - } else { - throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true)); - } - } - - /** - * @param \SimpleXMLElement | string $xml - * @return bool - */ - private function asBool($xml) { - $result = (string)$xml; - if ($result == 'true') { - $result = true; - } elseif ($result == 'false') { - $result = false; - } - return (bool)$result; - } - -} diff --git a/lib/db/mdb2schemawriter.php b/lib/db/mdb2schemawriter.php deleted file mode 100644 index 21b43cbfe80..00000000000 --- a/lib/db/mdb2schemawriter.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class OC_DB_MDB2SchemaWriter { - - /** - * @param $file - * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $sm - * @return bool - */ - static public function saveSchemaToFile($file, $sm) { - $xml = new SimpleXMLElement('<database/>'); - $xml->addChild('name', OC_Config::getValue( "dbname", "owncloud" )); - $xml->addChild('create', 'true'); - $xml->addChild('overwrite', 'false'); - $xml->addChild('charset', 'utf8'); - foreach ($sm->listTables() as $table) { - self::saveTable($table, $xml->addChild('table')); - } - file_put_contents($file, $xml->asXML()); - return true; - } - - private static function saveTable($table, $xml) { - $xml->addChild('name', $table->getName()); - $declaration = $xml->addChild('declaration'); - foreach($table->getColumns() as $column) { - self::saveColumn($column, $declaration->addChild('field')); - } - foreach($table->getIndexes() as $index) { - if ($index->getName() == 'PRIMARY') { - $autoincrement = false; - foreach($index->getColumns() as $column) { - if ($table->getColumn($column)->getAutoincrement()) { - $autoincrement = true; - } - } - if ($autoincrement) { - continue; - } - } - self::saveIndex($index, $declaration->addChild('index')); - } - } - - private static function saveColumn($column, $xml) { - $xml->addChild('name', $column->getName()); - switch($column->getType()) { - case 'SmallInt': - case 'Integer': - case 'BigInt': - $xml->addChild('type', 'integer'); - $default = $column->getDefault(); - if (is_null($default) && $column->getAutoincrement()) { - $default = '0'; - } - $xml->addChild('default', $default); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - if ($column->getAutoincrement()) { - $xml->addChild('autoincrement', '1'); - } - if ($column->getUnsigned()) { - $xml->addChild('unsigned', 'true'); - } - $length = '4'; - if ($column->getType() == 'SmallInt') { - $length = '2'; - } - elseif ($column->getType() == 'BigInt') { - $length = '8'; - } - $xml->addChild('length', $length); - break; - case 'String': - $xml->addChild('type', 'text'); - $default = trim($column->getDefault()); - if ($default === '') { - $default = false; - } - $xml->addChild('default', $default); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - $xml->addChild('length', $column->getLength()); - break; - case 'Text': - $xml->addChild('type', 'clob'); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - break; - case 'Decimal': - $xml->addChild('type', 'decimal'); - $xml->addChild('default', $column->getDefault()); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - $xml->addChild('length', '15'); - break; - case 'Boolean': - $xml->addChild('type', 'integer'); - $xml->addChild('default', $column->getDefault()); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - $xml->addChild('length', '1'); - break; - case 'DateTime': - $xml->addChild('type', 'timestamp'); - $xml->addChild('default', $column->getDefault()); - $xml->addChild('notnull', self::toBool($column->getNotnull())); - break; - - } - } - - private static function saveIndex($index, $xml) { - $xml->addChild('name', $index->getName()); - if ($index->isPrimary()) { - $xml->addChild('primary', 'true'); - } - elseif ($index->isUnique()) { - $xml->addChild('unique', 'true'); - } - foreach($index->getColumns() as $column) { - $field = $xml->addChild('field'); - $field->addChild('name', $column); - $field->addChild('sorting', 'ascending'); - - } - } - - private static function toBool($bool) { - return $bool ? 'true' : 'false'; - } -} diff --git a/lib/db/oracleconnection.php b/lib/db/oracleconnection.php deleted file mode 100644 index e2fc4644f47..00000000000 --- a/lib/db/oracleconnection.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace OC\DB; - -class OracleConnection extends Connection { - /** - * Quote the keys of the array - */ - private function quoteKeys(array $data) { - $return = array(); - foreach($data as $key => $value) { - $return[$this->quoteIdentifier($key)] = $value; - } - return $return; - } - - /* - * {@inheritDoc} - */ - public function insert($tableName, array $data, array $types = array()) { - $tableName = $this->quoteIdentifier($tableName); - $data = $this->quoteKeys($data); - return parent::insert($tableName, $data, $types); - } - - /* - * {@inheritDoc} - */ - public function update($tableName, array $data, array $identifier, array $types = array()) { - $tableName = $this->quoteIdentifier($tableName); - $data = $this->quoteKeys($data); - $identifier = $this->quoteKeys($identifier); - return parent::update($tableName, $data, $identifier, $types); - } - - /* - * {@inheritDoc} - */ - public function delete($tableName, array $identifier) { - $tableName = $this->quoteIdentifier($tableName); - $identifier = $this->quoteKeys($identifier); - return parent::delete($tableName, $identifier); - } -} diff --git a/lib/db/statementwrapper.php b/lib/db/statementwrapper.php deleted file mode 100644 index b8da1afc0e5..00000000000 --- a/lib/db/statementwrapper.php +++ /dev/null @@ -1,191 +0,0 @@ -<?php -/** - * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * small wrapper around \Doctrine\DBAL\Driver\Statement to make it behave, more like an MDB2 Statement - */ -class OC_DB_StatementWrapper { - /** - * @var \Doctrine\DBAL\Driver\Statement - */ - private $statement = null; - private $isManipulation = false; - private $lastArguments = array(); - - public function __construct($statement, $isManipulation) { - $this->statement = $statement; - $this->isManipulation = $isManipulation; - } - - /** - * pass all other function directly to the \Doctrine\DBAL\Driver\Statement - */ - public function __call($name,$arguments) { - return call_user_func_array(array($this->statement,$name), $arguments); - } - - /** - * provide numRows - */ - public function numRows() { - $type = OC_Config::getValue( "dbtype", "sqlite" ); - if ($type == 'oci') { - // OCI doesn't have a queryString, just do a rowCount for now - return $this->statement->rowCount(); - } - $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; - $queryString = $this->statement->getWrappedStatement()->queryString; - if (preg_match($regex, $queryString, $output) > 0) { - $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}"); - return $query->execute($this->lastArguments)->fetchColumn(); - }else{ - return $this->statement->rowCount(); - } - } - - /** - * make execute return the result 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->getWrappedStatement()->queryString; - $pos = stripos ($query, 'SUBSTRING'); - - if ( $pos === false) { - return $input; - } - - 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 an alias for fetch - */ - public function fetchRow() { - return $this->statement->fetch(); - } - - /** - * Provide a simple fetchOne. - * fetch single column from the next row - * @param int $colnum the column number to fetch - * @return string - */ - public function fetchOne($colnum = 0) { - return $this->statement->fetchColumn($colnum); - } -} |