59b302477e4df34cb871770a8da2654dbd1d3d95
3 * This script is the IBM DB2 database abstraction layer
5 * See maintenance/ibm_db2/README for development notes and other specific information
8 * @author leo.petr+mediawiki@gmail.com
12 * Utility class for generating blank objects
13 * Intended as an equivalent to {} in Javascript
20 * This represents a column in a DB2 database
24 private $name, $tablename, $type, $nullable, $max_length;
27 * Builder method for the class
28 * @param Object $db Database interface
29 * @param string $table table name
30 * @param string $field column name
31 * @return IBM_DB2Field
33 static function fromText($db, $table, $field) {
38 lcase(coltype) AS typname,
39 nulls AS attnotnull, length AS attlen
40 FROM sysibm.syscolumns
41 WHERE tbcreator=%s AND tbname=%s AND name=%s;
43 $res = $db->query(sprintf($q,
44 $db->addQuotes($wgDBmwschema),
45 $db->addQuotes($table),
46 $db->addQuotes($field)));
47 $row = $db->fetchObject($res);
50 $n = new IBM_DB2Field
;
51 $n->type
= $row->typname
;
52 $n->nullable
= ($row->attnotnull
== 'N');
54 $n->tablename
= $table;
55 $n->max_length
= $row->attlen
;
60 * @return string column name
62 function name() { return $this->name
; }
65 * @return string table name
67 function tableName() { return $this->tablename
; }
70 * @return string column type
72 function type() { return $this->type
; }
75 * @return bool true or false
77 function nullable() { return $this->nullable
; }
79 * How much can you fit in the column per row?
82 function maxLength() { return $this->max_length
; }
86 * Wrapper around binary large objects
92 function __construct($data) {
102 * Primary database interface
105 class DatabaseIbm_db2
extends DatabaseBase
{
108 protected $mLastQuery = '';
109 protected $mPHPError = false;
111 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
112 protected $mOut, $mOpened = false;
114 protected $mFailFunction;
115 protected $mTablePrefix;
117 protected $mTrxLevel = 0;
118 protected $mErrorCount = 0;
119 protected $mLBInfo = array();
120 protected $mFakeSlaveLag = null, $mFakeMaster = false;
124 /// Server port for uncataloged connections
125 protected $mPort = NULL;
126 /// Whether connection is cataloged
127 protected $mCataloged = NULL;
128 /// Schema for tables, stored procedures, triggers
129 protected $mSchema = NULL;
130 /// Whether the schema has been applied in this session
131 protected $mSchemaSet = false;
132 /// Result of last query
133 protected $mLastResult = NULL;
134 /// Number of rows affected by last INSERT/UPDATE/DELETE
135 protected $mAffectedRows = NULL;
136 /// Number of rows returned by last SELECT
137 protected $mNumRows = NULL;
140 const CATALOGED
= "cataloged";
141 const UNCATALOGED
= "uncataloged";
142 const USE_GLOBAL
= "get from global";
144 /// Last sequence value used for a primary key
145 protected $mInsertId = NULL;
148 * These can be safely inherited
150 * Getter/Setter: (18)
170 * Administrative: (8)
172 * installErrorHandler
173 * restoreErrorHandler
174 * connectionErrorHandler
175 * reportConnectionError
189 * Prepared Statement: 6
206 * tableNamesWithUseIndexOrJOIN
222 * These need to be implemented TODO
224 * Administrative: 7 / 7
227 * openCataloged [Done]
229 * newFromParams [Done]
230 * openUncataloged [Done]
231 * setup_database [Done]
233 * Getter/Setter: 13 / 13
234 * cascadingDeletes [Done]
235 * cleanupTriggers [Done]
237 * realTimestamps [Done]
238 * impliciGroupby [Done]
239 * implicitOrderby [Done]
240 * searchableIPs [Done]
241 * functionalIndexes [Done]
244 * getServerVersion [Done]
245 * getSoftwareLink [Done]
246 * getSearchEngine [Done]
248 * Database driver wrapper: 23 / 23
261 * affectedRows [Done]
274 * Slave/master: 2 / 2
275 * setFakeSlaveLag [Done]
276 * setFakeMaster [Done]
284 * textFieldSize [Done]
286 * Generation: 16 / 16
290 * makeSelectOptions [Done]
291 * estimateRowCount [Done]
292 * nextSequenceValue [Done]
293 * useIndexClause [Done]
296 * lowPriorityOption [Done]
298 * limitResultForUpdate [Done]
305 ######################################
306 # Getters and Setters
307 ######################################
310 * Returns true if this database supports (and uses) cascading deletes
312 function cascadingDeletes() {
317 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
319 function cleanupTriggers() {
324 * Returns true if this database is strict about what can be put into an IP field.
325 * Specifically, it uses a NULL value instead of an empty string.
327 function strictIPs() {
332 * Returns true if this database uses timestamps rather than integers
334 function realTimestamps() {
339 * Returns true if this database does an implicit sort when doing GROUP BY
341 function implicitGroupby() {
346 * Returns true if this database does an implicit order by when the column has an index
347 * For example: SELECT page_title FROM page LIMIT 1
349 function implicitOrderby() {
354 * Returns true if this database can do a native search on IP columns
355 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
357 function searchableIPs() {
362 * Returns true if this database can use functional indexes
364 function functionalIndexes() {
369 * Returns a unique string representing the wiki on the server
371 function getWikiID() {
372 if( $this->mSchema
) {
373 return "{$this->mDBname}-{$this->mSchema}";
375 return $this->mDBname
;
380 ######################################
382 ######################################
387 * @param string $server hostname of database server
388 * @param string $user username
389 * @param string $password
390 * @param string $dbName database name on the server
391 * @param function $failFunction (optional)
392 * @param integer $flags database behaviour flags (optional, unused)
394 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
395 $dbName = false, $failFunction = false, $flags = 0,
396 $schema = self
::USE_GLOBAL
)
399 global $wgOut, $wgDBmwschema;
400 # Can't get a reference if it hasn't been set yet
401 if ( !isset( $wgOut ) ) {
404 $this->mOut
=& $wgOut;
405 $this->mFailFunction
= $failFunction;
406 $this->mFlags
= DBO_TRX |
$flags;
408 if ( $schema == self
::USE_GLOBAL
) {
409 $this->mSchema
= $wgDBmwschema;
412 $this->mSchema
= $schema;
415 $this->open( $server, $user, $password, $dbName);
419 * Opens a database connection and returns it
420 * Closes any existing connection
421 * @return a fresh connection
422 * @param string $server hostname
423 * @param string $user
424 * @param string $password
425 * @param string $dbName database name
427 public function open( $server, $user, $password, $dbName )
429 // Load the port number
430 global $wgDBport_db2, $wgDBcataloged;
431 wfProfileIn( __METHOD__
);
433 // Load IBM DB2 driver if missing
434 if (!@extension_loaded
('ibm_db2')) {
437 // Test for IBM DB2 support, to avoid suppressed fatal error
438 if ( !function_exists( 'db2_connect' ) ) {
439 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
441 $this->reportConnectionError($error);
444 if (!strlen($user)) { // Copied from Postgres
448 // Close existing connection
451 $this->mServer
= $server;
452 $this->mPort
= $port = $wgDBport_db2;
453 $this->mUser
= $user;
454 $this->mPassword
= $password;
455 $this->mDBname
= $dbName;
456 $this->mCataloged
= $cataloged = $wgDBcataloged;
458 if ( $cataloged == self
::CATALOGED
) {
459 $this->openCataloged($dbName, $user, $password);
461 elseif ( $cataloged == self
::UNCATALOGED
) {
462 $this->openUncataloged($dbName, $user, $password, $server, $port);
465 // Not all MediaWiki code is transactional
466 // Rather, turn it off in the begin function and turn on after a commit
467 // db2_autocommit($this->mConn, DB2_AUTOCOMMIT_OFF);
468 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
470 if ( $this->mConn
== false ) {
471 wfDebug( "DB connection error\n" );
472 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
473 wfDebug( $this->lastError()."\n" );
477 $this->mOpened
= true;
478 $this->applySchema();
480 wfProfileOut( __METHOD__
);
485 * Opens a cataloged database connection, sets mConn
487 protected function openCataloged( $dbName, $user, $password )
489 @$this->mConn
= db2_connect($dbName, $user, $password);
493 * Opens an uncataloged database connection, sets mConn
495 protected function openUncataloged( $dbName, $user, $password, $server, $port )
497 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
498 $str .= "DATABASE=$dbName;";
499 $str .= "HOSTNAME=$server;";
500 if ($port) $str .= "PORT=$port;";
501 $str .= "PROTOCOL=TCPIP;";
502 $str .= "UID=$user;";
503 $str .= "PWD=$password;";
505 @$this->mConn
= db2_connect($str, $user, $password);
509 * Closes a database connection, if it is open
510 * Returns success, true if already closed
512 public function close() {
513 $this->mOpened
= false;
514 if ( $this->mConn
) {
515 if ($this->trxLevel() > 0) {
518 return db2_close( $this->mConn
);
526 * Returns a fresh instance of this class
529 * @param string $server hostname of database server
530 * @param string $user username
531 * @param string $password
532 * @param string $dbName database name on the server
533 * @param function $failFunction (optional)
534 * @param integer $flags database behaviour flags (optional, unused)
536 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
538 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
542 * Retrieves the most current database error
543 * Forces a database rollback
545 public function lastError() {
546 if ($this->lastError2()) {
553 private function lastError2() {
554 $connerr = db2_conn_errormsg();
555 if ($connerr) return $connerr;
556 $stmterr = db2_stmt_errormsg();
557 if ($stmterr) return $stmterr;
558 if ($this->mConn
) return "No open connection.";
559 if ($this->mOpened
) return "No open connection allegedly.";
565 * Get the last error number
566 * Return 0 if no error
569 public function lastErrno() {
570 $connerr = db2_conn_error();
571 if ($connerr) return $connerr;
572 $stmterr = db2_stmt_error();
573 if ($stmterr) return $stmterr;
578 * Is a database connection open?
581 public function isOpen() { return $this->mOpened
; }
584 * The DBMS-dependent part of query()
585 * @param $sql String: SQL query.
586 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
590 public function doQuery( $sql ) {
591 //print "<li><pre>$sql</pre></li>";
592 // Switch into the correct namespace
593 $this->applySchema();
595 $ret = db2_exec( $this->mConn
, $sql );
600 $error = db2_stmt_errormsg();
601 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
603 $this->mLastResult
= $ret;
604 $this->mAffectedRows
= NULL; // Not calculated until asked for
609 * @return string Version information from the database
611 public function getServerVersion() {
612 $info = db2_server_info( $this->mConn
);
613 return $info->DBMS_VER
;
617 * Queries whether a given table exists
620 public function tableExists( $table ) {
621 $schema = $this->mSchema
;
623 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
624 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
626 $res = $this->query( $sql );
627 if (!$res) return false;
629 // If the table exists, there should be one of it
630 @$row = $this->fetchRow($res);
632 if ($count == '1' or $count == 1) {
640 * Fetch the next row from the given result object, in object form.
641 * Fields can be retrieved with $row->fieldname, with fields acting like
644 * @param $res SQL result object as returned from Database::query(), etc.
645 * @return DB2 row object
646 * @throws DBUnexpectedError Thrown if the database returns an error
648 public function fetchObject( $res ) {
649 if ( $res instanceof ResultWrapper
) {
652 @$row = db2_fetch_object( $res );
653 if( $this->lastErrno() ) {
654 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
656 // Make field names lowercase for compatibility with MySQL
659 $row2 = new BlankObject();
660 foreach ($row as $key => $value)
662 $keyu = strtolower($key);
663 $row2->$keyu = $value;
671 * Fetch the next row from the given result object, in associative array
672 * form. Fields are retrieved with $row['fieldname'].
674 * @param $res SQL result object as returned from Database::query(), etc.
675 * @return DB2 row object
676 * @throws DBUnexpectedError Thrown if the database returns an error
678 public function fetchRow( $res ) {
679 if ( $res instanceof ResultWrapper
) {
682 @$row = db2_fetch_array( $res );
683 if ( $this->lastErrno() ) {
684 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
690 * Override if introduced to base Database class
692 public function initial_setup() {
697 * Create tables, stored procedures, and so on
699 public function setup_database() {
700 // Timeout was being changed earlier due to mysterious crashes
701 // Changing it now may cause more problems than not changing it
702 //set_time_limit(240);
704 // TODO: switch to root login if available
706 // Switch into the correct namespace
707 $this->applySchema();
710 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
713 // TODO: update mediawiki_version table
715 // TODO: populate interwiki links
719 catch (MWException
$mwe)
721 print "<br><pre>$mwe</pre><br>";
727 * Doesn't escape numbers
728 * @param string s string to escape
729 * @return escaped string
731 public function addQuotes( $s ) {
732 //wfDebug("DB2::addQuotes($s)\n");
733 if ( is_null( $s ) ) {
735 } else if ($s instanceof Blob
) {
736 return "'".$s->fetch($s)."'";
738 $s = $this->strencode($s);
739 if ( is_numeric($s) ) {
749 * Only escapes numbers going into non-numeric fields
750 * @param string s string to escape
751 * @return escaped string
753 public function addQuotesSmart( $table, $field, $s ) {
754 if ( is_null( $s ) ) {
756 } else if ($s instanceof Blob
) {
757 return "'".$s->fetch($s)."'";
759 $s = $this->strencode($s);
760 if ( is_numeric($s) ) {
761 // Check with the database if the column is actually numeric
762 // This allows for numbers in titles, etc
763 $res = $this->doQuery("SELECT $field FROM $table FETCH FIRST 1 ROWS ONLY");
764 $type = db2_field_type($res, strtoupper($field));
765 if ( $this->is_numeric_type( $type ) ) {
766 //wfDebug("DB2: Numeric value going in a numeric column: $s in $type $field in $table\n");
770 wfDebug("DB2: Numeric in non-numeric: '$s' in $type $field in $table\n");
780 * Verifies that a DB2 column/field type is numeric
781 * @return bool true if numeric
782 * @param string $type DB2 column type
784 public function is_numeric_type( $type ) {
785 switch (strtoupper($type)) {
800 * Alias for addQuotes()
801 * @param string s string to escape
802 * @return escaped string
804 public function strencode( $s ) {
805 // Bloody useless function
806 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
807 // But also necessary
808 $s = db2_escape_string($s);
809 // Wide characters are evil -- some of them look like '
810 $s = utf8_encode($s);
812 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
813 $to = array("\\", "''", "\n", "\t", '"', "\r");
814 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
819 * Switch into the database schema
821 protected function applySchema() {
822 if ( !($this->mSchemaSet
) ) {
823 $this->mSchemaSet
= true;
825 $this->doQuery("SET SCHEMA = $this->mSchema");
831 * Start a transaction (mandatory)
833 public function begin() {
834 // turn off auto-commit
835 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
836 $this->mTrxLevel
= 1;
841 * Must have a preceding begin()
843 public function commit() {
844 db2_commit($this->mConn
);
845 // turn auto-commit back on
846 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
847 $this->mTrxLevel
= 0;
851 * Cancel a transaction
853 public function rollback() {
854 db2_rollback($this->mConn
);
855 // turn auto-commit back on
856 // not sure if this is appropriate
857 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
858 $this->mTrxLevel
= 0;
862 * Makes an encoded list of strings from an array
864 * LIST_COMMA - comma separated, no field names
865 * LIST_AND - ANDed WHERE clause (without the WHERE)
866 * LIST_OR - ORed WHERE clause (without the WHERE)
867 * LIST_SET - comma separated with field names, like a SET clause
868 * LIST_NAMES - comma separated field names
870 public function makeList( $a, $mode = LIST_COMMA
) {
871 wfDebug("DB2::makeList()\n");
872 if ( !is_array( $a ) ) {
873 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
878 foreach ( $a as $field => $value ) {
880 if ( $mode == LIST_AND
) {
882 } elseif($mode == LIST_OR
) {
890 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
892 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
894 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
895 if( count( $value ) == 0 ) {
896 throw new MWException( __METHOD__
.': empty input' );
897 } elseif( count( $value ) == 1 ) {
898 // Special-case single values, as IN isn't terribly efficient
899 // Don't necessarily assume the single key is 0; we don't
900 // enforce linear numeric ordering on other arrays here.
901 $value = array_values( $value );
902 $list .= $field." = ".$this->addQuotes( $value[0] );
904 $list .= $field." IN (".$this->makeList($value).") ";
906 } elseif( is_null($value) ) {
907 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
908 $list .= "$field IS ";
909 } elseif ( $mode == LIST_SET
) {
910 $list .= "$field = ";
914 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
915 $list .= "$field = ";
917 if ( $mode == LIST_NAMES
) {
920 // Leo: Can't insert quoted numbers into numeric columns
921 // (?) Might cause other problems. May have to check column type before insertion.
922 else if ( is_numeric($value) ) {
926 $list .= $this->addQuotes( $value );
934 * Makes an encoded list of strings from an array
935 * Quotes numeric values being inserted into non-numeric fields
937 * @param string $table name of the table
938 * @param array $a list of values
940 * LIST_COMMA - comma separated, no field names
941 * LIST_AND - ANDed WHERE clause (without the WHERE)
942 * LIST_OR - ORed WHERE clause (without the WHERE)
943 * LIST_SET - comma separated with field names, like a SET clause
944 * LIST_NAMES - comma separated field names
946 public function makeListSmart( $table, $a, $mode = LIST_COMMA
) {
947 if ( !is_array( $a ) ) {
948 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
953 foreach ( $a as $field => $value ) {
955 if ( $mode == LIST_AND
) {
957 } elseif($mode == LIST_OR
) {
965 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
967 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
969 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
970 if( count( $value ) == 0 ) {
971 throw new MWException( __METHOD__
.': empty input' );
972 } elseif( count( $value ) == 1 ) {
973 // Special-case single values, as IN isn't terribly efficient
974 // Don't necessarily assume the single key is 0; we don't
975 // enforce linear numeric ordering on other arrays here.
976 $value = array_values( $value );
977 $list .= $field." = ".$this->addQuotes( $value[0] );
979 $list .= $field." IN (".$this->makeList($value).") ";
981 } elseif( is_null($value) ) {
982 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
983 $list .= "$field IS ";
984 } elseif ( $mode == LIST_SET
) {
985 $list .= "$field = ";
989 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
990 $list .= "$field = ";
992 if ( $mode == LIST_NAMES
) {
996 $list .= $this->addQuotesSmart( $table, $field, $value );
1004 * Construct a LIMIT query with optional offset
1005 * This is used for query pages
1006 * $sql string SQL query we will append the limit too
1007 * $limit integer the SQL limit
1008 * $offset integer the SQL offset (default false)
1010 public function limitResult($sql, $limit, $offset=false) {
1011 if( !is_numeric($limit) ) {
1012 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1015 wfDebug("Offset parameter not supported in limitResult()\n");
1017 // TODO implement proper offset handling
1018 // idea: get all the rows between 0 and offset, advance cursor to offset
1019 return "$sql FETCH FIRST $limit ROWS ONLY ";
1023 * Handle reserved keyword replacement in table names
1025 * @param $name Object
1027 public function tableName( $name ) {
1028 # Replace reserved words with better ones
1033 return 'pagecontent';
1040 * Generates a timestamp in an insertable format
1041 * @return string timestamp value
1042 * @param timestamp $ts
1044 public function timestamp( $ts=0 ) {
1045 // TS_MW cannot be easily distinguished from an integer
1046 return wfTimestamp(TS_DB2
,$ts);
1050 * Return the next in a sequence, save the value for retrieval via insertId()
1051 * @param string seqName Name of a defined sequence in the database
1052 * @return next value in that sequence
1054 public function nextSequenceValue( $seqName ) {
1055 $safeseq = preg_replace( "/'/", "''", $seqName );
1056 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1057 $row = $this->fetchRow( $res );
1058 $this->mInsertId
= $row[0];
1059 $this->freeResult( $res );
1060 return $this->mInsertId
;
1064 * This must be called after nextSequenceVal
1065 * @return Last sequence value used as a primary key
1067 public function insertId() {
1068 return $this->mInsertId
;
1072 * INSERT wrapper, inserts an array into a table
1074 * $args may be a single associative array, or an array of these with numeric keys,
1075 * for multi-row insert
1077 * @param array $table String: Name of the table to insert to.
1078 * @param array $args Array: Items to insert into the table.
1079 * @param array $fname String: Name of the function, for profiling
1080 * @param mixed $options String or Array. Valid options: IGNORE
1082 * @return bool Success of insert operation. IGNORE always returns true.
1084 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1085 wfDebug("DB2::insert($table)\n");
1086 if ( !count( $args ) ) {
1090 $table = $this->tableName( $table );
1092 if ( !is_array( $options ) )
1093 $options = array( $options );
1095 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
1098 $args = array($args);
1100 $keys = array_keys( $args[0] );
1102 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1103 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1105 // Cache autocommit value at the start
1106 $oldautocommit = db2_autocommit($this->mConn
);
1108 // If we are not in a transaction, we need to be for savepoint trickery
1110 if (! $this->mTrxLevel
) {
1115 $olde = error_reporting( 0 );
1116 // For future use, we may want to track the number of actual inserts
1117 // Right now, insert (all writes) simply return true/false
1118 $numrowsinserted = 0;
1121 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1125 foreach ( $args as $row ) {
1131 $sql .= '(' . $this->makeListSmart( $table, $row ) . ')';
1133 $res = (bool)$this->query( $sql, $fname, $ignore );
1138 foreach ( $args as $row ) {
1139 $tempsql = $origsql;
1140 $tempsql .= '(' . $this->makeListSmart( $table, $row ) . ')';
1143 db2_exec($this->mConn
, "SAVEPOINT $ignore");
1146 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
1149 $bar = db2_stmt_error();
1150 if ($bar != false) {
1151 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore" );
1154 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore" );
1159 // If any of them fail, we fail overall for this function call
1160 // Note that this will be ignored if IGNORE is set
1169 // if autocommit used to be on, it's ok to commit everything
1170 else if ($oldautocommit)
1176 $olde = error_reporting( $olde );
1177 // Set the affected row count for the whole operation
1178 $this->mAffectedRows
= $numrowsinserted;
1180 // IGNORE always returns true
1188 * UPDATE wrapper, takes a condition array and a SET array
1190 * @param string $table The table to UPDATE
1191 * @param array $values An array of values to SET
1192 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1193 * @param string $fname The Class::Function calling this function
1195 * @param array $options An array of UPDATE options, can be one or
1196 * more of IGNORE, LOW_PRIORITY
1199 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1200 $table = $this->tableName( $table );
1201 $opts = $this->makeUpdateOptions( $options );
1202 $sql = "UPDATE $opts $table SET " . $this->makeListSmart( $table, $values, LIST_SET
);
1203 if ( $conds != '*' ) {
1204 $sql .= " WHERE " . $this->makeListSmart( $table, $conds, LIST_AND
);
1206 return $this->query( $sql, $fname );
1210 * DELETE query wrapper
1212 * Use $conds == "*" to delete all rows
1214 function delete( $table, $conds, $fname = 'Database::delete' ) {
1216 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1218 $table = $this->tableName( $table );
1219 $sql = "DELETE FROM $table";
1220 if ( $conds != '*' ) {
1221 $sql .= ' WHERE ' . $this->makeListSmart( $table, $conds, LIST_AND
);
1223 return $this->query( $sql, $fname );
1227 * Returns the number of rows affected by the last query or 0
1228 * @return int the number of rows affected by the last query
1230 public function affectedRows() {
1231 if ( !is_null( $this->mAffectedRows
) ) {
1232 // Forced result for simulated queries
1233 return $this->mAffectedRows
;
1235 if( empty( $this->mLastResult
) )
1237 return db2_num_rows( $this->mLastResult
);
1241 * Simulates REPLACE with a DELETE followed by INSERT
1242 * @param $table Object
1243 * @param array $uniqueIndexes array consisting of indexes and arrays of indexes
1244 * @param array $rows Rows to insert
1245 * @param string $fname Name of the function for profiling
1248 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1249 $table = $this->tableName( $table );
1251 if (count($rows)==0) {
1256 if ( !is_array( reset( $rows ) ) ) {
1257 $rows = array( $rows );
1260 foreach( $rows as $row ) {
1261 # Delete rows which collide
1262 if ( $uniqueIndexes ) {
1263 $sql = "DELETE FROM $table WHERE ";
1265 foreach ( $uniqueIndexes as $index ) {
1272 if ( is_array( $index ) ) {
1274 foreach ( $index as $col ) {
1280 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1283 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1287 $this->query( $sql, $fname );
1290 # Now insert the row
1291 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1292 $this->makeList( $row, LIST_COMMA
) . ')';
1293 $this->query( $sql, $fname );
1298 * Returns the number of rows in the result set
1299 * Has to be called right after the corresponding select query
1300 * @param Object $res result set
1301 * @return int number of rows
1303 public function numRows( $res ) {
1304 if ( $res instanceof ResultWrapper
) {
1305 $res = $res->result
;
1307 if ( $this->mNumRows
) {
1308 return $this->mNumRows
;
1316 * Moves the row pointer of the result set
1317 * @param Object $res result set
1318 * @param int $row row number
1319 * @return success or failure
1321 public function dataSeek( $res, $row ) {
1322 if ( $res instanceof ResultWrapper
) {
1323 $res = $res->result
;
1325 return db2_fetch_row( $res, $row );
1329 # Fix notices in Block.php
1333 * Frees memory associated with a statement resource
1334 * @param Object $res Statement resource to free
1335 * @return bool success or failure
1337 public function freeResult( $res ) {
1338 if ( $res instanceof ResultWrapper
) {
1339 $res = $res->result
;
1341 if ( !@db2_free_result
( $res ) ) {
1342 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1347 * Returns the number of columns in a resource
1348 * @param Object $res Statement resource
1349 * @return Number of fields/columns in resource
1351 public function numFields( $res ) {
1352 if ( $res instanceof ResultWrapper
) {
1353 $res = $res->result
;
1355 return db2_num_fields( $res );
1359 * Returns the nth column name
1360 * @param Object $res Statement resource
1361 * @param int $n Index of field or column
1362 * @return string name of nth column
1364 public function fieldName( $res, $n ) {
1365 if ( $res instanceof ResultWrapper
) {
1366 $res = $res->result
;
1368 return db2_field_name( $res, $n );
1374 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1375 * @param mixed $vars Array or string, field name(s) to be retrieved
1376 * @param mixed $conds Array or string, condition(s) for WHERE
1377 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1378 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1379 * see Database::makeSelectOptions code for list of supported stuff
1380 * @param array $join_conds Associative array of table join conditions (optional)
1381 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1382 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1384 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1386 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1388 // We must adjust for offset
1389 if ( isset( $options['LIMIT'] ) ) {
1390 if ( isset ($options['OFFSET'] ) ) {
1391 $limit = $options['LIMIT'];
1392 $offset = $options['OFFSET'];
1397 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1398 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1401 // we want the count
1402 $vars2 = array('count(*) as num_rows');
1403 // respecting just the limit option
1404 $options2 = array();
1405 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1406 // but don't try to emulate for GROUP BY
1407 if ( isset( $options['GROUP BY'] ) ) return $res;
1409 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1410 $obj = $this->fetchObject($res2);
1411 $this->mNumRows
= $obj->num_rows
;
1413 wfDebug("DatabaseIbm_db2::select: There are $this->mNumRows rows.\n");
1419 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1420 * Has limited support for per-column options (colnum => 'DISTINCT')
1424 * @param array $options an associative array of options to be turned into
1425 * an SQL query, valid keys are listed in the function.
1428 function makeSelectOptions( $options ) {
1429 $preLimitTail = $postLimitTail = '';
1432 $noKeyOptions = array();
1433 foreach ( $options as $key => $option ) {
1434 if ( is_numeric( $key ) ) {
1435 $noKeyOptions[$option] = true;
1439 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1440 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1441 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1443 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1445 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1449 * Returns link to IBM DB2 free download
1450 * @return string wikitext of a link to the server software's web site
1452 public function getSoftwareLink() {
1453 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1457 * @return String: Database type for use in messages
1459 function getDBtypeForMsg() {
1467 * Get search engine class. All subclasses of this
1468 * need to implement this if they wish to use searching.
1472 public function getSearchEngine() {
1473 return "SearchIBM_DB2";
1477 # Tuesday the 14th of October, 2008
1480 * Did the last database access fail because of deadlock?
1483 public function wasDeadlock() {
1485 $err = $this->lastErrno();
1487 case '40001': // sql0911n, Deadlock or timeout, rollback
1488 case '57011': // sql0904n, Resource unavailable, no rollback
1489 case '57033': // sql0913n, Deadlock or timeout, no rollback
1490 wfDebug("In a deadlock because of SQLSTATE $err");
1497 * Ping the server and try to reconnect if it there is no connection
1498 * The connection may be closed and reopened while this happens
1499 * @return bool whether the connection exists
1501 public function ping() {
1502 // db2_ping() doesn't exist
1505 if ($this->mCataloged
== NULL) {
1508 else if ($this->mCataloged
) {
1509 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1511 else if (!$this->mCataloged
) {
1512 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1516 ######################################
1517 # Unimplemented and not applicable
1518 ######################################
1524 public function getStatus( $which ) { wfDebug('Not implemented for DB2: getStatus()'); return ''; }
1534 public function setFakeSlaveLag( $lag ) { wfDebug('Not implemented for DB2: setFakeSlaveLag()'); }
1539 public function setFakeMaster( $enabled ) { wfDebug('Not implemented for DB2: setFakeMaster()'); }
1542 * @return string $sql
1545 public function limitResultForUpdate($sql, $num) { return $sql; }
1547 ######################################
1549 ######################################
1552 * Query whether a given column exists in the mediawiki schema
1553 * @param string $table name of the table
1554 * @param string $field name of the column
1555 * @param string $fname function name for logging and profiling
1557 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1558 $table = $this->tableName( $table );
1559 $schema = $this->mSchema
;
1560 $etable = preg_replace("/'/", "''", $table);
1561 $eschema = preg_replace("/'/", "''", $schema);
1562 $ecol = preg_replace("/'/", "''", $field);
1564 SELECT 1 as fieldexists
1565 FROM sysibm.syscolumns sc
1566 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1568 $res = $this->query( $sql, $fname );
1569 $count = $res ?
$this->numRows($res) : 0;
1571 $this->freeResult( $res );
1576 * Returns information about an index
1577 * If errors are explicitly ignored, returns NULL on failure
1578 * @param string $table table name
1579 * @param string $index index name
1581 * @return object query row in object form
1583 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1584 $table = $this->tableName( $table );
1586 SELECT name as indexname
1587 FROM sysibm.sysindexes si
1588 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1590 $res = $this->query( $sql, $fname );
1594 $row = $this->fetchObject( $res );
1595 if ($row != NULL) return $row;
1600 * Returns an information object on a table column
1601 * @param string $table table name
1602 * @param string $field column name
1603 * @return IBM_DB2Field
1605 public function fieldInfo( $table, $field ) {
1606 return IBM_DB2Field
::fromText($this, $table, $field);
1610 * db2_field_type() wrapper
1611 * @param Object $res Result of executed statement
1612 * @param mixed $index number or name of the column
1613 * @return string column type
1615 public function fieldType( $res, $index ) {
1616 if ( $res instanceof ResultWrapper
) {
1617 $res = $res->result
;
1619 return db2_field_type( $res, $index );
1623 * Verifies that an index was created as unique
1624 * @param string $table table name
1625 * @param string $index index name
1626 * @param string $fnam function name for profiling
1629 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1630 $table = $this->tableName( $table );
1632 SELECT si.name as indexname
1633 FROM sysibm.sysindexes si
1634 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1635 AND si.uniquerule IN ('U', 'P')
1637 $res = $this->query( $sql, $fname );
1641 if ($this->fetchObject( $res )) {
1649 * Returns the size of a text field, or -1 for "unlimited"
1650 * @param string $table table name
1651 * @param string $field column name
1652 * @return int length or -1 for unlimited
1654 public function textFieldSize( $table, $field ) {
1655 $table = $this->tableName( $table );
1657 SELECT length as size
1658 FROM sysibm.syscolumns sc
1659 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1661 $res = $this->query($sql);
1662 $row = $this->fetchObject($res);
1664 $this->freeResult( $res );
1669 * DELETE where the condition is a join
1670 * @param string $delTable deleting from this table
1671 * @param string $joinTable using data from this table
1672 * @param string $delVar variable in deleteable table
1673 * @param string $joinVar variable in data table
1674 * @param array $conds conditionals for join table
1675 * @param string $fname function name for profiling
1677 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1679 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1682 $delTable = $this->tableName( $delTable );
1683 $joinTable = $this->tableName( $joinTable );
1684 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1685 if ( $conds != '*' ) {
1686 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1690 $this->query( $sql, $fname );
1694 * Estimate rows in dataset
1695 * Returns estimated count, based on COUNT(*) output
1696 * Takes same arguments as Database::select()
1697 * @param string $table table name
1698 * @param array $vars unused
1699 * @param array $conds filters on the table
1700 * @param string $fname function name for profiling
1701 * @param array $options options for select
1702 * @return int row count
1704 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1706 $res = $this->select ($table, 'COUNT(*) as mwrowcount', $conds, $fname, $options );
1708 $row = $this->fetchRow($res);
1709 $rows = (isset($row['mwrowcount'])) ?
$row['mwrowcount'] : 0;
1711 $this->freeResult($res);
1716 * Description is left as an exercise for the reader
1717 * @param mixed $b data to be encoded
1718 * @return IBM_DB2Blob
1720 public function encodeBlob($b) {
1721 return new IBM_DB2Blob($b);
1725 * Description is left as an exercise for the reader
1726 * @param IBM_DB2Blob $b data to be decoded
1729 public function decodeBlob($b) {
1730 return $b->getData();
1734 * Convert into a list of string being concatenated
1735 * @param array $stringList strings that need to be joined together by the SQL engine
1736 * @return string joined by the concatenation operator
1738 public function buildConcat( $stringList ) {
1739 // || is equivalent to CONCAT
1740 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1741 return implode( ' || ', $stringList );
1745 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1746 * @param string $column name of timestamp column
1747 * @return string SQL code
1749 public function extractUnixEpoch( $column ) {
1751 // see SpecialAncientpages