Merge pull request #2221 from owncloud/doctrine

OC6: Implement Doctrine as the backend for OC_DB
This commit is contained in:
Bart Visscher 2013-07-18 14:24:27 -07:00
commit 084cf0c202
15 changed files with 848 additions and 4455 deletions

@ -1 +1 @@
Subproject commit 217626723957161191572ea50172a3943c30696d
Subproject commit 25e8568d41a9b9a6d1662ccf33058822a890e7f5

View File

@ -308,7 +308,7 @@
<name>etag</name>
<type>text</type>
<default></default>
<notnull>true</notnull>
<notnull>false</notnull>
<length>40</length>
</field>

View File

@ -1,385 +0,0 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2011 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once 'MDB2/Driver/Datatype/Common.php';
/**
* MDB2 SQLite driver
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Driver_Datatype_sqlite3 extends MDB2_Driver_Datatype_Common
{
// {{{ _getCollationFieldDeclaration()
/**
* Obtain DBMS specific SQL code portion needed to set the COLLATION
* of a field declaration to be used in statements like CREATE TABLE.
*
* @param string $collation name of the collation
*
* @return string DBMS specific SQL code portion needed to set the COLLATION
* of a field declaration.
*/
function _getCollationFieldDeclaration($collation)
{
return 'COLLATE '.$collation;
}
// }}}
// {{{ getTypeDeclaration()
/**
* Obtain DBMS specific SQL code portion needed to declare an text type
* field to be used in statements like CREATE TABLE.
*
* @param array $field associative array with the name of the properties
* of the field being declared as array indexes. Currently, the types
* of supported field properties are as follows:
*
* length
* Integer value that determines the maximum length of the text
* field. If this argument is missing the field should be
* declared to have the longest length allowed by the DBMS.
*
* default
* Text value to be used as default for this field.
*
* notnull
* Boolean flag that indicates whether this field is constrained
* to not be set to null.
* @return string DBMS specific SQL code portion that should be used to
* declare the specified field.
* @access public
*/
function getTypeDeclaration($field)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
switch ($field['type']) {
case 'text':
$length = !empty($field['length'])
? $field['length'] : false;
$fixed = !empty($field['fixed']) ? $field['fixed'] : false;
return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
: ($length ? 'VARCHAR('.$length.')' : 'TEXT');
case 'clob':
if (!empty($field['length'])) {
$length = $field['length'];
if ($length <= 255) {
return 'TINYTEXT';
} elseif ($length <= 65532) {
return 'TEXT';
} elseif ($length <= 16777215) {
return 'MEDIUMTEXT';
}
}
return 'LONGTEXT';
case 'blob':
if (!empty($field['length'])) {
$length = $field['length'];
if ($length <= 255) {
return 'TINYBLOB';
} elseif ($length <= 65532) {
return 'BLOB';
} elseif ($length <= 16777215) {
return 'MEDIUMBLOB';
}
}
return 'LONGBLOB';
case 'integer':
if (!empty($field['length'])) {
$length = $field['length'];
if ($length <= 2) {
return 'SMALLINT';
} elseif ($length == 3 || $length == 4) {
return 'INTEGER';
} elseif ($length > 4) {
return 'BIGINT';
}
}
return 'INTEGER';
case 'boolean':
return 'BOOLEAN';
case 'date':
return 'DATE';
case 'time':
return 'TIME';
case 'timestamp':
return 'DATETIME';
case 'float':
return 'DOUBLE'.($db->options['fixed_float'] ? '('.
($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : '');
case 'decimal':
$length = !empty($field['length']) ? $field['length'] : 18;
$scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
return 'DECIMAL('.$length.','.$scale.')';
}
return '';
}
// }}}
// {{{ _getIntegerDeclaration()
/**
* Obtain DBMS specific SQL code portion needed to declare an integer type
* field to be used in statements like CREATE TABLE.
*
* @param string $name name the field to be declared.
* @param string $field associative array with the name of the properties
* of the field being declared as array indexes.
* Currently, the types of supported field
* properties are as follows:
*
* unsigned
* Boolean flag that indicates whether the field
* should be declared as unsigned integer if
* possible.
*
* default
* Integer value to be used as default for this
* field.
*
* notnull
* Boolean flag that indicates whether this field is
* constrained to not be set to null.
* @return string DBMS specific SQL code portion that should be used to
* declare the specified field.
* @access protected
*/
function _getIntegerDeclaration($name, $field)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
$default = $autoinc = '';
if (!empty($field['autoincrement'])) {
$autoinc = ' PRIMARY KEY AUTOINCREMENT';
} elseif (array_key_exists('default', $field)) {
if ($field['default'] === '') {
$field['default'] = empty($field['notnull']) ? null : 0;
}
$default = ' DEFAULT '.$this->quote($field['default'], 'integer');
}
$notnull = empty($field['notnull']) ? '' : ' NOT NULL';
$unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
$name = $db->quoteIdentifier($name, true);
if($autoinc) {
return $name.' '.$this->getTypeDeclaration($field).$autoinc;
}else{
return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
}
}
// }}}
// {{{ matchPattern()
/**
* build a pattern matching string
*
* @access public
*
* @param array $pattern even keys are strings, odd are patterns (% and _)
* @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
* @param string $field optional field name that is being matched against
* (might be required when emulating ILIKE)
*
* @return string SQL pattern
*/
function matchPattern($pattern, $operator = null, $field = null)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
$match = '';
if (!is_null($operator)) {
$field = is_null($field) ? '' : $field.' ';
$operator = strtoupper($operator);
switch ($operator) {
// case insensitive
case 'ILIKE':
$match = $field.'LIKE ';
break;
// case sensitive
case 'LIKE':
$match = $field.'LIKE ';
break;
default:
return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'not a supported operator type:'. $operator, __FUNCTION__);
}
}
$match.= "'";
foreach ($pattern as $key => $value) {
if ($key % 2) {
$match.= $value;
} else {
$match.= $db->escapePattern($db->escape($value));
}
}
$match.= "'";
$match.= $this->patternEscapeString();
return $match;
}
// }}}
// {{{ _mapNativeDatatype()
/**
* Maps a native array description of a field to a MDB2 datatype and length
*
* @param array $field native field description
* @return array containing the various possible types, length, sign, fixed
* @access public
*/
function _mapNativeDatatype($field)
{
$db_type = strtolower($field['type']);
$length = !empty($field['length']) ? $field['length'] : null;
$unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null;
$fixed = null;
$type = array();
switch ($db_type) {
case 'boolean':
$type[] = 'boolean';
break;
case 'tinyint':
$type[] = 'integer';
$type[] = 'boolean';
if (preg_match('/^(is|has)/', $field['name'])) {
$type = array_reverse($type);
}
$unsigned = preg_match('/ unsigned/i', $field['type']);
$length = 1;
break;
case 'smallint':
$type[] = 'integer';
$unsigned = preg_match('/ unsigned/i', $field['type']);
$length = 2;
break;
case 'mediumint':
$type[] = 'integer';
$unsigned = preg_match('/ unsigned/i', $field['type']);
$length = 3;
break;
case 'int':
case 'integer':
case 'serial':
$type[] = 'integer';
$unsigned = preg_match('/ unsigned/i', $field['type']);
$length = 4;
break;
case 'bigint':
case 'bigserial':
$type[] = 'integer';
$unsigned = preg_match('/ unsigned/i', $field['type']);
$length = 8;
break;
case 'clob':
$type[] = 'clob';
$fixed = false;
break;
case 'tinytext':
case 'mediumtext':
case 'longtext':
case 'text':
case 'varchar':
case 'varchar2':
$fixed = false;
case 'char':
$type[] = 'text';
if ($length == '1') {
$type[] = 'boolean';
if (preg_match('/^(is|has)/', $field['name'])) {
$type = array_reverse($type);
}
} elseif (strstr($db_type, 'text')) {
$type[] = 'clob';
$type = array_reverse($type);
}
if ($fixed !== false) {
$fixed = true;
}
break;
case 'date':
$type[] = 'date';
$length = null;
break;
case 'datetime':
case 'timestamp':
$type[] = 'timestamp';
$length = null;
break;
case 'time':
$type[] = 'time';
$length = null;
break;
case 'float':
case 'double':
case 'real':
$type[] = 'float';
break;
case 'decimal':
case 'numeric':
$type[] = 'decimal';
$length = $length.','.$field['decimal'];
break;
case 'tinyblob':
case 'mediumblob':
case 'longblob':
case 'blob':
$type[] = 'blob';
$length = null;
break;
case 'year':
$type[] = 'integer';
$type[] = 'date';
$length = null;
break;
default:
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'unknown database attribute type: '.$db_type, __FUNCTION__);
}
if ((int)$length <= 0) {
$length = null;
}
return array($type, $length, $unsigned, $fixed);
}
// }}}
}

View File

@ -1,136 +0,0 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2011 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once 'MDB2/Driver/Function/Common.php';
/**
* MDB2 SQLite driver for the function modules
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Driver_Function_sqlite3 extends MDB2_Driver_Function_Common
{
// {{{ constructor
/**
* Constructor
*/
function __construct($db_index)
{
parent::__construct($db_index);
// create all sorts of UDFs
}
// {{{ now()
/**
* Return string to call a variable with the current timestamp inside an SQL statement
* There are three special variables for current date and time.
*
* @return string to call a variable with the current timestamp
* @access public
*/
function now($type = 'timestamp')
{
switch ($type) {
case 'time':
return 'CURRENT_TIME';
case 'date':
return 'CURRENT_DATE';
case 'timestamp':
default:
return 'CURRENT_TIMESTAMP';
}
}
// }}}
// {{{ unixtimestamp()
/**
* return string to call a function to get the unix timestamp from a iso timestamp
*
* @param string $expression
*
* @return string to call a variable with the timestamp
* @access public
*/
function unixtimestamp($expression)
{
return 'strftime("%s",'. $expression.', "utc")';
}
// }}}
// {{{ substring()
/**
* return string to call a function to get a substring inside an SQL statement
*
* @return string to call a function to get a substring
* @access public
*/
function substring($value, $position = 1, $length = null)
{
if (!is_null($length)) {
return "substr($value, $position, $length)";
}
return "substr($value, $position, length($value))";
}
// }}}
// {{{ random()
/**
* return string to call a function to get random value inside an SQL statement
*
* @return return string to generate float between 0 and 1
* @access public
*/
function random()
{
return '((RANDOM()+2147483648)/4294967296)';
}
// }}}
// {{{ replace()
/**
* return string to call a function to get a replacement inside an SQL statement.
*
* @return string to call a function to get a replace
* @access public
*/
function replace($str, $from_str, $to_str)
{
$db =& $this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
$error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
return $error;
}
// }}}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +0,0 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2011 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once 'MDB2/Driver/Native/Common.php';
/**
* MDB2 SQLite driver for the native module
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common
{
}

View File

@ -1,586 +0,0 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2011 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once 'MDB2/Driver/Reverse/Common.php';
/**
* MDB2 SQlite driver for the schema reverse engineering module
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Driver_Reverse_sqlite3 extends MDB2_Driver_Reverse_Common
{
/**
* Remove SQL comments from the field definition
*
* @access private
*/
function _removeComments($sql) {
$lines = explode("\n", $sql);
foreach ($lines as $k => $line) {
$pieces = explode('--', $line);
if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
$lines[$k] = substr($line, 0, strpos($line, '--'));
}
}
return implode("\n", $lines);
}
/**
*
*/
function _getTableColumns($sql)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
$start_pos = strpos($sql, '(');
$end_pos = strrpos($sql, ')');
$column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
// replace the decimal length-places-separator with a colon
$column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
$column_def = $this->_removeComments($column_def);
$column_sql = explode(',', $column_def);
$columns = array();
$count = count($column_sql);
if ($count == 0) {
return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'unexpected empty table column definition list', __FUNCTION__);
}
$regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( AUTOINCREMENT)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
$regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
for ($i=0, $j=0; $i<$count; ++$i) {
if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
if (!preg_match($regexp2, trim($column_sql[$i]))) {
continue;
}
return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
}
$columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
$columns[$j]['type'] = strtolower($matches[2]);
if (isset($matches[4]) && strlen($matches[4])) {
$columns[$j]['length'] = $matches[4];
}
if (isset($matches[6]) && strlen($matches[6])) {
$columns[$j]['decimal'] = $matches[6];
}
if (isset($matches[8]) && strlen($matches[8])) {
$columns[$j]['unsigned'] = true;
}
if (isset($matches[10]) && strlen($matches[10])) {
$columns[$j]['autoincrement'] = true;
$columns[$j]['notnull']=true;
}
if (isset($matches[10]) && strlen($matches[10])) {
$columns[$j]['autoincrement'] = true;
$columns[$j]['notnull']=true;
}
if (isset($matches[13]) && strlen($matches[13])) {
$default = $matches[13];
if (strlen($default) && $default[0]=="'") {
$default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
}
if ($default === 'NULL') {
$default = null;
}
$columns[$j]['default'] = $default;
}
if (isset($matches[7]) && strlen($matches[7])) {
$columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
} else if (isset($matches[9]) && strlen($matches[9])) {
$columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
} else if (isset($matches[14]) && strlen($matches[14])) {
$columns[$j]['notnull'] = ($matches[14] === ' NOT NULL');
}
++$j;
}
return $columns;
}
// {{{ getTableFieldDefinition()
/**
* Get the stucture of a field into an array
*
* @param string $table_name name of table that should be used in method
* @param string $field_name name of field that should be used in method
* @return mixed data array on success, a MDB2 error on failure.
* The returned array contains an array for each field definition,
* with (some of) these indices:
* [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
* @access public
*/
function getTableFieldDefinition($table_name, $field_name)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
list($schema, $table) = $this->splitTableSchema($table_name);
$result = $db->loadModule('Datatype', null, true);
if (PEAR::isError($result)) {
return $result;
}
$query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
} else {
$query.= 'name='.$db->quote($table, 'text');
}
$sql = $db->queryOne($query);
if (PEAR::isError($sql)) {
return $sql;
}
$columns = $this->_getTableColumns($sql);
foreach ($columns as $column) {
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
if ($db->options['field_case'] == CASE_LOWER) {
$column['name'] = strtolower($column['name']);
} else {
$column['name'] = strtoupper($column['name']);
}
} else {
$column = array_change_key_case($column, $db->options['field_case']);
}
if ($field_name == $column['name']) {
$mapped_datatype = $db->datatype->mapNativeDatatype($column);
if (PEAR::isError($mapped_datatype)) {
return $mapped_datatype;
}
list($types, $length, $unsigned, $fixed) = $mapped_datatype;
$notnull = false;
if (!empty($column['notnull'])) {
$notnull = $column['notnull'];
}
$default = false;
if (array_key_exists('default', $column)) {
$default = $column['default'];
if (is_null($default) && $notnull) {
$default = '';
}
}
$autoincrement = false;
if (!empty($column['autoincrement'])) {
$autoincrement = true;
}
$definition[0] = array(
'notnull' => $notnull,
'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
);
if (!is_null($length)) {
$definition[0]['length'] = $length;
}
if (!is_null($unsigned)) {
$definition[0]['unsigned'] = $unsigned;
}
if (!is_null($fixed)) {
$definition[0]['fixed'] = $fixed;
}
if ($default !== false) {
$definition[0]['default'] = $default;
}
if ($autoincrement !== false) {
$definition[0]['autoincrement'] = $autoincrement;
}
foreach ($types as $key => $type) {
$definition[$key] = $definition[0];
if ($type == 'clob' || $type == 'blob') {
unset($definition[$key]['default']);
}
$definition[$key]['type'] = $type;
$definition[$key]['mdb2type'] = $type;
}
return $definition;
}
}
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'it was not specified an existing table column', __FUNCTION__);
}
// }}}
// {{{ getTableIndexDefinition()
/**
* Get the stucture of an index into an array
*
* @param string $table_name name of table that should be used in method
* @param string $index_name name of index that should be used in method
* @return mixed data array on success, a MDB2 error on failure
* @access public
*/
function getTableIndexDefinition($table_name, $index_name)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
list($schema, $table) = $this->splitTableSchema($table_name);
$query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
} else {
$query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
}
$query.= ' AND sql NOT NULL ORDER BY name';
$index_name_mdb2 = $db->getIndexName($index_name);
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
} else {
$qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
}
$sql = $db->queryOne($qry, 'text');
if (PEAR::isError($sql) || empty($sql)) {
// fallback to the given $index_name, without transformation
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
} else {
$qry = sprintf($query, $db->quote($index_name, 'text'));
}
$sql = $db->queryOne($qry, 'text');
}
if (PEAR::isError($sql)) {
return $sql;
}
if (!$sql) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'it was not specified an existing table index', __FUNCTION__);
}
$sql = strtolower($sql);
$start_pos = strpos($sql, '(');
$end_pos = strrpos($sql, ')');
$column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
$column_names = explode(',', $column_names);
if (preg_match("/^create unique/", $sql)) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'it was not specified an existing table index', __FUNCTION__);
}
$definition = array();
$count = count($column_names);
for ($i=0; $i<$count; ++$i) {
$column_name = strtok($column_names[$i], ' ');
$collation = strtok(' ');
$definition['fields'][$column_name] = array(
'position' => $i+1
);
if (!empty($collation)) {
$definition['fields'][$column_name]['sorting'] =
($collation=='ASC' ? 'ascending' : 'descending');
}
}
if (empty($definition['fields'])) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'it was not specified an existing table index', __FUNCTION__);
}
return $definition;
}
// }}}
// {{{ getTableConstraintDefinition()
/**
* Get the stucture of a constraint into an array
*
* @param string $table_name name of table that should be used in method
* @param string $constraint_name name of constraint that should be used in method
* @return mixed data array on success, a MDB2 error on failure
* @access public
*/
function getTableConstraintDefinition($table_name, $constraint_name)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
list($schema, $table) = $this->splitTableSchema($table_name);
$query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
} else {
$query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
}
$query.= ' AND sql NOT NULL ORDER BY name';
$constraint_name_mdb2 = $db->getIndexName($constraint_name);
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
} else {
$qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
}
$sql = $db->queryOne($qry, 'text');
if (PEAR::isError($sql) || empty($sql)) {
// fallback to the given $index_name, without transformation
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
} else {
$qry = sprintf($query, $db->quote($constraint_name, 'text'));
}
$sql = $db->queryOne($qry, 'text');
}
if (PEAR::isError($sql)) {
return $sql;
}
//default values, eventually overridden
$definition = array(
'primary' => false,
'unique' => false,
'foreign' => false,
'check' => false,
'fields' => array(),
'references' => array(
'table' => '',
'fields' => array(),
),
'onupdate' => '',
'ondelete' => '',
'match' => '',
'deferrable' => false,
'initiallydeferred' => false,
);
if (!$sql) {
$query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
} else {
$query.= 'name='.$db->quote($table, 'text');
}
$query.= " AND sql NOT NULL ORDER BY name";
$sql = $db->queryOne($query, 'text');
if (PEAR::isError($sql)) {
return $sql;
}
if ($constraint_name == 'primary') {
// search in table definition for PRIMARY KEYs
if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
$definition['primary'] = true;
$definition['fields'] = array();
$column_names = explode(',', $tmp[1]);
$colpos = 1;
foreach ($column_names as $column_name) {
$definition['fields'][trim($column_name)] = array(
'position' => $colpos++
);
}
return $definition;
}
if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
$definition['primary'] = true;
$definition['fields'] = array();
$column_names = explode(',', $tmp[1]);
$colpos = 1;
foreach ($column_names as $column_name) {
$definition['fields'][trim($column_name)] = array(
'position' => $colpos++
);
}
return $definition;
}
} else {
// search in table definition for FOREIGN KEYs
$pattern = "/\bCONSTRAINT\b\s+%s\s+
\bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
\bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
(?:\bMATCH\s*([^\s]+))?\s*
(?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
(?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
/imsx";
$found_fk = false;
if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
$found_fk = true;
} elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
$found_fk = true;
}
if ($found_fk) {
$definition['foreign'] = true;
$definition['match'] = 'SIMPLE';
$definition['onupdate'] = 'NO ACTION';
$definition['ondelete'] = 'NO ACTION';
$definition['references']['table'] = $tmp[2];
$column_names = explode(',', $tmp[1]);
$colpos = 1;
foreach ($column_names as $column_name) {
$definition['fields'][trim($column_name)] = array(
'position' => $colpos++
);
}
$referenced_cols = explode(',', $tmp[3]);
$colpos = 1;
foreach ($referenced_cols as $column_name) {
$definition['references']['fields'][trim($column_name)] = array(
'position' => $colpos++
);
}
if (isset($tmp[4])) {
$definition['match'] = $tmp[4];
}
if (isset($tmp[5])) {
$definition['onupdate'] = $tmp[5];
}
if (isset($tmp[6])) {
$definition['ondelete'] = $tmp[6];
}
return $definition;
}
}
$sql = false;
}
if (!$sql) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
$constraint_name . ' is not an existing table constraint', __FUNCTION__);
}
$sql = strtolower($sql);
$start_pos = strpos($sql, '(');
$end_pos = strrpos($sql, ')');
$column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
$column_names = explode(',', $column_names);
if (!preg_match("/^create unique/", $sql)) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
$constraint_name . ' is not an existing table constraint', __FUNCTION__);
}
$definition['unique'] = true;
$count = count($column_names);
for ($i=0; $i<$count; ++$i) {
$column_name = strtok($column_names[$i], " ");
$collation = strtok(" ");
$definition['fields'][$column_name] = array(
'position' => $i+1
);
if (!empty($collation)) {
$definition['fields'][$column_name]['sorting'] =
($collation=='ASC' ? 'ascending' : 'descending');
}
}
if (empty($definition['fields'])) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
$constraint_name . ' is not an existing table constraint', __FUNCTION__);
}
return $definition;
}
// }}}
// {{{ getTriggerDefinition()
/**
* Get the structure of a trigger into an array
*
* EXPERIMENTAL
*
* WARNING: this function is experimental and may change the returned value
* at any time until labelled as non-experimental
*
* @param string $trigger name of trigger that should be used in method
* @return mixed data array on success, a MDB2 error on failure
* @access public
*/
function getTriggerDefinition($trigger)
{
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
$query = "SELECT name as trigger_name,
tbl_name AS table_name,
sql AS trigger_body,
NULL AS trigger_type,
NULL AS trigger_event,
NULL AS trigger_comment,
1 AS trigger_enabled
FROM sqlite_master
WHERE type='trigger'";
if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
$query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
} else {
$query.= ' AND name='.$db->quote($trigger, 'text');
}
$types = array(
'trigger_name' => 'text',
'table_name' => 'text',
'trigger_body' => 'text',
'trigger_type' => 'text',
'trigger_event' => 'text',
'trigger_comment' => 'text',
'trigger_enabled' => 'boolean',
);
$def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
if (PEAR::isError($def)) {
return $def;
}
if (empty($def)) {
return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'it was not specified an existing trigger', __FUNCTION__);
}
if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
$def['trigger_type'] = strtoupper($tmp[1]);
$def['trigger_event'] = strtoupper($tmp[2]);
}
return $def;
}
// }}}
// {{{ tableInfo()
/**
* Returns information about a table
*
* @param string $result a string containing the name of a table
* @param int $mode a valid tableInfo mode
*
* @return array an associative array with the information requested.
* A MDB2_Error object on failure.
*
* @see MDB2_Driver_Common::tableInfo()
* @since Method available since Release 1.7.0
*/
function tableInfo($result, $mode = null)
{
if (is_string($result)) {
return parent::tableInfo($result, $mode);
}
$db =$this->getDBInstance();
if (PEAR::isError($db)) {
return $db;
}
return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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
* @var \Doctrine\DBAL\Connection
*/
static private $MDB2=null;
/**
* @var PDO
*/
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'];
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;
}
// 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);
}
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);
}
}

241
lib/db/mdb2schemareader.php Normal file
View File

@ -0,0 +1,241 @@
<?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_MDB2SchemaReader {
static protected $DBNAME;
static protected $DBTABLEPREFIX;
static protected $platform;
/**
* @param $file
* @param $platform
* @return \Doctrine\DBAL\Schema\Schema
* @throws DomainException
*/
public static function loadSchemaFromFile($file, $platform) {
self::$DBNAME = OC_Config::getValue( "dbname", "owncloud" );
self::$DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
self::$platform = $platform;
$schema = new \Doctrine\DBAL\Schema\Schema();
$xml = simplexml_load_file($file);
foreach($xml->children() as $child) {
switch($child->getName()) {
case 'name':
case 'create':
case 'overwrite':
case 'charset':
break;
case 'table':
self::loadTable($schema, $child);
break;
default:
throw new DomainException('Unknown element: '.$child->getName());
}
}
return $schema;
}
/**
* @param\Doctrine\DBAL\Schema\Schema $schema
* @param $xml
* @throws DomainException
*/
private static function loadTable($schema, $xml) {
foreach($xml->children() as $child) {
switch($child->getName()) {
case 'name':
$name = (string)$child;
$name = str_replace( '*dbprefix*', self::$DBTABLEPREFIX, $name );
$name = self::$platform->quoteIdentifier($name);
$table = $schema->createTable($name);
break;
case 'create':
case 'overwrite':
case 'charset':
break;
case 'declaration':
self::loadDeclaration($table, $child);
break;
default:
throw new DomainException('Unknown element: '.$child->getName());
}
}
}
/**
* @param \Doctrine\DBAL\Schema\Table $table
* @param $xml
* @throws DomainException
*/
private static function loadDeclaration($table, $xml) {
foreach($xml->children() as $child) {
switch($child->getName()) {
case 'field':
self::loadField($table, $child);
break;
case 'index':
self::loadIndex($table, $child);
break;
default:
throw new DomainException('Unknown element: '.$child->getName());
}
}
}
private static function loadField($table, $xml) {
$options = array();
foreach($xml->children() as $child) {
switch($child->getName()) {
case 'name':
$name = (string)$child;
$name = self::$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;
// TODO
return;
}
break;
case 'length':
$length = (string)$child;
$options['length'] = $length;
break;
case 'unsigned':
$unsigned = self::asBool($child);
$options['unsigned'] = $unsigned;
break;
case 'notnull':
$notnull = self::asBool($child);
$options['notnull'] = $notnull;
break;
case 'autoincrement':
$autoincrement = self::asBool($child);
$options['autoincrement'] = $autoincrement;
break;
case 'default':
$default = (string)$child;
$options['default'] = $default;
break;
case 'comments':
$comment = (string)$child;
$options['comment'] = $comment;
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;
}
if (!empty($options['autoincrement']) && $options['autoincrement']) {
unset($options['default']);
}
}
if ($type == 'integer' && isset($options['length'])) {
$length = $options['length'];
if ($length < 4) {
$type = 'smallint';
}
else if ($length > 4) {
$type = 'bigint';
}
}
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));
}
}
}
private static function loadIndex($table, $xml) {
$name = null;
$fields = array();
foreach($xml->children() as $child) {
switch($child->getName()) {
case 'name':
$name = (string)$child;
break;
case 'primary':
$primary = self::asBool($child);
break;
case 'unique':
$unique = self::asBool($child);
break;
case 'field':
foreach($child->children() as $field) {
switch($field->getName()) {
case 'name':
$field_name = (string)$field;
$field_name = self::$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));
}
}
private static function asBool($xml) {
$result = (string)$xml;
if ($result == 'true') {
$result = true;
} else
if ($result == 'false') {
$result = false;
}
return (bool)$result;
}
}

133
lib/db/mdb2schemawriter.php Normal file
View File

@ -0,0 +1,133 @@
<?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';
}
}

136
lib/db/schema.php Normal file
View File

@ -0,0 +1,136 @@
<?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_Schema {
/**
* @brief saves database scheme to xml file
* @param \Doctrine\DBAL\Connection $conn
* @param string $file name of file
* @param int|string $mode
* @return bool
*
* TODO: write more documentation
*/
public static function getDbStructure( $conn, $file, $mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
$sm = $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 static function createDbFromStructure( $conn, $file ) {
$toSchema = OC_DB_MDB2SchemaReader::loadSchemaFromFile($file, $conn->getDatabasePlatform());
return self::executeSchemaChange($conn, $toSchema);
}
/**
* @brief update the database scheme
* @param string $file file to read structure from
* @return bool
*/
public static function updateDbFromStructure($conn, $file) {
$sm = $conn->getSchemaManager();
$fromSchema = $sm->createSchema();
$toSchema = OC_DB_MDB2SchemaReader::loadSchemaFromFile($file, $conn->getDatabasePlatform());
// 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 = $conn->getDatabasePlatform();
$tables = $schemaDiff->newTables + $schemaDiff->changedTables + $schemaDiff->removedTables;
foreach($tables as $tableDiff) {
$tableDiff->name = $platform->quoteIdentifier($tableDiff->name);
}
//$from = $fromSchema->toSql($conn->getDatabasePlatform());
//$to = $toSchema->toSql($conn->getDatabasePlatform());
//echo($from[9]);
//echo '<br>';
//echo($to[9]);
//var_dump($from, $to);
return self::executeSchemaChange($conn, $schemaDiff);
}
/**
* @brief drop a table
* @param string $tableName the table to drop
*/
public static function dropTable($conn, $tableName) {
$sm = $conn->getSchemaManager();
$fromSchema = $sm->createSchema();
$toSchema = clone $fromSchema;
$toSchema->dropTable($tableName);
$sql = $fromSchema->getMigrateToSql($toSchema, $conn->getDatabasePlatform());
$conn->execute($sql);
}
/**
* remove all tables defined in a database structure xml file
* @param string $file the xml file describing the tables
*/
public static function removeDBStructure($conn, $file) {
$fromSchema = OC_DB_MDB2SchemaReader::loadSchemaFromFile($file, $conn->getDatabasePlatform());
$toSchema = clone $fromSchema;
foreach($toSchema->getTables() as $table) {
$toSchema->dropTable($table->getName());
}
$comparator = new \Doctrine\DBAL\Schema\Comparator();
$schemaDiff = $comparator->compare($fromSchema, $toSchema);
self::executeSchemaChange($conn, $schemaDiff);
}
/**
* @brief replaces the ownCloud tables with a new set
* @param $file string path to the MDB2 xml db export file
*/
public static function replaceDB( $conn, $file ) {
$apps = OC_App::getAllApps();
self::beginTransaction();
// Delete the old tables
self::removeDBStructure( $conn, OC::$SERVERROOT . '/db_structure.xml' );
foreach($apps as $app) {
$path = OC_App::getAppPath($app).'/appinfo/database.xml';
if(file_exists($path)) {
self::removeDBStructure( $conn, $path );
}
}
// Create new tables
self::commit();
}
private static function executeSchemaChange($conn, $schema) {
$conn->beginTransaction();
foreach($schema->toSql($conn->getDatabasePlatform()) as $sql) {
$conn->query($sql);
}
$conn->commit();
}
}

191
lib/db/statementwrapper.php Normal file
View File

@ -0,0 +1,191 @@
<?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);
}
}

View File

@ -37,7 +37,7 @@ class Test_DB extends PHPUnit_Framework_TestCase {
$result = $query->execute(array('uri_1'));
$this->assertTrue((bool)$result);
$row = $result->fetchRow();
$this->assertFalse((bool)$row); //PDO returns false, MDB2 returns null
$this->assertFalse($row);
$query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)');
$result = $query->execute(array('fullname test', 'uri_1'));
$this->assertEquals(1, $result);
@ -94,7 +94,7 @@ class Test_DB extends PHPUnit_Framework_TestCase {
$query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table3.'`');
$result = $query->execute();
$this->assertTrue((bool)$result);
$this->assertEquals(4, $result->numRows());
$this->assertEquals(4, count($result->fetchAll()));
}
public function testinsertIfNotExistDontOverwrite() {

View File

@ -20,10 +20,19 @@ class View extends \PHPUnit_Framework_TestCase {
private $storages = array();
public function setUp() {
\OC_User::clearBackends();
\OC_User::useBackend(new \OC_User_Dummy());
//login
\OC_User::createUser('test', 'test');
$this->user=\OC_User::getUser();
\OC_User::setUserId('test');
\OC\Files\Filesystem::clearMounts();
}
public function tearDown() {
\OC_User::setUserId($this->user);
foreach ($this->storages as $storage) {
$cache = $storage->getCache();
$ids = $cache->getAll();