r72213 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r72212‎ | r72213 | r72214 >
Date:19:10, 2 September 2010
Author:leonsp
Status:ok
Tags:
Comment:
Based on r72134 feedback, applied spacing conventions from MediaWiki style guide, eliminated one-line ifs, wrapped all lines at less than 80 chars, and improved comments a bit.
Modified paths:
  • /trunk/phase3/includes/db/DatabaseIbm_db2.php (modified) (history)

Diff [purge]

Index: trunk/phase3/includes/db/DatabaseIbm_db2.php
@@ -1,7 +1,8 @@
22 <?php
33 /**
44 * This is the IBM DB2 database abstraction layer.
5 - * See maintenance/ibm_db2/README for development notes and other specific information
 5+ * See maintenance/ibm_db2/README for development notes
 6+ * and other specific information
67 *
78 * @file
89 * @ingroup Database
@@ -26,26 +27,26 @@
2728 * @param $field String: column name
2829 * @return IBM_DB2Field
2930 */
30 - static function fromText($db, $table, $field) {
 31+ static function fromText( $db, $table, $field ) {
3132 global $wgDBmwschema;
3233
3334 $q = <<<SQL
3435 SELECT
35 -lcase(coltype) AS typname,
 36+lcase( coltype ) AS typname,
3637 nulls AS attnotnull, length AS attlen
3738 FROM sysibm.syscolumns
3839 WHERE tbcreator=%s AND tbname=%s AND name=%s;
3940 SQL;
40 - $res = $db->query(sprintf($q,
41 - $db->addQuotes($wgDBmwschema),
42 - $db->addQuotes($table),
43 - $db->addQuotes($field)));
44 - $row = $db->fetchObject($res);
45 - if (!$row)
 41+ $res = $db->query( sprintf( $q,
 42+ $db->addQuotes( $wgDBmwschema ),
 43+ $db->addQuotes( $table ),
 44+ $db->addQuotes( $field )) );
 45+ $row = $db->fetchObject( $res );
 46+ if ( !$row )
4647 return null;
4748 $n = new IBM_DB2Field;
4849 $n->type = $row->typname;
49 - $n->nullable = ($row->attnotnull == 'N');
 50+ $n->nullable = ( $row->attnotnull == 'N' );
5051 $n->name = $field;
5152 $n->tablename = $table;
5253 $n->max_length = $row->attlen;
@@ -85,7 +86,7 @@
8687 class IBM_DB2Blob {
8788 private $mData;
8889
89 - public function __construct($data) {
 90+ public function __construct( $data ) {
9091 $this->mData = $data;
9192 }
9293
@@ -122,196 +123,45 @@
123124 *
124125 */
125126
126 - /// Server port
 127+ /** Database server port */
127128 protected $mPort = null;
128 - /// Schema for tables, stored procedures, triggers
 129+ /** Schema for tables, stored procedures, triggers */
129130 protected $mSchema = null;
130 - /// Whether the schema has been applied in this session
 131+ /** Whether the schema has been applied in this session */
131132 protected $mSchemaSet = false;
132 - /// Result of last query
 133+ /** Result of last query */
133134 protected $mLastResult = null;
134 - /// Number of rows affected by last INSERT/UPDATE/DELETE
 135+ /** Number of rows affected by last INSERT/UPDATE/DELETE */
135136 protected $mAffectedRows = null;
136 - /// Number of rows returned by last SELECT
 137+ /** Number of rows returned by last SELECT */
137138 protected $mNumRows = null;
138139
139 - /// Connection config options - see constructor
 140+ /** Connection config options - see constructor */
140141 public $mConnOptions = array();
141 - /// Statement config options -- see constructor
 142+ /** Statement config options -- see constructor */
142143 public $mStmtOptions = array();
143144
 145+ /** Default schema */
 146+ const USE_GLOBAL = "mediawiki";
144147
145 - const USE_GLOBAL = "get from global";
146 -
 148+ /** Option that applies to nothing */
147149 const NONE_OPTION = 0x00;
 150+ /** Option that applies to connection objects */
148151 const CONN_OPTION = 0x01;
 152+ /** Option that applies to statement objects */
149153 const STMT_OPTION = 0x02;
150154
 155+ /** Regular operation mode -- minimal debug messages */
151156 const REGULAR_MODE = 'regular';
 157+ /** Installation mode -- lots of debug messages */
152158 const INSTALL_MODE = 'install';
153159
154 - // Whether this is regular operation or the initial installation
 160+ /** Controls the level of debug message output */
155161 protected $mMode = self::REGULAR_MODE;
156162
157 - /// Last sequence value used for a primary key
 163+ /** Last sequence value used for a primary key */
158164 protected $mInsertId = null;
159165
160 - /*
161 - * These can be safely inherited
162 - *
163 - * Getter/Setter: (18)
164 - * failFunction
165 - * bufferResults
166 - * ignoreErrors
167 - * trxLevel
168 - * errorCount
169 - * getLBInfo
170 - * setLBInfo
171 - * lastQuery
172 - * isOpen
173 - * setFlag
174 - * clearFlag
175 - * getFlag
176 - * getProperty
177 - * getDBname
178 - * getServer
179 - * tableNameCallback
180 - * tablePrefix
181 - *
182 - * Administrative: (8)
183 - * debug
184 - * installErrorHandler
185 - * restoreErrorHandler
186 - * connectionErrorHandler
187 - * reportConnectionError
188 - * sourceFile
189 - * sourceStream
190 - * replaceVars
191 - *
192 - * Database: (5)
193 - * query
194 - * set
195 - * selectField
196 - * generalizeSQL
197 - * update
198 - * strreplace
199 - * deadlockLoop
200 - *
201 - * Prepared Statement: 6
202 - * prepare
203 - * freePrepared
204 - * execute
205 - * safeQuery
206 - * fillPrepared
207 - * fillPreparedArg
208 - *
209 - * Slave/Master: (4)
210 - * masterPosWait
211 - * getSlavePos
212 - * getMasterPos
213 - * getLag
214 - * setFakeMaster
215 - *
216 - * Generation: (9)
217 - * tableNames
218 - * tableNamesN
219 - * tableNamesWithUseIndexOrJOIN
220 - * escapeLike
221 - * delete
222 - * insertSelect
223 - * timestampOrNull
224 - * resultObject
225 - * aggregateValue
226 - * selectSQLText
227 - * selectRow
228 - * makeUpdateOptions
229 - *
230 - * Reflection: (1)
231 - * indexExists
232 - */
233 -
234 - /*
235 - * These have been implemented
236 - *
237 - * Administrative: 7 / 7
238 - * constructor [Done]
239 - * open [Done]
240 - * openCataloged [Done]
241 - * close [Done]
242 - * newFromParams [Done]
243 - * openUncataloged [Done]
244 - * setup_database [Done]
245 - *
246 - * Getter/Setter: 13 / 13
247 - * cascadingDeletes [Done]
248 - * cleanupTriggers [Done]
249 - * strictIPs [Done]
250 - * realTimestamps [Done]
251 - * impliciGroupby [Done]
252 - * implicitOrderby [Done]
253 - * searchableIPs [Done]
254 - * functionalIndexes [Done]
255 - * getWikiID [Done]
256 - * isOpen [Done]
257 - * getServerVersion [Done]
258 - * getSoftwareLink [Done]
259 - * getSearchEngine [Done]
260 - *
261 - * Database driver wrapper: 23 / 23
262 - * lastError [Done]
263 - * lastErrno [Done]
264 - * doQuery [Done]
265 - * tableExists [Done]
266 - * fetchObject [Done]
267 - * fetchRow [Done]
268 - * freeResult [Done]
269 - * numRows [Done]
270 - * numFields [Done]
271 - * fieldName [Done]
272 - * insertId [Done]
273 - * dataSeek [Done]
274 - * affectedRows [Done]
275 - * selectDB [Done]
276 - * strencode [Done]
277 - * conditional [Done]
278 - * wasDeadlock [Done]
279 - * ping [Done]
280 - * getStatus [Done]
281 - * setTimeout [Done]
282 - * lock [Done]
283 - * unlock [Done]
284 - * insert [Done]
285 - * select [Done]
286 - *
287 - * Slave/master: 2 / 2
288 - * setFakeSlaveLag [Done] - Where??
289 - *
290 - * Reflection: 5 / 5
291 - * indexInfo [Done]
292 - * fieldInfo [Done]
293 - * fieldType [Done]
294 - * indexUnique [Done]
295 - * textFieldSize [Done]
296 - *
297 - * Generation: 16 / 16
298 - * tableName [Done]
299 - * addQuotes [Done]
300 - * makeList [Done]
301 - * makeSelectOptions [Done]
302 - * estimateRowCount [Done]
303 - * nextSequenceValue [Done]
304 - * useIndexClause [Done]
305 - * replace [Done]
306 - * deleteJoin [Done]
307 - * lowPriorityOption [Done]
308 - * limitResult [Done]
309 - * limitResultForUpdate [Done]
310 - * timestamp [Done]
311 - * encodeBlob [Done]
312 - * decodeBlob [Done]
313 - * buildConcat [Done]
314 - */
315 -
316166 ######################################
317167 # Getters and Setters
318168 ######################################
@@ -324,14 +174,16 @@
325175 }
326176
327177 /**
328 - * Returns true if this database supports (and uses) triggers (e.g. on the page table)
 178+ * Returns true if this database supports (and uses) triggers (e.g. on the
 179+ * page table)
329180 */
330181 function cleanupTriggers() {
331182 return true;
332183 }
333184
334185 /**
335 - * Returns true if this database is strict about what can be put into an IP field.
 186+ * Returns true if this database is strict about what can be put into an
 187+ * IP field.
336188 * Specifically, it uses a NULL value instead of an empty string.
337189 */
338190 function strictIPs() {
@@ -353,7 +205,8 @@
354206 }
355207
356208 /**
357 - * Returns true if this database does an implicit order by when the column has an index
 209+ * Returns true if this database does an implicit order by when the column
 210+ * has an index
358211 * For example: SELECT page_title FROM page LIMIT 1
359212 */
360213 function implicitOrderby() {
@@ -405,7 +258,8 @@
406259 * @param $flags Integer: database behaviour flags (optional, unused)
407260 * @param $schema String
408261 */
409 - public function DatabaseIbm_db2($server = false, $user = false, $password = false,
 262+ public function DatabaseIbm_db2( $server = false, $user = false,
 263+ $password = false,
410264 $dbName = false, $failFunction = false, $flags = 0,
411265 $schema = self::USE_GLOBAL )
412266 {
@@ -427,11 +281,14 @@
428282 }
429283
430284 // configure the connection and statement objects
431 - $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self::CONN_OPTION | self::STMT_OPTION);
432 - $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self::STMT_OPTION);
433 - $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self::STMT_OPTION);
 285+ $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
 286+ self::CONN_OPTION | self::STMT_OPTION );
 287+ $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
 288+ self::STMT_OPTION );
 289+ $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
 290+ self::STMT_OPTION );
434291
435 - $this->open( $server, $user, $password, $dbName);
 292+ $this->open( $server, $user, $password, $dbName );
436293 }
437294
438295 /**
@@ -440,13 +297,18 @@
441298 * @param $const String: name of the constant holding the right option value
442299 * @param $type Integer: whether this is a Connection or Statement otion
443300 */
444 - private function setDB2Option($name, $const, $type) {
445 - if (defined($const)) {
446 - if ($type & self::CONN_OPTION) $this->mConnOptions[$name] = constant($const);
447 - if ($type & self::STMT_OPTION) $this->mStmtOptions[$name] = constant($const);
 301+ private function setDB2Option( $name, $const, $type ) {
 302+ if ( defined( $const )) {
 303+ if ( $type & self::CONN_OPTION ) {
 304+ $this->mConnOptions[$name] = constant( $const );
 305+ }
 306+ if ( $type & self::STMT_OPTION ) {
 307+ $this->mStmtOptions[$name] = constant( $const );
 308+ }
448309 }
449310 else {
450 - $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
 311+ $this->installPrint(
 312+ "$const is not defined. ibm_db2 version is likely too low." );
451313 }
452314 }
453315
@@ -454,9 +316,9 @@
455317 * Outputs debug information in the appropriate place
456318 * @param $string String: the relevant debug message
457319 */
458 - private function installPrint($string) {
459 - wfDebug("$string\n");
460 - if ($this->mMode == self::INSTALL_MODE) {
 320+ private function installPrint( $string ) {
 321+ wfDebug( "$string\n" );
 322+ if ( $this->mMode == self::INSTALL_MODE ) {
461323 print "<li><pre>$string</pre></li>";
462324 flush();
463325 }
@@ -482,12 +344,15 @@
483345
484346 // Test for IBM DB2 support, to avoid suppressed fatal error
485347 if ( !function_exists( 'db2_connect' ) ) {
486 - $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
487 - $this->installPrint($error);
488 - $this->reportConnectionError($error);
 348+ $error = <<<ERROR
 349+DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
 350+
 351+ERROR;
 352+ $this->installPrint( $error );
 353+ $this->reportConnectionError( $error );
489354 }
490355
491 - if (!strlen($user)) { // Copied from Postgres
 356+ if ( strlen( $user ) < 1) {
492357 return null;
493358 }
494359
@@ -500,18 +365,21 @@
501366 $this->mPassword = $password;
502367 $this->mDBname = $dbName;
503368
504 - $this->openUncataloged($dbName, $user, $password, $server, $port);
 369+ $this->openUncataloged( $dbName, $user, $password, $server, $port );
505370
506371 // Apply connection config
507 - db2_set_option($this->mConn, $this->mConnOptions, 1);
508 - // Not all MediaWiki code is transactional
509 - // Rather, turn autocommit off in the begin function and turn on after a commit
510 - db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
 372+ db2_set_option( $this->mConn, $this->mConnOptions, 1 );
 373+ // Some MediaWiki code is still transaction-less (?).
 374+ // The strategy is to keep AutoCommit on for that code
 375+ // but switch it off whenever a transaction is begun.
 376+ db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
511377
512378 if ( !$this->mConn ) {
513379 $this->installPrint( "DB connection error\n" );
514 - $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
515 - $this->installPrint( $this->lastError()."\n" );
 380+ $this->installPrint(
 381+ "Server: $server, Database: $dbName, User: $user, Password: "
 382+ . substr( $password, 0, 3 ) . "...\n" );
 383+ $this->installPrint( $this->lastError() . "\n" );
516384 return null;
517385 }
518386
@@ -527,7 +395,7 @@
528396 */
529397 protected function openCataloged( $dbName, $user, $password )
530398 {
531 - @$this->mConn = db2_pconnect($dbName, $user, $password);
 399+ @$this->mConn = db2_pconnect( $dbName, $user, $password );
532400 }
533401
534402 /**
@@ -538,12 +406,13 @@
539407 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
540408 $str .= "DATABASE=$dbName;";
541409 $str .= "HOSTNAME=$server;";
542 - if ($port) $str .= "PORT=$port;";
 410+ // port was formerly validated to not be 0
 411+ $str .= "PORT=$port;";
543412 $str .= "PROTOCOL=TCPIP;";
544413 $str .= "UID=$user;";
545414 $str .= "PWD=$password;";
546415
547 - @$this->mConn = db2_pconnect($str, $user, $password);
 416+ @$this->mConn = db2_pconnect( $str, $user, $password );
548417 }
549418
550419 /**
@@ -574,9 +443,11 @@
575444 * @param $flags Integer: database behaviour flags (optional, unused)
576445 * @return DatabaseIbm_db2 object
577446 */
578 - static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
 447+ static function newFromParams( $server, $user, $password, $dbName,
 448+ $failFunction = false, $flags = 0 )
579449 {
580 - return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
 450+ return new DatabaseIbm_db2( $server, $user, $password, $dbName,
 451+ $failFunction, $flags );
581452 }
582453
583454 /**
@@ -585,12 +456,12 @@
586457 */
587458 public function lastError() {
588459 $connerr = db2_conn_errormsg();
589 - if ($connerr) {
 460+ if ( $connerr ) {
590461 //$this->rollback();
591462 return $connerr;
592463 }
593464 $stmterr = db2_stmt_errormsg();
594 - if ($stmterr) {
 465+ if ( $stmterr ) {
595466 //$this->rollback();
596467 return $stmterr;
597468 }
@@ -605,9 +476,13 @@
606477 */
607478 public function lastErrno() {
608479 $connerr = db2_conn_error();
609 - if ($connerr) return $connerr;
 480+ if ( $connerr ) {
 481+ return $connerr;
 482+ }
610483 $stmterr = db2_stmt_error();
611 - if ($stmterr) return $stmterr;
 484+ if ( $stmterr ) {
 485+ return $stmterr;
 486+ }
612487 return 0;
613488 }
614489
@@ -620,7 +495,7 @@
621496 /**
622497 * The DBMS-dependent part of query()
623498 * @param $sql String: SQL query.
624 - * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
 499+ * @return object Result object for fetch functions or false on failure
625500 * @access private
626501 */
627502 /*private*/
@@ -630,9 +505,10 @@
631506 $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
632507 if( $ret == FALSE ) {
633508 $error = db2_stmt_errormsg();
634 - $this->installPrint("<pre>$sql</pre>");
635 - $this->installPrint($error);
636 - throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
 509+ $this->installPrint( "<pre>$sql</pre>" );
 510+ $this->installPrint( $error );
 511+ throw new DBUnexpectedError( $this, 'SQL error: '
 512+ . htmlspecialchars( $error ) );
637513 }
638514 $this->mLastResult = $ret;
639515 $this->mAffectedRows = null; // Not calculated until asked for
@@ -654,16 +530,16 @@
655531 public function tableExists( $table ) {
656532 $schema = $this->mSchema;
657533 $sql = <<< EOF
658 -SELECT COUNT(*) FROM SYSIBM.SYSTABLES ST
 534+SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST
659535 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
660536 EOF;
661537 $res = $this->query( $sql );
662 - if (!$res) return false;
 538+ if ( !$res ) return false;
663539
664540 // If the table exists, there should be one of it
665 - @$row = $this->fetchRow($res);
 541+ @$row = $this->fetchRow( $res );
666542 $count = $row[0];
667 - if ($count == '1' or $count == 1) {
 543+ if ( $count == '1' or $count == 1 ) {
668544 return true;
669545 }
670546
@@ -685,7 +561,8 @@
686562 }
687563 @$row = db2_fetch_object( $res );
688564 if( $this->lastErrno() ) {
689 - throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
 565+ throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
 566+ . htmlspecialchars( $this->lastError() ) );
690567 }
691568 return $row;
692569 }
@@ -704,7 +581,8 @@
705582 }
706583 @$row = db2_fetch_array( $res );
707584 if ( $this->lastErrno() ) {
708 - throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
 585+ throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
 586+ . htmlspecialchars( $this->lastError() ) );
709587 }
710588 return $row;
711589 }
@@ -720,9 +598,6 @@
721599 * Create tables, stored procedures, and so on
722600 */
723601 public function setup_database() {
724 - // Timeout was being changed earlier due to mysterious crashes
725 - // Changing it now may cause more problems than not changing it
726 - //set_time_limit(240);
727602 try {
728603 // TODO: switch to root login if available
729604
@@ -731,13 +606,13 @@
732607 $this->begin();
733608
734609 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
735 - if ($res !== true) {
 610+ if ( $res !== true ) {
736611 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
737612 } else {
738613 print " done</li>";
739614 }
740615 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
741 - if ($res !== true) {
 616+ if ( $res !== true ) {
742617 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
743618 } else {
744619 print "<li>Foreign keys done</li>";
@@ -746,16 +621,17 @@
747622
748623 // TODO: populate interwiki links
749624
750 - if ($this->lastError()) {
751 - print "<li>Errors encountered during table creation -- rolled back</li>\n";
752 - print "<li>Please install again</li>\n";
 625+ if ( $this->lastError() ) {
 626+ $this->installPrint(
 627+ "Errors encountered during table creation -- rolled back" );
 628+ $this->installPrint( "Please install again" );
753629 $this->rollback();
754630 }
755631 else {
756632 $this->commit();
757633 }
758634 }
759 - catch (MWException $mwe)
 635+ catch ( MWException $mwe )
760636 {
761637 print "<br><pre>$mwe</pre><br>";
762638 }
@@ -768,16 +644,16 @@
769645 * @return escaped string
770646 */
771647 public function addQuotes( $s ) {
772 - //$this->installPrint("DB2::addQuotes($s)\n");
 648+ //$this->installPrint( "DB2::addQuotes( $s )\n" );
773649 if ( is_null( $s ) ) {
774650 return "NULL";
775 - } else if ($s instanceof Blob) {
776 - return "'".$s->fetch($s)."'";
777 - } else if ($s instanceof IBM_DB2Blob) {
778 - return "'".$this->decodeBlob($s)."'";
 651+ } else if ( $s instanceof Blob ) {
 652+ return "'" . $s->fetch( $s ) . "'";
 653+ } else if ( $s instanceof IBM_DB2Blob ) {
 654+ return "'" . $this->decodeBlob( $s ) . "'";
779655 }
780 - $s = $this->strencode($s);
781 - if ( is_numeric($s) ) {
 656+ $s = $this->strencode( $s );
 657+ if ( is_numeric( $s ) ) {
782658 return $s;
783659 }
784660 else {
@@ -791,7 +667,7 @@
792668 * @param $type String: DB2 column type
793669 */
794670 public function is_numeric_type( $type ) {
795 - switch (strtoupper($type)) {
 671+ switch ( strtoupper( $type )) {
796672 case 'SMALLINT':
797673 case 'INTEGER':
798674 case 'INT':
@@ -814,13 +690,13 @@
815691 // Bloody useless function
816692 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
817693 // But also necessary
818 - $s = db2_escape_string($s);
 694+ $s = db2_escape_string( $s );
819695 // Wide characters are evil -- some of them look like '
820 - $s = utf8_encode($s);
 696+ $s = utf8_encode( $s );
821697 // Fix its stupidity
822 - $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
823 - $to = array("\\", "''", "\n", "\t", '"', "\r");
824 - $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
 698+ $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
 699+ $to = array( "\\", "''", "\n", "\t", '"', "\r" );
 700+ $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
825701 return $s;
826702 }
827703
@@ -828,10 +704,10 @@
829705 * Switch into the database schema
830706 */
831707 protected function applySchema() {
832 - if ( !($this->mSchemaSet) ) {
 708+ if ( !( $this->mSchemaSet ) ) {
833709 $this->mSchemaSet = true;
834710 $this->begin();
835 - $this->doQuery("SET SCHEMA = $this->mSchema");
 711+ $this->doQuery( "SET SCHEMA = $this->mSchema" );
836712 $this->commit();
837713 }
838714 }
@@ -840,8 +716,14 @@
841717 * Start a transaction (mandatory)
842718 */
843719 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
844 - // turn off auto-commit
845 - db2_autocommit($this->mConn, DB2_AUTOCOMMIT_OFF);
 720+ // BEGIN is implicit for DB2
 721+ // However, it requires that AutoCommit be off.
 722+
 723+ // Some MediaWiki code is still transaction-less (?).
 724+ // The strategy is to keep AutoCommit on for that code
 725+ // but switch it off whenever a transaction is begun.
 726+ db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_OFF );
 727+
846728 $this->mTrxLevel = 1;
847729 }
848730
@@ -850,9 +732,13 @@
851733 * Must have a preceding begin()
852734 */
853735 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
854 - db2_commit($this->mConn);
855 - // turn auto-commit back on
856 - db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
 736+ db2_commit( $this->mConn );
 737+
 738+ // Some MediaWiki code is still transaction-less (?).
 739+ // The strategy is to keep AutoCommit on for that code
 740+ // but switch it off whenever a transaction is begun.
 741+ db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
 742+
857743 $this->mTrxLevel = 0;
858744 }
859745
@@ -860,41 +746,42 @@
861747 * Cancel a transaction
862748 */
863749 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
864 - db2_rollback($this->mConn);
 750+ db2_rollback( $this->mConn );
865751 // turn auto-commit back on
866752 // not sure if this is appropriate
867 - db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
 753+ db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
868754 $this->mTrxLevel = 0;
869755 }
870756
871757 /**
872758 * Makes an encoded list of strings from an array
873759 * $mode:
874 - * LIST_COMMA - comma separated, no field names
875 - * LIST_AND - ANDed WHERE clause (without the WHERE)
876 - * LIST_OR - ORed WHERE clause (without the WHERE)
877 - * LIST_SET - comma separated with field names, like a SET clause
878 - * LIST_NAMES - comma separated field names
879 - * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
 760+ * LIST_COMMA - comma separated, no field names
 761+ * LIST_AND - ANDed WHERE clause (without the WHERE)
 762+ * LIST_OR - ORed WHERE clause (without the WHERE)
 763+ * LIST_SET - comma separated with field names, like a SET clause
 764+ * LIST_NAMES - comma separated field names
 765+ * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
880766 */
881767 function makeList( $a, $mode = LIST_COMMA ) {
882768 if ( !is_array( $a ) ) {
883 - throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
 769+ throw new DBUnexpectedError( $this,
 770+ 'DatabaseBase::makeList called with incorrect parameters' );
884771 }
885772
886773 // if this is for a prepared UPDATE statement
887774 // (this should be promoted to the parent class
888775 // once other databases use prepared statements)
889 - if ($mode == LIST_SET_PREPARED) {
 776+ if ( $mode == LIST_SET_PREPARED ) {
890777 $first = true;
891778 $list = '';
892779 foreach ( $a as $field => $value ) {
893 - if (!$first) {
 780+ if ( !$first ) {
894781 $list .= ", $field = ?";
895782 }
896783 else {
897784 $list .= "$field = ?";
898 - $first = false;
 785+ $first = false;
899786 }
900787 }
901788 $list .= '';
@@ -913,17 +800,17 @@
914801 * @param $limit integer the SQL limit
915802 * @param $offset integer the SQL offset (default false)
916803 */
917 - public function limitResult($sql, $limit, $offset=false) {
918 - if( !is_numeric($limit) ) {
919 - throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
 804+ public function limitResult( $sql, $limit, $offset=false ) {
 805+ if( !is_numeric( $limit ) ) {
 806+ throw new DBUnexpectedError( $this,
 807+ "Invalid non-numeric limit passed to limitResult()\n" );
920808 }
921809 if( $offset ) {
922 - //$this->installPrint("Offset parameter not supported in limitResult()\n");
923 - if ( stripos($sql, 'where') === false ) {
924 - return "$sql AND (ROWNUM BETWEEN $offset AND $offset+$limit)";
 810+ if ( stripos( $sql, 'where' ) === false ) {
 811+ return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
925812 }
926813 else {
927 - return "$sql WHERE (ROWNUM BETWEEN $offset AND $offset+$limit)";
 814+ return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
928815 }
929816 }
930817 return "$sql FETCH FIRST $limit ROWS ONLY ";
@@ -935,15 +822,6 @@
936823 * @param $name Object
937824 */
938825 public function tableName( $name ) {
939 - # Replace reserved words with better ones
940 -// switch( $name ) {
941 -// case 'user':
942 -// return 'mwuser';
943 -// case 'text':
944 -// return 'pagecontent';
945 -// default:
946 -// return $name;
947 -// }
948826 // we want maximum compatibility with MySQL schema
949827 return $name;
950828 }
@@ -955,7 +833,7 @@
956834 */
957835 public function timestamp( $ts=0 ) {
958836 // TS_MW cannot be easily distinguished from an integer
959 - return wfTimestamp(TS_DB2,$ts);
 837+ return wfTimestamp( TS_DB2, $ts );
960838 }
961839
962840 /**
@@ -964,8 +842,10 @@
965843 * @return next value in that sequence
966844 */
967845 public function nextSequenceValue( $seqName ) {
968 - // Not using sequences in the primary schema to allow for easy third-party migration scripts
969 - // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
 846+ // Not using sequences in the primary schema to allow for easier migration
 847+ // from MySQL
 848+ // Emulating MySQL behaviour of using NULL to signal that sequences
 849+ // aren't used
970850 /*
971851 $safeseq = preg_replace( "/'/", "''", $seqName );
972852 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
@@ -985,24 +865,24 @@
986866 }
987867
988868 /**
989 - * Updates the mInsertId property with the value of the last insert into a generated column
 869+ * Updates the mInsertId property with the value of the last insert
 870+ * into a generated column
990871 * @param $table String: sanitized table name
991 - * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
 872+ * @param $primaryKey Mixed: string name of the primary key
992873 * @param $stmt Resource: prepared statement resource
993874 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
994875 */
995 - private function calcInsertId($table, $primaryKey, $stmt) {
996 - if ($primaryKey) {
997 - $this->mInsertId = db2_last_insert_id($this->mConn);
998 - //$this->installPrint("Last $primaryKey for $table was $this->mInsertId");
 876+ private function calcInsertId( $table, $primaryKey, $stmt ) {
 877+ if ( $primaryKey ) {
 878+ $this->mInsertId = db2_last_insert_id( $this->mConn );
999879 }
1000880 }
1001881
1002882 /**
1003883 * INSERT wrapper, inserts an array into a table
1004884 *
1005 - * $args may be a single associative array, or an array of these with numeric keys,
1006 - * for multi-row insert
 885+ * $args may be a single associative array, or an array of arrays
 886+ * with numeric keys, for multi-row insert
1007887 *
1008888 * @param $table String: Name of the table to insert to.
1009889 * @param $args Array: Items to insert into the table.
@@ -1011,31 +891,33 @@
1012892 *
1013893 * @return bool Success of insert operation. IGNORE always returns true.
1014894 */
1015 - public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
 895+ public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
 896+ $options = array() )
 897+ {
1016898 if ( !count( $args ) ) {
1017899 return true;
1018900 }
1019901 // get database-specific table name (not used)
1020902 $table = $this->tableName( $table );
1021903 // format options as an array
1022 - $options = IBM_DB2Helper::makeArray($options);
 904+ $options = IBM_DB2Helper::makeArray( $options );
1023905 // format args as an array of arrays
1024906 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1025 - $args = array($args);
 907+ $args = array( $args );
1026908 }
1027909
1028910 // prevent insertion of NULL into primary key columns
1029 - list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
 911+ list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
1030912 // if there's only one primary key
1031913 // we'll be able to read its value after insertion
1032914 $primaryKey = false;
1033 - if (count($primaryKeys) == 1) {
 915+ if ( count( $primaryKeys ) == 1 ) {
1034916 $primaryKey = $primaryKeys[0];
1035917 }
1036918
1037919 // get column names
1038920 $keys = array_keys( $args[0] );
1039 - $key_count = count($keys);
 921+ $key_count = count( $keys );
1040922
1041923 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1042924 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
@@ -1043,20 +925,20 @@
1044926 // assume success
1045927 $res = true;
1046928 // If we are not in a transaction, we need to be for savepoint trickery
1047 - if (! $this->mTrxLevel) {
 929+ if ( ! $this->mTrxLevel ) {
1048930 $this->begin();
1049931 }
1050932
1051 - $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1052 - if ($key_count == 1) {
1053 - $sql .= '(?)';
 933+ $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
 934+ if ( $key_count == 1 ) {
 935+ $sql .= '( ? )';
1054936 } else {
1055 - $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
 937+ $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1056938 }
1057 - //$this->installPrint("Preparing the following SQL:");
1058 - //$this->installPrint("$sql");
1059 - //$this->installPrint(print_r($args, true));
1060 - $stmt = $this->prepare($sql);
 939+ //$this->installPrint( "Preparing the following SQL:" );
 940+ //$this->installPrint( "$sql" );
 941+ //$this->installPrint( print_r( $args, true ));
 942+ $stmt = $this->prepare( $sql );
1061943
1062944 // start a transaction/enter transaction mode
1063945 $this->begin();
@@ -1064,15 +946,15 @@
1065947 if ( !$ignore ) {
1066948 //$first = true;
1067949 foreach ( $args as $row ) {
1068 - //$this->installPrint("Inserting " . print_r($row, true));
 950+ //$this->installPrint( "Inserting " . print_r( $row, true ));
1069951 // insert each row into the database
1070 - $res = $res & $this->execute($stmt, $row);
1071 - if (!$res) {
1072 - $this->installPrint("Last error:");
1073 - $this->installPrint($this->lastError());
 952+ $res = $res & $this->execute( $stmt, $row );
 953+ if ( !$res ) {
 954+ $this->installPrint( "Last error:" );
 955+ $this->installPrint( $this->lastError() );
1074956 }
1075957 // get the last inserted value into a generated column
1076 - $this->calcInsertId($table, $primaryKey, $stmt);
 958+ $this->calcInsertId( $table, $primaryKey, $stmt );
1077959 }
1078960 }
1079961 else {
@@ -1086,24 +968,26 @@
1087969
1088970 foreach ( $args as $row ) {
1089971 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1090 - db2_exec($this->mConn, $overhead, $this->mStmtOptions);
1091 - //$this->installPrint("Inserting " . print_r($row, true));
 972+ db2_exec( $this->mConn, $overhead, $this->mStmtOptions );
1092973
1093 - $this->execute($stmt, $row);
1094 - //$this->installPrint(wfGetAllCallers());
1095 - if (!$res2) {
1096 - $this->installPrint("Last error:");
1097 - $this->installPrint($this->lastError());
 974+
 975+ $this->execute( $stmt, $row );
 976+
 977+ if ( !$res2 ) {
 978+ $this->installPrint( "Last error:" );
 979+ $this->installPrint( $this->lastError() );
1098980 }
1099981 // get the last inserted value into a generated column
1100 - $this->calcInsertId($table, $primaryKey, $stmt);
 982+ $this->calcInsertId( $table, $primaryKey, $stmt );
1101983
1102984 $errNum = $this->lastErrno();
1103 - if ($errNum) {
1104 - db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions );
 985+ if ( $errNum ) {
 986+ db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore",
 987+ $this->mStmtOptions );
1105988 }
1106989 else {
1107 - db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions );
 990+ db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore",
 991+ $this->mStmtOptions );
1108992 $numrowsinserted++;
1109993 }
1110994 }
@@ -1114,7 +998,7 @@
1115999 }
11161000 // commit either way
11171001 $this->commit();
1118 - $this->freePrepared($stmt);
 1002+ $this->freePrepared( $stmt );
11191003
11201004 return $res;
11211005 }
@@ -1125,27 +1009,32 @@
11261010 *
11271011 * @param $table String: name of the table
11281012 * @param $args Array of hashes of column names with values
1129 - * @return Array: tuple containing filtered array of columns, array of primary keys
 1013+ * @return Array: tuple( filtered array of columns, array of primary keys )
11301014 */
1131 - private function removeNullPrimaryKeys($table, $args) {
 1015+ private function removeNullPrimaryKeys( $table, $args ) {
11321016 $schema = $this->mSchema;
11331017 // find out the primary keys
1134 - $keyres = db2_primary_keys($this->mConn, null, strtoupper($schema), strtoupper($table));
 1018+ $keyres = db2_primary_keys( $this->mConn, null, strtoupper( $schema ),
 1019+ strtoupper( $table ));
11351020 $keys = array();
1136 - for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1137 - $keys[] = strtolower($row->column_name);
 1021+ for (
 1022+ $row = $this->fetchObject( $keyres );
 1023+ $row != null;
 1024+ $row = $this->fetchObject( $keyres ))
 1025+ {
 1026+ $keys[] = strtolower( $row->column_name );
11381027 }
11391028 // remove primary keys
1140 - foreach ($args as $ai => $row) {
1141 - foreach ($keys as $ki => $key) {
1142 - if ($row[$key] == null) {
1143 - unset($row[$key]);
 1029+ foreach ( $args as $ai => $row ) {
 1030+ foreach ( $keys as $ki => $key ) {
 1031+ if ( $row[$key] == null ) {
 1032+ unset( $row[$key] );
11441033 }
11451034 }
11461035 $args[$ai] = $row;
11471036 }
11481037 // return modified hash
1149 - return array($args, $keys);
 1038+ return array( $args, $keys );
11501039 }
11511040
11521041 /**
@@ -1153,29 +1042,30 @@
11541043 *
11551044 * @param $table String: The table to UPDATE
11561045 * @param $values An array of values to SET
1157 - * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
 1046+ * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
11581047 * @param $fname String: The Class::Function calling this function
1159 - * (for the log)
 1048+ * ( for the log )
11601049 * @param $options An array of UPDATE options, can be one or
11611050 * more of IGNORE, LOW_PRIORITY
11621051 * @return Boolean
11631052 */
1164 - public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
 1053+ public function update( $table, $values, $conds, $fname = 'Database::update',
 1054+ $options = array() )
 1055+ {
11651056 $table = $this->tableName( $table );
11661057 $opts = $this->makeUpdateOptions( $options );
1167 - $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET_PREPARED );
 1058+ $sql = "UPDATE $opts $table SET "
 1059+ . $this->makeList( $values, LIST_SET_PREPARED );
11681060 if ( $conds != '*' ) {
11691061 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
11701062 }
11711063 $stmt = $this->prepare( $sql );
1172 - $this->installPrint("UPDATE: " . print_r($values, TRUE));
 1064+ $this->installPrint( "UPDATE: " . print_r( $values, TRUE ));
11731065 // assuming for now that an array with string keys will work
11741066 // if not, convert to simple array first
11751067 $result = $this->execute( $stmt, $values );
11761068 $this->freePrepared( $stmt );
1177 - //$result = $this->query( $sql, $fname );
1178 - // commit regardless of state
1179 - //$this->commit();
 1069+
11801070 return $result;
11811071 }
11821072
@@ -1186,7 +1076,8 @@
11871077 */
11881078 public function delete( $table, $conds, $fname = 'Database::delete' ) {
11891079 if ( !$conds ) {
1190 - throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
 1080+ throw new DBUnexpectedError( $this,
 1081+ 'Database::delete() called with no conditions' );
11911082 }
11921083 $table = $this->tableName( $table );
11931084 $sql = "DELETE FROM $table";
@@ -1194,8 +1085,7 @@
11951086 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
11961087 }
11971088 $result = $this->query( $sql, $fname );
1198 - // commit regardless
1199 - //$this->commit();
 1089+
12001090 return $result;
12011091 }
12021092
@@ -1221,10 +1111,12 @@
12221112 * @param $fname String: name of the function for profiling
12231113 * @return nothing
12241114 */
1225 - function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
 1115+ function replace( $table, $uniqueIndexes, $rows,
 1116+ $fname = 'DatabaseIbm_db2::replace' )
 1117+ {
12261118 $table = $this->tableName( $table );
12271119
1228 - if (count($rows)==0) {
 1120+ if ( count( $rows )==0 ) {
12291121 return;
12301122 }
12311123
@@ -1241,9 +1133,9 @@
12421134 foreach ( $uniqueIndexes as $index ) {
12431135 if ( $first ) {
12441136 $first = false;
1245 - $sql .= "(";
 1137+ $sql .= "( ";
12461138 } else {
1247 - $sql .= ') OR (';
 1139+ $sql .= ' ) OR ( ';
12481140 }
12491141 if ( is_array( $index ) ) {
12501142 $first2 = true;
@@ -1253,19 +1145,20 @@
12541146 } else {
12551147 $sql .= ' AND ';
12561148 }
1257 - $sql .= $col.'=' . $this->addQuotes( $row[$col] );
 1149+ $sql .= $col . '=' . $this->addQuotes( $row[$col] );
12581150 }
12591151 } else {
1260 - $sql .= $index.'=' . $this->addQuotes( $row[$index] );
 1152+ $sql .= $index . '=' . $this->addQuotes( $row[$index] );
12611153 }
12621154 }
1263 - $sql .= ')';
 1155+ $sql .= ' )';
12641156 $this->query( $sql, $fname );
12651157 }
12661158
12671159 # Now insert the row
1268 - $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
1269 - $this->makeList( $row, LIST_COMMA ) . ')';
 1160+ $sql = "INSERT INTO $table ( "
 1161+ . $this->makeList( array_keys( $row ), LIST_NAMES )
 1162+ .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA ) . ' )';
12701163 $this->query( $sql, $fname );
12711164 }
12721165 }
@@ -1315,7 +1208,7 @@
13161209 $res = $res->result;
13171210 }
13181211 if ( !@db2_free_result( $res ) ) {
1319 - throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
 1212+ throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
13201213 }
13211214 }
13221215
@@ -1350,40 +1243,52 @@
13511244 * @param $table Array or string, table name(s) (prefix auto-added)
13521245 * @param $vars Array or string, field name(s) to be retrieved
13531246 * @param $conds Array or string, condition(s) for WHERE
1354 - * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1355 - * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1356 - * see Database::makeSelectOptions code for list of supported stuff
 1247+ * @param $fname String: calling function name (use __METHOD__)
 1248+ * for logs/profiling
 1249+ * @param $options Associative array of options
 1250+ * (e.g. array('GROUP BY' => 'page_title')),
 1251+ * see Database::makeSelectOptions code for list of
 1252+ * supported stuff
13571253 * @param $join_conds Associative array of table join conditions (optional)
1358 - * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1359 - * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
 1254+ * (e.g. array( 'page' => array('LEFT JOIN',
 1255+ * 'page_latest=rev_id') )
 1256+ * @return Mixed: database result resource for fetch functions or false
 1257+ * on failure
13601258 */
13611259 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
13621260 {
1363 - $res = parent::select( $table, $vars, $conds, $fname, $options, $join_conds );
 1261+ $res = parent::select( $table, $vars, $conds, $fname, $options,
 1262+ $join_conds );
13641263
13651264 // We must adjust for offset
13661265 if ( isset( $options['LIMIT'] ) ) {
1367 - if ( isset ($options['OFFSET'] ) ) {
 1266+ if ( isset ( $options['OFFSET'] ) ) {
13681267 $limit = $options['LIMIT'];
13691268 $offset = $options['OFFSET'];
13701269 }
13711270 }
13721271
13731272
1374 - // DB2 does not have a proper num_rows() function yet, so we must emulate it
1375 - // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1376 - // Yay!
 1273+ // DB2 does not have a proper num_rows() function yet, so we must emulate
 1274+ // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
 1275+ // a working one
 1276+ // TODO: Yay!
13771277
13781278 // we want the count
1379 - $vars2 = array('count(*) as num_rows');
 1279+ $vars2 = array( 'count( * ) as num_rows' );
13801280 // respecting just the limit option
13811281 $options2 = array();
1382 - if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
 1282+ if ( isset( $options['LIMIT'] ) ) {
 1283+ $options2['LIMIT'] = $options['LIMIT'];
 1284+ }
13831285 // but don't try to emulate for GROUP BY
1384 - if ( isset( $options['GROUP BY'] ) ) return $res;
 1286+ if ( isset( $options['GROUP BY'] ) ) {
 1287+ return $res;
 1288+ }
13851289
1386 - $res2 = parent::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1387 - $obj = $this->fetchObject($res2);
 1290+ $res2 = parent::select( $table, $vars2, $conds, $fname, $options2,
 1291+ $join_conds );
 1292+ $obj = $this->fetchObject( $res2 );
13881293 $this->mNumRows = $obj->num_rows;
13891294
13901295
@@ -1411,11 +1316,21 @@
14121317 }
14131318 }
14141319
1415 - if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1416 - if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1417 - if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
 1320+ if ( isset( $options['GROUP BY'] ) ) {
 1321+ $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
 1322+ }
 1323+ if ( isset( $options['HAVING'] ) ) {
 1324+ $preLimitTail .= " HAVING {$options['HAVING']}";
 1325+ }
 1326+ if ( isset( $options['ORDER BY'] ) ) {
 1327+ $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
 1328+ }
14181329
1419 - if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
 1330+ if ( isset( $noKeyOptions['DISTINCT'] )
 1331+ || isset( $noKeyOptions['DISTINCTROW'] ) )
 1332+ {
 1333+ $startOpts .= 'DISTINCT';
 1334+ }
14201335
14211336 return array( $startOpts, '', $preLimitTail, $postLimitTail );
14221337 }
@@ -1425,7 +1340,7 @@
14261341 * @return string wikitext of a link to the server software's web site
14271342 */
14281343 public static function getSoftwareLink() {
1429 - return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
 1344+ return "[http://www.ibm.com/db2/express/ IBM DB2]";
14301345 }
14311346
14321347 /**
@@ -1445,11 +1360,12 @@
14461361 public function wasDeadlock() {
14471362 // get SQLSTATE
14481363 $err = $this->lastErrno();
1449 - switch($err) {
 1364+ switch( $err ) {
 1365+ // This is literal port of the MySQL logic and may be wrong for DB2
14501366 case '40001': // sql0911n, Deadlock or timeout, rollback
14511367 case '57011': // sql0904n, Resource unavailable, no rollback
14521368 case '57033': // sql0913n, Deadlock or timeout, no rollback
1453 - $this->installPrint("In a deadlock because of SQLSTATE $err");
 1369+ $this->installPrint( "In a deadlock because of SQLSTATE $err" );
14541370 return true;
14551371 }
14561372 return false;
@@ -1464,7 +1380,8 @@
14651381 // db2_ping() doesn't exist
14661382 // Emulate
14671383 $this->close();
1468 - $this->mConn = $this->openUncataloged($this->mDBName, $this->mUser, $this->mPassword, $this->mServer, $this->mPort);
 1384+ $this->mConn = $this->openUncataloged( $this->mDBName, $this->mUser,
 1385+ $this->mPassword, $this->mServer, $this->mPort );
14691386
14701387 return false;
14711388 }
@@ -1475,18 +1392,27 @@
14761393 * Not implemented
14771394 * @return string ''
14781395 */
1479 - public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
 1396+ public function getStatus( $which="%" ) {
 1397+ $this->installPrint( 'Not implemented for DB2: getStatus()' );
 1398+ return '';
 1399+ }
14801400 /**
14811401 * Not implemented
14821402 * @return string $sql
14831403 */
1484 - public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
 1404+ public function limitResultForUpdate( $sql, $num ) {
 1405+ $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
 1406+ return $sql;
 1407+ }
14851408
14861409 /**
14871410 * Only useful with fake prepare like in base Database class
14881411 * @return string
14891412 */
1490 - public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
 1413+ public function fillPreparedArg( $matches ) {
 1414+ $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
 1415+ return '';
 1416+ }
14911417
14921418 ######################################
14931419 # Reflection
@@ -1500,19 +1426,24 @@
15011427 * @param $fname String: function name for logging and profiling
15021428 * @return Object query row in object form
15031429 */
1504 - public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
 1430+ public function indexInfo( $table, $index,
 1431+ $fname = 'DatabaseIbm_db2::indexExists' )
 1432+ {
15051433 $table = $this->tableName( $table );
15061434 $sql = <<<SQL
15071435 SELECT name as indexname
15081436 FROM sysibm.sysindexes si
1509 -WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
 1437+WHERE si.name='$index' AND si.tbname='$table'
 1438+AND sc.tbcreator='$this->mSchema'
15101439 SQL;
15111440 $res = $this->query( $sql, $fname );
15121441 if ( !$res ) {
15131442 return null;
15141443 }
15151444 $row = $this->fetchObject( $res );
1516 - if ($row != null) return $row;
 1445+ if ( $row != null ) {
 1446+ return $row;
 1447+ }
15171448 else return false;
15181449 }
15191450
@@ -1523,7 +1454,7 @@
15241455 * @return IBM_DB2Field
15251456 */
15261457 public function fieldInfo( $table, $field ) {
1527 - return IBM_DB2Field::fromText($this, $table, $field);
 1458+ return IBM_DB2Field::fromText( $this, $table, $field );
15281459 }
15291460
15301461 /**
@@ -1546,19 +1477,22 @@
15471478 * @param $fname function name for profiling
15481479 * @return Bool
15491480 */
1550 - public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
 1481+ public function indexUnique ( $table, $index,
 1482+ $fname = 'Database::indexUnique' )
 1483+ {
15511484 $table = $this->tableName( $table );
15521485 $sql = <<<SQL
15531486 SELECT si.name as indexname
15541487 FROM sysibm.sysindexes si
1555 -WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1556 -AND si.uniquerule IN ('U', 'P')
 1488+WHERE si.name='$index' AND si.tbname='$table'
 1489+AND sc.tbcreator='$this->mSchema'
 1490+AND si.uniquerule IN ( 'U', 'P' )
15571491 SQL;
15581492 $res = $this->query( $sql, $fname );
15591493 if ( !$res ) {
15601494 return null;
15611495 }
1562 - if ($this->fetchObject( $res )) {
 1496+ if ( $this->fetchObject( $res ) ) {
15631497 return true;
15641498 }
15651499 return false;
@@ -1576,10 +1510,11 @@
15771511 $sql = <<<SQL
15781512 SELECT length as size
15791513 FROM sysibm.syscolumns sc
1580 -WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
 1514+WHERE sc.name='$field' AND sc.tbname='$table'
 1515+AND sc.tbcreator='$this->mSchema'
15811516 SQL;
1582 - $res = $this->query($sql);
1583 - $row = $this->fetchObject($res);
 1517+ $res = $this->query( $sql );
 1518+ $row = $this->fetchObject( $res );
15841519 $size = $row->size;
15851520 return $size;
15861521 }
@@ -1593,18 +1528,26 @@
15941529 * @param $conds Array: conditionals for join table
15951530 * @param $fname String: function name for profiling
15961531 */
1597 - public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
 1532+ public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
 1533+ $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
 1534+ {
15981535 if ( !$conds ) {
1599 - throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
 1536+ throw new DBUnexpectedError( $this,
 1537+ 'Database::deleteJoin() called with empty $conds' );
16001538 }
16011539
16021540 $delTable = $this->tableName( $delTable );
16031541 $joinTable = $this->tableName( $joinTable );
1604 - $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
 1542+ $sql = <<<SQL
 1543+DELETE FROM $delTable
 1544+WHERE $delVar IN (
 1545+ SELECT $joinVar FROM $joinTable
 1546+
 1547+SQL;
16051548 if ( $conds != '*' ) {
16061549 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
16071550 }
1608 - $sql .= ')';
 1551+ $sql .= ' )';
16091552
16101553 $this->query( $sql, $fname );
16111554 }
@@ -1614,8 +1557,8 @@
16151558 * @param $b Mixed: data to be encoded
16161559 * @return IBM_DB2Blob
16171560 */
1618 - public function encodeBlob($b) {
1619 - return new IBM_DB2Blob($b);
 1561+ public function encodeBlob( $b ) {
 1562+ return new IBM_DB2Blob( $b );
16201563 }
16211564
16221565 /**
@@ -1623,13 +1566,14 @@
16241567 * @param $b IBM_DB2Blob: data to be decoded
16251568 * @return mixed
16261569 */
1627 - public function decodeBlob($b) {
 1570+ public function decodeBlob( $b ) {
16281571 return "$b";
16291572 }
16301573
16311574 /**
16321575 * Convert into a list of string being concatenated
1633 - * @param $stringList Array: strings that need to be joined together by the SQL engine
 1576+ * @param $stringList Array: strings that need to be joined together
 1577+ * by the SQL engine
16341578 * @return String: joined by the concatenation operator
16351579 */
16361580 public function buildConcat( $stringList ) {
@@ -1665,7 +1609,7 @@
16661610 * @return resource a prepared DB2 SQL statement
16671611 */
16681612 public function prepare( $sql, $func = 'DB2::prepare' ) {
1669 - $stmt = db2_prepare($this->mConn, $sql, $this->mStmtOptions);
 1613+ $stmt = db2_prepare( $this->mConn, $sql, $this->mStmtOptions );
16701614 return $stmt;
16711615 }
16721616
@@ -1674,7 +1618,7 @@
16751619 * @return Boolean success or failure
16761620 */
16771621 public function freePrepared( $prepared ) {
1678 - return db2_free_stmt($prepared);
 1622+ return db2_free_stmt( $prepared );
16791623 }
16801624
16811625 /**
@@ -1689,9 +1633,9 @@
16901634 $args = func_get_args();
16911635 array_shift( $args );
16921636 }
1693 - $res = db2_execute($prepared, $args);
 1637+ $res = db2_execute( $prepared, $args );
16941638 if ( !$res ) {
1695 - $this->installPrint(db2_stmt_errormsg());
 1639+ $this->installPrint( db2_stmt_errormsg() );
16961640 }
16971641 return $res;
16981642 }
@@ -1726,8 +1670,8 @@
17271671 reset( $args );
17281672 $this->preparedArgs =& $args;
17291673
1730 - foreach ($args as $i => $arg) {
1731 - db2_bind_param($preparedQuery, $i+1, $args[$i]);
 1674+ foreach ( $args as $i => $arg ) {
 1675+ db2_bind_param( $preparedQuery, $i+1, $args[$i] );
17321676 }
17331677
17341678 return $preparedQuery;
@@ -1736,7 +1680,7 @@
17371681 /**
17381682 * Switches module between regular and install modes
17391683 */
1740 - public function setMode($mode) {
 1684+ public function setMode( $mode ) {
17411685 $old = $this->mMode;
17421686 $this->mMode = $mode;
17431687 return $old;
@@ -1748,9 +1692,9 @@
17491693 * @param $field String
17501694 * @return String
17511695 */
1752 - function bitNot($field) {
 1696+ function bitNot( $field ) {
17531697 //expecting bit-fields smaller than 4bytes
1754 - return 'BITNOT('.$field.')';
 1698+ return "BITNOT( $field )";
17551699 }
17561700
17571701 /**
@@ -1760,8 +1704,8 @@
17611705 * @param $fieldRight String
17621706 * @return String
17631707 */
1764 - function bitAnd($fieldLeft, $fieldRight) {
1765 - return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
 1708+ function bitAnd( $fieldLeft, $fieldRight ) {
 1709+ return "BITAND( $fieldLeft, $fieldRight )";
17661710 }
17671711
17681712 /**
@@ -1771,14 +1715,16 @@
17721716 * @param $fieldRight String
17731717 * @return String
17741718 */
1775 - function bitOr($fieldLeft, $fieldRight) {
1776 - return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
 1719+ function bitOr( $fieldLeft, $fieldRight ) {
 1720+ return "BITOR( $fieldLeft, $fieldRight )";
17771721 }
17781722 }
17791723
17801724 class IBM_DB2Helper {
1781 - public static function makeArray($maybeArray) {
1782 - if ( !is_array( $maybeArray ) ) $maybeArray = array( $maybeArray );
 1725+ public static function makeArray( $maybeArray ) {
 1726+ if ( !is_array( $maybeArray ) ) {
 1727+ return array( $maybeArray );
 1728+ }
17831729
17841730 return $maybeArray;
17851731 }

Past revisions this follows-up on

RevisionCommit summaryAuthorDate
r72134DB2: Implemented prepared statements for INSERT and UPDATE to allow more than...leonsp18:14, 1 September 2010

Status & tagging log