minor typo in comment
[lhc/web/wiklou.git] / includes / db / DatabaseIbm_db2.php
index eea29b2..a2a2be0 100644 (file)
@@ -2,7 +2,7 @@
 /**
  * This is the IBM DB2 database abstraction layer.
  * See maintenance/ibm_db2/README for development notes
- *  and other specific information
+ * and other specific information
  *
  * @file
  * @ingroup Database
@@ -13,7 +13,7 @@
  * This represents a column in a DB2 database
  * @ingroup Database
  */
-class IBM_DB2Field {
+class IBM_DB2Field implements Field {
        private $name = '';
        private $tablename = '';
        private $type = '';
@@ -37,13 +37,17 @@ nulls AS attnotnull, length AS attlen
 FROM sysibm.syscolumns
 WHERE tbcreator=%s AND tbname=%s AND name=%s;
 SQL;
-               $res = $db->query( sprintf( $q,
+               $res = $db->query(
+                       sprintf( $q,
                                $db->addQuotes( $wgDBmwschema ),
                                $db->addQuotes( $table ),
-                               $db->addQuotes( $field )) );
+                               $db->addQuotes( $field )
+                       )
+               );
                $row = $db->fetchObject( $res );
-               if ( !$row )
+               if ( !$row ) {
                        return null;
+               }
                $n = new IBM_DB2Field;
                $n->type = $row->typname;
                $n->nullable = ( $row->attnotnull == 'N' );
@@ -71,7 +75,7 @@ SQL;
         * Can column be null?
         * @return bool true or false
         */
-       function nullable() { return $this->nullable; }
+       function isNullable() { return $this->nullable; }
        /**
         * How much can you fit in the column per row?
         * @return int length
@@ -94,10 +98,9 @@ class IBM_DB2Blob {
                return $this->mData;
        }
 
-       public function __toString()
-    {
-        return $this->mData;
-    }
+       public function __toString() {
+               return $this->mData;
+       }
 }
 
 /**
@@ -111,9 +114,8 @@ class DatabaseIbm_db2 extends DatabaseBase {
        protected $mPHPError = false;
 
        protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
-       protected $mOut, $mOpened = false;
+       protected $mOpened = false;
 
-       protected $mFailFunction;
        protected $mTablePrefix;
        protected $mFlags;
        protected $mTrxLevel = 0;
@@ -142,7 +144,7 @@ class DatabaseIbm_db2 extends DatabaseBase {
        public $mStmtOptions = array();
 
        /** Default schema */
-       const USE_GLOBAL = "mediawiki";
+       const USE_GLOBAL = 'mediawiki';
 
        /** Option that applies to nothing */
        const NONE_OPTION = 0x00;
@@ -254,29 +256,19 @@ class DatabaseIbm_db2 extends DatabaseBase {
         * @param $user String: username
         * @param $password String: password
         * @param $dbName String: database name on the server
-        * @param $failFunction Callback (optional)
         * @param $flags Integer: database behaviour flags (optional, unused)
         * @param $schema String
         */
-       public function DatabaseIbm_db2( $server = false, $user = false,
+       public function __construct( $server = false, $user = false,
                                                        $password = false,
-                                                       $dbName = false, $failFunction = false, $flags = 0,
+                                                       $dbName = false, $flags = 0,
                                                        $schema = self::USE_GLOBAL )
        {
-
-               global $wgOut, $wgDBmwschema;
-               # Can't get a reference if it hasn't been set yet
-               if ( !isset( $wgOut ) ) {
-                       $wgOut = null;
-               }
-               $this->mOut =& $wgOut;
-               $this->mFailFunction = $failFunction;
-               $this->mFlags = DBO_TRX | $flags;
+               global $wgDBmwschema;
 
                if ( $schema == self::USE_GLOBAL ) {
                        $this->mSchema = $wgDBmwschema;
-               }
-               else {
+               } else {
                        $this->mSchema = $schema;
                }
 
@@ -288,7 +280,7 @@ class DatabaseIbm_db2 extends DatabaseBase {
                $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
                        self::STMT_OPTION );
 
-               $this->open( $server, $user, $password, $dbName );
+               parent::__construct( $server, $user, $password, $dbName, $flags );
        }
 
        /**
@@ -298,15 +290,14 @@ class DatabaseIbm_db2 extends DatabaseBase {
         * @param $type Integer: whether this is a Connection or Statement otion
         */
        private function setDB2Option( $name, $const, $type ) {
-               if ( defined( $const )) {
+               if ( defined( $const ) ) {
                        if ( $type & self::CONN_OPTION ) {
                                $this->mConnOptions[$name] = constant( $const );
                        }
                        if ( $type & self::STMT_OPTION ) {
                                $this->mStmtOptions[$name] = constant( $const );
                        }
-               }
-               else {
+               } else {
                        $this->installPrint(
                                "$const is not defined. ibm_db2 version is likely too low." );
                }
@@ -327,14 +318,14 @@ class DatabaseIbm_db2 extends DatabaseBase {
        /**
         * Opens a database connection and returns it
         * Closes any existing connection
-        * @return a fresh connection
+        *
         * @param $server String: hostname
         * @param $user String
         * @param $password String
         * @param $dbName String: database name
+        * @return a fresh connection
         */
-       public function open( $server, $user, $password, $dbName )
-       {
+       public function open( $server, $user, $password, $dbName ) {
                // Load the port number
                global $wgDBport;
                wfProfileIn( __METHOD__ );
@@ -352,7 +343,7 @@ ERROR;
                        $this->reportConnectionError( $error );
                }
 
-               if ( strlen( $user ) < 1) {
+               if ( strlen( $user ) < 1 ) {
                        return null;
                }
 
@@ -393,8 +384,7 @@ ERROR;
        /**
         * Opens a cataloged database connection, sets mConn
         */
-       protected function openCataloged( $dbName, $user, $password )
-       {
+       protected function openCataloged( $dbName, $user, $password ) {
                @$this->mConn = db2_pconnect( $dbName, $user, $password );
        }
 
@@ -422,34 +412,15 @@ ERROR;
        public function close() {
                $this->mOpened = false;
                if ( $this->mConn ) {
-                       if ($this->trxLevel() > 0) {
+                       if ( $this->trxLevel() > 0 ) {
                                $this->commit();
                        }
                        return db2_close( $this->mConn );
-               }
-               else {
+               } else {
                        return true;
                }
        }
 
-       /**
-        * Returns a fresh instance of this class
-        *
-        * @param $server String: hostname of database server
-        * @param $user String: username
-        * @param $password String
-        * @param $dbName String: database name on the server
-        * @param $failFunction Callback (optional)
-        * @param $flags Integer: database behaviour flags (optional, unused)
-        * @return DatabaseIbm_db2 object
-        */
-       static function newFromParams( $server, $user, $password, $dbName,
-               $failFunction = false, $flags = 0 )
-       {
-               return new DatabaseIbm_db2( $server, $user, $password, $dbName,
-                       $failFunction, $flags );
-       }
-
        /**
         * Retrieves the most current database error
         * Forces a database rollback
@@ -503,15 +474,15 @@ ERROR;
                $this->applySchema();
 
                $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
-               if( $ret == FALSE ) {
+               if( $ret == false ) {
                        $error = db2_stmt_errormsg();
                        $this->installPrint( "<pre>$sql</pre>" );
                        $this->installPrint( $error );
-                       throw new DBUnexpectedError( $this,  'SQL error: '
+                       throw new DBUnexpectedError( $this, 'SQL error: '
                                . htmlspecialchars( $error ) );
                }
                $this->mLastResult = $ret;
-               $this->mAffectedRows = null;    // Not calculated until asked for
+               $this->mAffectedRows = null; // Not calculated until asked for
                return $ret;
        }
 
@@ -534,12 +505,14 @@ SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST
 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
 EOF;
                $res = $this->query( $sql );
-               if ( !$res ) return false;
+               if ( !$res ) {
+                       return false;
+               }
 
                // If the table exists, there should be one of it
                @$row = $this->fetchRow( $res );
                $count = $row[0];
-               if ( $count == '1' or $count == 1 ) {
+               if ( $count == '1' || $count == 1 ) {
                        return true;
                }
 
@@ -569,7 +542,7 @@ EOF;
 
        /**
         * Fetch the next row from the given result object, in associative array
-        * form.  Fields are retrieved with $row['fieldname'].
+        * form. Fields are retrieved with $row['fieldname'].
         *
         * @param $res SQL result object as returned from Database::query(), etc.
         * @return DB2 row object
@@ -587,13 +560,6 @@ EOF;
                return $row;
        }
 
-       /**
-        * Override if introduced to base Database class
-        */
-       public function initial_setup() {
-               // do nothing
-       }
-
        /**
         * Create tables, stored procedures, and so on
         */
@@ -607,32 +573,28 @@ EOF;
 
                        $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
                        if ( $res !== true ) {
-                               print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
+                               print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
                        } else {
-                               print " done</li>";
+                               print ' done</li>';
                        }
                        $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
                        if ( $res !== true ) {
-                               print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
+                               print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
                        } else {
-                               print "<li>Foreign keys done</li>";
+                               print '<li>Foreign keys done</li>';
                        }
-                       $res = null;
 
                        // TODO: populate interwiki links
 
                        if ( $this->lastError() ) {
                                $this->installPrint(
-                                       "Errors encountered during table creation -- rolled back" );
-                               $this->installPrint( "Please install again" );
+                                       'Errors encountered during table creation -- rolled back' );
+                               $this->installPrint( 'Please install again' );
                                $this->rollback();
-                       }
-                       else {
+                       } else {
                                $this->commit();
                        }
-               }
-               catch ( MWException $mwe )
-               {
+               } catch ( MWException $mwe ) {
                        print "<br><pre>$mwe</pre><br>";
                }
        }
@@ -640,43 +602,44 @@ EOF;
        /**
         * Escapes strings
         * Doesn't escape numbers
+        *
         * @param $s String: string to escape
         * @return escaped string
         */
        public function addQuotes( $s ) {
                //$this->installPrint( "DB2::addQuotes( $s )\n" );
                if ( is_null( $s ) ) {
-                       return "NULL";
-               } else if ( $s instanceof Blob ) {
+                       return 'NULL';
+               } elseif ( $s instanceof Blob ) {
                        return "'" . $s->fetch( $s ) . "'";
-               } else if ( $s instanceof IBM_DB2Blob ) {
+               } elseif ( $s instanceof IBM_DB2Blob ) {
                        return "'" . $this->decodeBlob( $s ) . "'";
                }
                $s = $this->strencode( $s );
                if ( is_numeric( $s ) ) {
                        return $s;
-               }
-               else {
+               } else {
                        return "'$s'";
                }
        }
 
        /**
         * Verifies that a DB2 column/field type is numeric
-        * @return bool true if numeric
+        *
         * @param $type String: DB2 column type
+        * @return Boolean: true if numeric
         */
        public function is_numeric_type( $type ) {
-               switch ( strtoupper( $type )) {
-               case 'SMALLINT':
-               case 'INTEGER':
-               case 'INT':
-               case 'BIGINT':
-               case 'DECIMAL':
-               case 'REAL':
-               case 'DOUBLE':
-               case 'DECFLOAT':
-                       return true;
+               switch ( strtoupper( $type ) ) {
+                       case 'SMALLINT':
+                       case 'INTEGER':
+                       case 'INT':
+                       case 'BIGINT':
+                       case 'DECIMAL':
+                       case 'REAL':
+                       case 'DOUBLE':
+                       case 'DECFLOAT':
+                               return true;
                }
                return false;
        }
@@ -695,7 +658,7 @@ EOF;
                $s = utf8_encode( $s );
                // Fix its stupidity
                $from = array(  "\\\\", "\\'",  '\\n',  '\\t',  '\\"',  '\\r' );
-               $to =   array(          "\\",           "''",           "\n",           "\t",           '"',            "\r" );
+               $to = array(            "\\",           "''",           "\n",           "\t",           '"',            "\r" );
                $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
                return $s;
        }
@@ -766,7 +729,7 @@ EOF;
        function makeList( $a, $mode = LIST_COMMA ) {
                if ( !is_array( $a ) ) {
                        throw new DBUnexpectedError( $this,
-                               'DatabaseBase::makeList called with incorrect parameters' );
+                               'DatabaseIbm_db2::makeList called with incorrect parameters' );
                }
 
                // if this is for a prepared UPDATE statement
@@ -778,8 +741,7 @@ EOF;
                        foreach ( $a as $field => $value ) {
                                if ( !$first ) {
                                        $list .= ", $field = ?";
-                               }
-                               else {
+                               } else {
                                        $list .= "$field = ?";
                                        $first = false;
                                }
@@ -796,6 +758,7 @@ EOF;
        /**
         * Construct a LIMIT query with optional offset
         * This is used for query pages
+        *
         * @param $sql string SQL query we will append the limit too
         * @param $limit integer the SQL limit
         * @param $offset integer the SQL offset (default false)
@@ -808,8 +771,7 @@ EOF;
                if( $offset ) {
                        if ( stripos( $sql, 'where' ) === false ) {
                                return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
-                       }
-                       else {
+                       } else {
                                return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
                        }
                }
@@ -818,8 +780,9 @@ EOF;
 
        /**
         * Handle reserved keyword replacement in table names
-        * @return
+        *
         * @param $name Object
+        * @return String
         */
        public function tableName( $name ) {
                // we want maximum compatibility with MySQL schema
@@ -828,10 +791,11 @@ EOF;
 
        /**
         * Generates a timestamp in an insertable format
-        * @return string timestamp value
+        *
         * @param $ts timestamp
+        * @return String: timestamp value
         */
-       public function timestamp( $ts=0 ) {
+       public function timestamp( $ts = 0 ) {
                // TS_MW cannot be easily distinguished from an integer
                return wfTimestamp( TS_DB2, $ts );
        }
@@ -867,6 +831,7 @@ EOF;
        /**
         * Updates the mInsertId property with the value of the last insert
         *  into a generated column
+        *
         * @param $table      String: sanitized table name
         * @param $primaryKey Mixed: string name of the primary key
         * @param $stmt       Resource: prepared statement resource
@@ -925,7 +890,7 @@ EOF;
                // assume success
                $res = true;
                // If we are not in a transaction, we need to be for savepoint trickery
-               if ( ! $this->mTrxLevel ) {
+               if ( !$this->mTrxLevel ) {
                        $this->begin();
                }
 
@@ -950,14 +915,13 @@ EOF;
                                // insert each row into the database
                                $res = $res & $this->execute( $stmt, $row );
                                if ( !$res ) {
-                                       $this->installPrint( "Last error:" );
+                                       $this->installPrint( 'Last error:' );
                                        $this->installPrint( $this->lastError() );
                                }
                                // get the last inserted value into a generated column
                                $this->calcInsertId( $table, $primaryKey, $stmt );
                        }
-               }
-               else {
+               } else {
                        $olde = error_reporting( 0 );
                        // For future use, we may want to track the number of actual inserts
                        // Right now, insert (all writes) simply return true/false
@@ -970,11 +934,10 @@ EOF;
                                $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
                                db2_exec( $this->mConn, $overhead, $this->mStmtOptions );
 
-
                                $this->execute( $stmt, $row );
 
                                if ( !$res2 ) {
-                                       $this->installPrint( "Last error:" );
+                                       $this->installPrint( 'Last error:' );
                                        $this->installPrint( $this->lastError() );
                                }
                                // get the last inserted value into a generated column
@@ -984,8 +947,7 @@ EOF;
                                if ( $errNum ) {
                                        db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore",
                                                $this->mStmtOptions );
-                               }
-                               else {
+                               } else {
                                        db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore",
                                                $this->mStmtOptions );
                                        $numrowsinserted++;
@@ -1015,18 +977,20 @@ EOF;
                $schema = $this->mSchema;
                // find out the primary keys
                $keyres = db2_primary_keys( $this->mConn, null, strtoupper( $schema ),
-                       strtoupper( $table ));
+                       strtoupper( $table )
+               );
                $keys = array();
                for (
                        $row = $this->fetchObject( $keyres );
                        $row != null;
-                       $row = $this->fetchObject( $keyres ))
+                       $row = $this->fetchObject( $keyres )
+               )
                {
                        $keys[] = strtolower( $row->column_name );
                }
                // remove primary keys
                foreach ( $args as $ai => $row ) {
-                       foreach ( $keys as $ki => $key ) {
+                       foreach ( $keys as $key ) {
                                if ( $row[$key] == null ) {
                                        unset( $row[$key] );
                                }
@@ -1049,7 +1013,7 @@ EOF;
         *                 more of IGNORE, LOW_PRIORITY
         * @return Boolean
         */
-       public function update( $table, $values, $conds, $fname = 'Database::update',
+       public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
                $options = array() )
        {
                $table = $this->tableName( $table );
@@ -1060,7 +1024,7 @@ EOF;
                        $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
                }
                $stmt = $this->prepare( $sql );
-               $this->installPrint( "UPDATE: " . print_r( $values, TRUE ));
+               $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
                // assuming for now that an array with string keys will work
                // if not, convert to simple array first
                $result = $this->execute( $stmt, $values );
@@ -1074,10 +1038,10 @@ EOF;
         *
         * Use $conds == "*" to delete all rows
         */
-       public function delete( $table, $conds, $fname = 'Database::delete' ) {
+       public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
                if ( !$conds ) {
                        throw new DBUnexpectedError( $this,
-                       'Database::delete() called with no conditions' );
+                               'DatabaseIbm_db2::delete() called with no conditions' );
                }
                $table = $this->tableName( $table );
                $sql = "DELETE FROM $table";
@@ -1098,8 +1062,9 @@ EOF;
                        // Forced result for simulated queries
                        return $this->mAffectedRows;
                }
-               if( empty( $this->mLastResult ) )
+               if( empty( $this->mLastResult ) ) {
                        return 0;
+               }
                return db2_num_rows( $this->mLastResult );
        }
 
@@ -1133,7 +1098,7 @@ EOF;
                                foreach ( $uniqueIndexes as $index ) {
                                        if ( $first ) {
                                                $first = false;
-                                               $sql .= "( ";
+                                               $sql .= '( ';
                                        } else {
                                                $sql .= ' ) OR ( ';
                                        }
@@ -1175,8 +1140,7 @@ EOF;
                }
                if ( $this->mNumRows ) {
                        return $this->mNumRows;
-               }
-               else {
+               } else {
                        return 0;
                }
        }
@@ -1208,7 +1172,7 @@ EOF;
                        $res = $res->result;
                }
                if ( !@db2_free_result( $res ) ) {
-                       throw new DBUnexpectedError( $this,  "Unable to free DB2 result\n" );
+                       throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
                }
        }
 
@@ -1255,20 +1219,17 @@ EOF;
         * @return Mixed: database result resource for fetch functions or false
         *                 on failure
         */
-       public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
+       public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
        {
                $res = parent::select( $table, $vars, $conds, $fname, $options,
                        $join_conds );
 
                // We must adjust for offset
-               if ( isset( $options['LIMIT'] ) ) {
-                       if ( isset ( $options['OFFSET'] ) ) {
-                               $limit = $options['LIMIT'];
-                               $offset = $options['OFFSET'];
-                       }
+               if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
+                       $limit = $options['LIMIT'];
+                       $offset = $options['OFFSET'];
                }
 
-
                // DB2 does not have a proper num_rows() function yet, so we must emulate
                // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
                //  a working one
@@ -1291,7 +1252,6 @@ EOF;
                $obj = $this->fetchObject( $res2 );
                $this->mNumRows = $obj->num_rows;
 
-
                return $res;
        }
 
@@ -1337,10 +1297,10 @@ EOF;
 
        /**
         * Returns link to IBM DB2 free download
-        * @return string wikitext of a link to the server software's web site
+        * @return String: wikitext of a link to the server software's web site
         */
        public static function getSoftwareLink() {
-               return "[http://www.ibm.com/db2/express/ IBM DB2]";
+               return '[http://www.ibm.com/db2/express/ IBM DB2]';
        }
 
        /**
@@ -1350,7 +1310,7 @@ EOF;
         * @return String
         */
        public function getSearchEngine() {
-               return "SearchIBM_DB2";
+               return 'SearchIBM_DB2';
        }
 
        /**
@@ -1392,9 +1352,9 @@ EOF;
         * Not implemented
         * @return string ''
         */
-       public function getStatus( $which="%" ) {
-                       $this->installPrint( 'Not implemented for DB2: getStatus()' );
-                       return '';
+       public function getStatus( $which = '%' ) {
+               $this->installPrint( 'Not implemented for DB2: getStatus()' );
+               return '';
        }
        /**
         * Not implemented
@@ -1443,8 +1403,9 @@ SQL;
                $row = $this->fetchObject( $res );
                if ( $row != null ) {
                        return $row;
+               } else {
+                       return false;
                }
-               else return false;
        }
 
        /**
@@ -1478,7 +1439,7 @@ SQL;
         * @return Bool
         */
        public function indexUnique ( $table, $index,
-               $fname = 'Database::indexUnique' )
+               $fname = 'DatabaseIbm_db2::indexUnique' )
        {
                $table = $this->tableName( $table );
                $sql = <<<SQL
@@ -1533,7 +1494,7 @@ SQL;
        {
                if ( !$conds ) {
                        throw new DBUnexpectedError( $this,
-                       'Database::deleteJoin() called with empty $conds' );
+                               'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
                }
 
                $delTable = $this->tableName( $delTable );
@@ -1681,7 +1642,7 @@ SQL;
         * Switches module between regular and install modes
         */
        public function setMode( $mode ) {
-               $old =  $this->mMode;
+               $old = $this->mMode;
                $this->mMode = $mode;
                return $old;
        }
@@ -1693,7 +1654,7 @@ SQL;
         * @return String
         */
        function bitNot( $field ) {
-               //expecting bit-fields smaller than 4bytes
+               // expecting bit-fields smaller than 4bytes
                return "BITNOT( $field )";
        }