Merge "jquery.byteLimit: Partial rewrite to fix logic errors"
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
index b298545..8ce6e70 100644 (file)
@@ -2,6 +2,21 @@
 /**
  * This is the Oracle database abstraction layer.
  *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
  * @file
  * @ingroup Database
  */
@@ -16,7 +31,7 @@ class ORAResult {
        private $rows;
        private $cursor;
        private $nrows;
-       
+
        private $columns = array();
 
        private function array_unique_md( $array_in ) {
@@ -226,6 +241,7 @@ class DatabaseOracle extends DatabaseBase {
 
        /**
         * Usually aborts on failure
+        * @return DatabaseBase|null
         */
        function open( $server, $user, $password, $dbName ) {
                if ( !function_exists( 'oci_connect' ) ) {
@@ -246,7 +262,7 @@ class DatabaseOracle extends DatabaseBase {
                        $this->mServer = $server;
                        if ( !$dbName ) {
                                $this->mDBname = $user;
-                       } else {        
+                       } else {
                                $this->mDBname = $dbName;
                        }
                }
@@ -285,24 +301,17 @@ class DatabaseOracle extends DatabaseBase {
        /**
         * Closes a database connection, if it is open
         * Returns success, true if already closed
+        * @return bool
         */
-       function close() {
-               $this->mOpened = false;
-               if ( $this->mConn ) {
-                       if ( $this->mTrxLevel ) {
-                               $this->commit();
-                       }
-                       return oci_close( $this->mConn );
-               } else {
-                       return true;
-               }
+       protected function closeConnection() {
+               return oci_close( $this->mConn );
        }
 
        function execFlags() {
                return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
        }
 
-       function doQuery( $sql ) {
+       protected function doQuery( $sql ) {
                wfDebug( "SQL: [$sql]\n" );
                if ( !mb_check_encoding( $sql ) ) {
                        throw new MWException( "SQL encoding is invalid\n$sql" );
@@ -359,7 +368,7 @@ class DatabaseOracle extends DatabaseBase {
                if ( $res instanceof ResultWrapper ) {
                        $res = $res->result;
                }
-               
+
                $res->free();
        }
 
@@ -367,7 +376,7 @@ class DatabaseOracle extends DatabaseBase {
                if ( $res instanceof ResultWrapper ) {
                        $res = $res->result;
                }
-               
+
                return $res->fetchObject();
        }
 
@@ -401,6 +410,7 @@ class DatabaseOracle extends DatabaseBase {
 
        /**
         * This must be called after nextSequenceVal
+        * @return null
         */
        function insertId() {
                return $this->mInsertId;
@@ -439,6 +449,7 @@ class DatabaseOracle extends DatabaseBase {
        /**
         * Returns information about an index
         * If errors are explicitly ignored, returns NULL on failure
+        * @return bool
         */
        function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
                return false;
@@ -485,15 +496,19 @@ class DatabaseOracle extends DatabaseBase {
                if ( is_numeric( $col ) ) {
                        $bind = $val;
                        $val = null;
-                       return $bind; 
-               } else if ( $includeCol ) {
+                       return $bind;
+               } elseif ( $includeCol ) {
                        $bind = "$col = ";
                }
-               
+
                if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
                        $val = null;
                }
 
+               if ( $val === 'NULL' ) {
+                       $val = null;
+               }
+
                if ( $val === null ) {
                        if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
                                $bind .= 'DEFAULT';
@@ -503,7 +518,7 @@ class DatabaseOracle extends DatabaseBase {
                } else {
                        $bind .= ':' . $col;
                }
-               
+
                return $bind;
        }
 
@@ -523,7 +538,7 @@ class DatabaseOracle extends DatabaseBase {
                        } else {
                                $first = false;
                        }
-                       
+
                        $sql .= $this->fieldBindStatement( $table, $col, $val );
                }
                $sql .= ')';
@@ -544,8 +559,9 @@ class DatabaseOracle extends DatabaseBase {
                                        $val = $val->fetch();
                                }
 
+                               // backward compatibility
                                if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
-                                       $val = '31-12-2030 12:00:00.000000';
+                                       $val = $this->getInfinity();
                                }
 
                                $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
@@ -650,7 +666,7 @@ class DatabaseOracle extends DatabaseBase {
                return $retval;
        }
 
-       function tableName( $name, $quoted = true ) {
+       function tableName( $name, $format = 'quoted' ) {
                /*
                Replace reserved words with better ones
                Using uppercase because that's the only way Oracle can handle
@@ -665,7 +681,7 @@ class DatabaseOracle extends DatabaseBase {
                                break;
                }
 
-               return parent::tableName( strtoupper( $name ), $quoted );
+               return parent::tableName( strtoupper( $name ), $format );
        }
 
        function tableNameInternal( $name ) {
@@ -674,6 +690,7 @@ class DatabaseOracle extends DatabaseBase {
        }
        /**
         * Return the next in a sequence, save the value for retrieval via insertId()
+        * @return null
         */
        function nextSequenceValue( $seqName ) {
                $res = $this->query( "SELECT $seqName.nextval FROM dual" );
@@ -684,6 +701,7 @@ class DatabaseOracle extends DatabaseBase {
 
        /**
         * Return sequence_name if table has a sequence
+        * @return bool
         */
        private function getSequenceData( $table ) {
                if ( $this->sequenceData == null ) {
@@ -693,11 +711,11 @@ class DatabaseOracle extends DatabaseBase {
                          FROM all_sequences asq, all_tab_columns atc
                         WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
                                   atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
-                          AND asq.sequence_owner = '{$this->mDBname}'
-                          AND atc.owner = '{$this->mDBname}'" );
+                          AND asq.sequence_owner = upper('{$this->mDBname}')
+                          AND atc.owner = upper('{$this->mDBname}')" );
 
                        while ( ( $row = $result->fetchRow() ) !== false ) {
-                               $this->sequenceData[$this->tableName( $row[1] )] = array(
+                               $this->sequenceData[$row[1]] = array(
                                        'sequence' => $row[0],
                                        'column' => $row[2]
                                );
@@ -707,83 +725,6 @@ class DatabaseOracle extends DatabaseBase {
                return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
        }
 
-       /**
-        * REPLACE query wrapper
-        * Oracle simulates this with a DELETE followed by INSERT
-        * $row is the row to insert, an associative array
-        * $uniqueIndexes is an array of indexes. Each element may be either a
-        * field name or an array of field names
-        *
-        * It may be more efficient to leave off unique indexes which are unlikely to collide.
-        * However if you do this, you run the risk of encountering errors which wouldn't have
-        * occurred in MySQL.
-        *
-        * @param $table String: table name
-        * @param $uniqueIndexes Array: array of indexes. Each element may be
-        *                       either a field name or an array of field names
-        * @param $rows Array: rows to insert to $table
-        * @param $fname String: function name, you can use __METHOD__ here
-        */
-       function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
-               $table = $this->tableName( $table );
-
-               if ( count( $rows ) == 0 ) {
-                       return;
-               }
-
-               # Single row case
-               if ( !is_array( reset( $rows ) ) ) {
-                       $rows = array( $rows );
-               }
-
-               $sequenceData = $this->getSequenceData( $table );
-
-               foreach ( $rows as $row ) {
-                       # Delete rows which collide
-                       if ( $uniqueIndexes ) {
-                               $deleteConds = array();
-                               foreach ( $uniqueIndexes as $key=>$index ) {
-                                       if ( is_array( $index ) ) {
-                                               $deleteConds2 = array();
-                                               foreach ( $index as $col ) {
-                                                       $deleteConds2[$col] = $row[$col];
-                                               }
-                                               $deleteConds[$key] = $this->makeList( $deleteConds2, LIST_AND );
-                                       } else {
-                                               $deleteConds[$index] = $row[$index];
-                                       }
-                               }
-                               $deleteConds = array( $this->makeList( $deleteConds, LIST_OR ) );
-                               $this->delete( $table, $deleteConds, $fname );
-                       }
-
-                       
-                       if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
-                               $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
-                       }
-
-                       # Now insert the row
-                       $this->insert( $table, $row, $fname );
-               }
-       }
-
-       # DELETE where the condition is a join
-       function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
-               if ( !$conds ) {
-                       throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
-               }
-
-               $delTable = $this->tableName( $delTable );
-               $joinTable = $this->tableName( $joinTable );
-               $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
-               if ( $conds != '*' ) {
-                       $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
-               }
-               $sql .= ')';
-
-               $this->query( $sql, $fname );
-       }
-
        # Returns the size of a text field, or -1 for "unlimited"
        function textFieldSize( $table, $field ) {
                $fieldInfoData = $this->fieldInfo( $table, $field );
@@ -835,15 +776,15 @@ class DatabaseOracle extends DatabaseBase {
                if (!empty($prefix)) {
                        $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
                }
-               
+
                $owner = strtoupper( $this->mDBname );
                $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
 
                // dirty code ... i know
                $endArray = array();
-               $endArray[] = $prefix.'MWUSER';
-               $endArray[] = $prefix.'PAGE';
-               $endArray[] = $prefix.'IMAGE';
+               $endArray[] = strtoupper($prefix.'MWUSER');
+               $endArray[] = strtoupper($prefix.'PAGE');
+               $endArray[] = strtoupper($prefix.'IMAGE');
                $fixedOrderTabs = $endArray;
                while (($row = $result->fetchRow()) !== false) {
                        if (!in_array($row['table_name'], $fixedOrderTabs))
@@ -858,7 +799,7 @@ class DatabaseOracle extends DatabaseBase {
                if( !$this->tableExists( $tableName ) ) {
                        return false;
                }
-               
+
                return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
        }
 
@@ -902,12 +843,13 @@ class DatabaseOracle extends DatabaseBase {
                $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
                if ( !( $row =  $rset->fetchRow() ) ) {
                        return oci_server_version( $this->mConn );
-               } 
+               }
                return $row['version'];
        }
 
        /**
         * Query whether a given index exists
+        * @return bool
         */
        function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
                $table = $this->tableName( $table );
@@ -927,12 +869,13 @@ class DatabaseOracle extends DatabaseBase {
 
        /**
         * Query whether a given table exists (in the given schema, or the default mw one if not given)
+        * @return int
         */
-       function tableExists( $table ) {
+       function tableExists( $table, $fname = __METHOD__ ) {
                $table = $this->tableName( $table );
-               $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
-               $owner = strtoupper( $this->mDBname );
-               $SQL = "SELECT 1 FROM all_tables WHERE owner='$owner' AND table_name='$table'";
+               $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
+               $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
+               $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
                $res = $this->doQuery( $SQL );
                if ( $res ) {
                        $count = $res->numRows();
@@ -1042,7 +985,8 @@ class DatabaseOracle extends DatabaseBase {
        }
 
        /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
-       function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
+       function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
+               $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
                $cmd = '';
                $done = false;
                $dollarquote = false;
@@ -1096,6 +1040,9 @@ class DatabaseOracle extends DatabaseBase {
                                        }
 
                                        $cmd = $this->replaceVars( $cmd );
+                                       if ( $inputCallback ) {
+                                               call_user_func( $inputCallback, $cmd );
+                                       }
                                        $res = $this->doQuery( $cmd );
                                        if ( $resultCallback ) {
                                                call_user_func( $resultCallback, $res, $this );
@@ -1163,7 +1110,7 @@ class DatabaseOracle extends DatabaseBase {
 
        private function wrapFieldForWhere( $table, &$col, &$val ) {
                global $wgContLang;
-               
+
                $col_info = $this->fieldInfoMulti( $table, $col );
                $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
                if ( $col_type == 'CLOB' ) {
@@ -1245,20 +1192,36 @@ class DatabaseOracle extends DatabaseBase {
                if ( is_array($conds) ) {
                        $conds = $this->wrapConditionsForWhere( $table, $conds );
                }
+               // a hack for deleting pages, users and images (which have non-nullable FKs)
+               // all deletions on these tables have transactions so final failure rollbacks these updates
+               $table = $this->tableName( $table );
+               if ( $table == $this->tableName( 'user' )  ) {
+                               $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
+                               $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
+               } elseif ( $table == $this->tableName( 'image' )  ) {
+                               $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
+               }
                return parent::delete( $table, $conds, $fname );
        }
 
        function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
                global $wgContLang;
-               
+
                $table = $this->tableName( $table );
                $opts = $this->makeUpdateOptions( $options );
                $sql = "UPDATE $opts $table SET ";
-               
+
                $first = true;
                foreach ( $values as $col => &$val ) {
                        $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
-                       
+
                        if ( !$first ) {
                                $sqlSet = ', ' . $sqlSet;
                        } else {
@@ -1267,7 +1230,7 @@ class DatabaseOracle extends DatabaseBase {
                        $sql .= $sqlSet;
                }
 
-               if ( $conds != '*' ) {
+               if ( $conds !== array() && $conds !== '*' ) {
                        $conds = $this->wrapConditionsForWhere( $table, $conds );
                        $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
                }
@@ -1304,8 +1267,8 @@ class DatabaseOracle extends DatabaseBase {
                                        throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
                                }
 
-                               if ( $col_type == 'BLOB' ) { 
-                                       $lob[$col]->writeTemporary( $val ); 
+                               if ( $col_type == 'BLOB' ) {
+                                       $lob[$col]->writeTemporary( $val );
                                        oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
                                } else {
                                        $lob[$col]->writeTemporary( $val );
@@ -1356,7 +1319,8 @@ class DatabaseOracle extends DatabaseBase {
                return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
        }
 
-       function setFakeMaster( $enabled = true ) { }
+       function setFakeMaster( $enabled = true ) {
+       }
 
        function getDBname() {
                return $this->mDBname;
@@ -1369,4 +1333,9 @@ class DatabaseOracle extends DatabaseBase {
        public function getSearchEngine() {
                return 'SearchOracle';
        }
+
+       public function getInfinity() {
+               return '31-12-2030 12:00:00.000000';
+       }
+
 } // end DatabaseOracle class