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
21 * This represents a column in a DB2 database
26 private $tablename = '';
28 private $nullable = false;
29 private $max_length = 0;
32 * Builder method for the class
33 * @param DatabaseIbm_db2 $db Database interface
34 * @param string $table table name
35 * @param string $field column name
36 * @return IBM_DB2Field
38 static function fromText($db, $table, $field) {
43 lcase(coltype) AS typname,
44 nulls AS attnotnull, length AS attlen
45 FROM sysibm.syscolumns
46 WHERE tbcreator=%s AND tbname=%s AND name=%s;
48 $res = $db->query(sprintf($q,
49 $db->addQuotes($wgDBmwschema),
50 $db->addQuotes($table),
51 $db->addQuotes($field)));
52 $row = $db->fetchObject($res);
55 $n = new IBM_DB2Field
;
56 $n->type
= $row->typname
;
57 $n->nullable
= ($row->attnotnull
== 'N');
59 $n->tablename
= $table;
60 $n->max_length
= $row->attlen
;
65 * @return string column name
67 function name() { return $this->name
; }
70 * @return string table name
72 function tableName() { return $this->tablename
; }
75 * @return string column type
77 function type() { return $this->type
; }
80 * @return bool true or false
82 function nullable() { return $this->nullable
; }
84 * How much can you fit in the column per row?
87 function maxLength() { return $this->max_length
; }
91 * Wrapper around binary large objects
97 function __construct($data) {
107 * Primary database interface
110 class DatabaseIbm_db2
extends DatabaseBase
{
113 protected $mLastQuery = '';
114 protected $mPHPError = false;
116 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
117 protected $mOut, $mOpened = false;
119 protected $mFailFunction;
120 protected $mTablePrefix;
122 protected $mTrxLevel = 0;
123 protected $mErrorCount = 0;
124 protected $mLBInfo = array();
125 protected $mFakeSlaveLag = null, $mFakeMaster = false;
129 /// Server port for uncataloged connections
130 protected $mPort = NULL;
131 /// Whether connection is cataloged
132 protected $mCataloged = NULL;
133 /// Schema for tables, stored procedures, triggers
134 protected $mSchema = NULL;
135 /// Whether the schema has been applied in this session
136 protected $mSchemaSet = false;
137 /// Result of last query
138 protected $mLastResult = NULL;
139 /// Number of rows affected by last INSERT/UPDATE/DELETE
140 protected $mAffectedRows = NULL;
141 /// Number of rows returned by last SELECT
142 protected $mNumRows = NULL;
144 /// Connection config options - see constructor
145 public $mConnOptions = array();
146 /// Statement config options -- see constructor
147 public $mStmtOptions = array();
150 const CATALOGED
= "cataloged";
151 const UNCATALOGED
= "uncataloged";
152 const USE_GLOBAL
= "get from global";
154 const NONE_OPTION
= 0x00;
155 const CONN_OPTION
= 0x01;
156 const STMT_OPTION
= 0x02;
158 const REGULAR_MODE
= 'regular';
159 const INSTALL_MODE
= 'install';
161 // Whether this is regular operation or the initial installation
162 protected $mMode = self
::REGULAR_MODE
;
164 /// Last sequence value used for a primary key
165 protected $mInsertId = NULL;
168 * These can be safely inherited
170 * Getter/Setter: (18)
190 * Administrative: (8)
192 * installErrorHandler
193 * restoreErrorHandler
194 * connectionErrorHandler
195 * reportConnectionError
209 * Prepared Statement: 6
226 * tableNamesWithUseIndexOrJOIN
242 * These have been implemented
244 * Administrative: 7 / 7
247 * openCataloged [Done]
249 * newFromParams [Done]
250 * openUncataloged [Done]
251 * setup_database [Done]
253 * Getter/Setter: 13 / 13
254 * cascadingDeletes [Done]
255 * cleanupTriggers [Done]
257 * realTimestamps [Done]
258 * impliciGroupby [Done]
259 * implicitOrderby [Done]
260 * searchableIPs [Done]
261 * functionalIndexes [Done]
264 * getServerVersion [Done]
265 * getSoftwareLink [Done]
266 * getSearchEngine [Done]
268 * Database driver wrapper: 23 / 23
281 * affectedRows [Done]
294 * Slave/master: 2 / 2
295 * setFakeSlaveLag [Done]
296 * setFakeMaster [Done]
304 * textFieldSize [Done]
306 * Generation: 16 / 16
310 * makeSelectOptions [Done]
311 * estimateRowCount [Done]
312 * nextSequenceValue [Done]
313 * useIndexClause [Done]
316 * lowPriorityOption [Done]
318 * limitResultForUpdate [Done]
325 ######################################
326 # Getters and Setters
327 ######################################
330 * Returns true if this database supports (and uses) cascading deletes
332 function cascadingDeletes() {
337 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
339 function cleanupTriggers() {
344 * Returns true if this database is strict about what can be put into an IP field.
345 * Specifically, it uses a NULL value instead of an empty string.
347 function strictIPs() {
352 * Returns true if this database uses timestamps rather than integers
354 function realTimestamps() {
359 * Returns true if this database does an implicit sort when doing GROUP BY
361 function implicitGroupby() {
366 * Returns true if this database does an implicit order by when the column has an index
367 * For example: SELECT page_title FROM page LIMIT 1
369 function implicitOrderby() {
374 * Returns true if this database can do a native search on IP columns
375 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
377 function searchableIPs() {
382 * Returns true if this database can use functional indexes
384 function functionalIndexes() {
389 * Returns a unique string representing the wiki on the server
391 function getWikiID() {
392 if( $this->mSchema
) {
393 return "{$this->mDBname}-{$this->mSchema}";
395 return $this->mDBname
;
400 ######################################
402 ######################################
407 * @param string $server hostname of database server
408 * @param string $user username
409 * @param string $password
410 * @param string $dbName database name on the server
411 * @param function $failFunction (optional)
412 * @param integer $flags database behaviour flags (optional, unused)
414 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
415 $dbName = false, $failFunction = false, $flags = 0,
416 $schema = self
::USE_GLOBAL
)
419 global $wgOut, $wgDBmwschema;
420 # Can't get a reference if it hasn't been set yet
421 if ( !isset( $wgOut ) ) {
424 $this->mOut
=& $wgOut;
425 $this->mFailFunction
= $failFunction;
426 $this->mFlags
= DBO_TRX |
$flags;
428 if ( $schema == self
::USE_GLOBAL
) {
429 $this->mSchema
= $wgDBmwschema;
432 $this->mSchema
= $schema;
435 // configure the connection and statement objects
436 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
437 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
438 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
440 $this->open( $server, $user, $password, $dbName);
444 * Enables options only if the ibm_db2 extension version supports them
445 * @param string $name Name of the option in the options array
446 * @param string $const Name of the constant holding the right option value
447 * @param int $type Whether this is a Connection or Statement otion
449 private function setDB2Option($name, $const, $type) {
450 if (defined($const)) {
451 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
452 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
455 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
460 * Outputs debug information in the appropriate place
461 * @param string $string The relevant debug message
463 private function installPrint($string) {
465 if ($this->mMode
== self
::INSTALL_MODE
) {
466 print "<li>$string</li>";
472 * Opens a database connection and returns it
473 * Closes any existing connection
474 * @return a fresh connection
475 * @param string $server hostname
476 * @param string $user
477 * @param string $password
478 * @param string $dbName database name
480 public function open( $server, $user, $password, $dbName )
482 // Load the port number
483 global $wgDBport_db2, $wgDBcataloged;
484 wfProfileIn( __METHOD__
);
486 // Load IBM DB2 driver if missing
487 if (!@extension_loaded
('ibm_db2')) {
490 // Test for IBM DB2 support, to avoid suppressed fatal error
491 if ( !function_exists( 'db2_connect' ) ) {
492 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
493 $this->installPrint($error);
494 $this->reportConnectionError($error);
497 if (!strlen($user)) { // Copied from Postgres
501 // Close existing connection
504 $this->mServer
= $server;
505 $this->mPort
= $port = $wgDBport_db2;
506 $this->mUser
= $user;
507 $this->mPassword
= $password;
508 $this->mDBname
= $dbName;
509 $this->mCataloged
= $cataloged = $wgDBcataloged;
511 if ( $cataloged == self
::CATALOGED
) {
512 $this->openCataloged($dbName, $user, $password);
514 elseif ( $cataloged == self
::UNCATALOGED
) {
515 $this->openUncataloged($dbName, $user, $password, $server, $port);
517 // Apply connection config
518 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
519 // Not all MediaWiki code is transactional
520 // Rather, turn autocommit off in the begin function and turn on after a commit
521 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
523 if ( $this->mConn
== false ) {
524 $this->installPrint( "DB connection error\n" );
525 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
526 $this->installPrint( $this->lastError()."\n" );
530 $this->mOpened
= true;
531 $this->applySchema();
533 wfProfileOut( __METHOD__
);
538 * Opens a cataloged database connection, sets mConn
540 protected function openCataloged( $dbName, $user, $password )
542 @$this->mConn
= db2_connect($dbName, $user, $password);
546 * Opens an uncataloged database connection, sets mConn
548 protected function openUncataloged( $dbName, $user, $password, $server, $port )
550 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
551 $str .= "DATABASE=$dbName;";
552 $str .= "HOSTNAME=$server;";
553 if ($port) $str .= "PORT=$port;";
554 $str .= "PROTOCOL=TCPIP;";
555 $str .= "UID=$user;";
556 $str .= "PWD=$password;";
558 @$this->mConn
= db2_connect($str, $user, $password);
562 * Closes a database connection, if it is open
563 * Returns success, true if already closed
565 public function close() {
566 $this->mOpened
= false;
567 if ( $this->mConn
) {
568 if ($this->trxLevel() > 0) {
571 return db2_close( $this->mConn
);
579 * Returns a fresh instance of this class
582 * @param string $server hostname of database server
583 * @param string $user username
584 * @param string $password
585 * @param string $dbName database name on the server
586 * @param function $failFunction (optional)
587 * @param integer $flags database behaviour flags (optional, unused)
589 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
591 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
595 * Retrieves the most current database error
596 * Forces a database rollback
598 public function lastError() {
599 $connerr = db2_conn_errormsg();
604 $stmterr = db2_stmt_errormsg();
614 * Get the last error number
615 * Return 0 if no error
618 public function lastErrno() {
619 $connerr = db2_conn_error();
620 if ($connerr) return $connerr;
621 $stmterr = db2_stmt_error();
622 if ($stmterr) return $stmterr;
627 * Is a database connection open?
630 public function isOpen() { return $this->mOpened
; }
633 * The DBMS-dependent part of query()
634 * @param $sql String: SQL query.
635 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
639 public function doQuery( $sql ) {
640 //print "<li><pre>$sql</pre></li>";
641 // Switch into the correct namespace
642 $this->applySchema();
644 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
649 $error = db2_stmt_errormsg();
650 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
652 $this->mLastResult
= $ret;
653 $this->mAffectedRows
= NULL; // Not calculated until asked for
658 * @return string Version information from the database
660 public function getServerVersion() {
661 $info = db2_server_info( $this->mConn
);
662 return $info->DBMS_VER
;
666 * Queries whether a given table exists
669 public function tableExists( $table ) {
670 $schema = $this->mSchema
;
672 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
673 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
675 $res = $this->query( $sql );
676 if (!$res) return false;
678 // If the table exists, there should be one of it
679 @$row = $this->fetchRow($res);
681 if ($count == '1' or $count == 1) {
689 * Fetch the next row from the given result object, in object form.
690 * Fields can be retrieved with $row->fieldname, with fields acting like
693 * @param $res SQL result object as returned from Database::query(), etc.
694 * @return DB2 row object
695 * @throws DBUnexpectedError Thrown if the database returns an error
697 public function fetchObject( $res ) {
698 if ( $res instanceof ResultWrapper
) {
701 @$row = db2_fetch_object( $res );
702 if( $this->lastErrno() ) {
703 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
705 // Make field names lowercase for compatibility with MySQL
708 $row2 = new BlankObject();
709 foreach ($row as $key => $value)
711 $keyu = strtolower($key);
712 $row2->$keyu = $value;
720 * Fetch the next row from the given result object, in associative array
721 * form. Fields are retrieved with $row['fieldname'].
723 * @param $res SQL result object as returned from Database::query(), etc.
724 * @return DB2 row object
725 * @throws DBUnexpectedError Thrown if the database returns an error
727 public function fetchRow( $res ) {
728 if ( $res instanceof ResultWrapper
) {
731 @$row = db2_fetch_array( $res );
732 if ( $this->lastErrno() ) {
733 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
739 * Override if introduced to base Database class
741 public function initial_setup() {
746 * Create tables, stored procedures, and so on
748 public function setup_database() {
749 // Timeout was being changed earlier due to mysterious crashes
750 // Changing it now may cause more problems than not changing it
751 //set_time_limit(240);
753 // TODO: switch to root login if available
755 // Switch into the correct namespace
756 $this->applySchema();
759 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
762 // TODO: update mediawiki_version table
764 // TODO: populate interwiki links
766 if ($this->lastError()) {
767 print "<li>Errors encountered during table creation -- rolled back</li>\n";
768 print "<li>Please install again</li>\n";
775 catch (MWException
$mwe)
777 print "<br><pre>$mwe</pre><br>";
783 * Doesn't escape numbers
784 * @param string s string to escape
785 * @return escaped string
787 public function addQuotes( $s ) {
788 //$this->installPrint("DB2::addQuotes($s)\n");
789 if ( is_null( $s ) ) {
791 } else if ($s instanceof Blob
) {
792 return "'".$s->fetch($s)."'";
794 $s = $this->strencode($s);
795 if ( is_numeric($s) ) {
804 * Verifies that a DB2 column/field type is numeric
805 * @return bool true if numeric
806 * @param string $type DB2 column type
808 public function is_numeric_type( $type ) {
809 switch (strtoupper($type)) {
824 * Alias for addQuotes()
825 * @param string s string to escape
826 * @return escaped string
828 public function strencode( $s ) {
829 // Bloody useless function
830 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
831 // But also necessary
832 $s = db2_escape_string($s);
833 // Wide characters are evil -- some of them look like '
834 $s = utf8_encode($s);
836 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
837 $to = array("\\", "''", "\n", "\t", '"', "\r");
838 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
843 * Switch into the database schema
845 protected function applySchema() {
846 if ( !($this->mSchemaSet
) ) {
847 $this->mSchemaSet
= true;
849 $this->doQuery("SET SCHEMA = $this->mSchema");
855 * Start a transaction (mandatory)
857 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
858 // turn off auto-commit
859 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
860 $this->mTrxLevel
= 1;
865 * Must have a preceding begin()
867 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
868 db2_commit($this->mConn
);
869 // turn auto-commit back on
870 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
871 $this->mTrxLevel
= 0;
875 * Cancel a transaction
877 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
878 db2_rollback($this->mConn
);
879 // turn auto-commit back on
880 // not sure if this is appropriate
881 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
882 $this->mTrxLevel
= 0;
886 * Makes an encoded list of strings from an array
888 * LIST_COMMA - comma separated, no field names
889 * LIST_AND - ANDed WHERE clause (without the WHERE)
890 * LIST_OR - ORed WHERE clause (without the WHERE)
891 * LIST_SET - comma separated with field names, like a SET clause
892 * LIST_NAMES - comma separated field names
894 public function makeList( $a, $mode = LIST_COMMA
) {
895 $this->installPrint("DB2::makeList()\n");
896 if ( !is_array( $a ) ) {
897 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
902 foreach ( $a as $field => $value ) {
904 if ( $mode == LIST_AND
) {
906 } elseif($mode == LIST_OR
) {
914 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
916 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
918 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
919 if( count( $value ) == 0 ) {
920 throw new MWException( __METHOD__
.': empty input' );
921 } elseif( count( $value ) == 1 ) {
922 // Special-case single values, as IN isn't terribly efficient
923 // Don't necessarily assume the single key is 0; we don't
924 // enforce linear numeric ordering on other arrays here.
925 $value = array_values( $value );
926 $list .= $field." = ".$this->addQuotes( $value[0] );
928 $list .= $field." IN (".$this->makeList($value).") ";
930 } elseif( is_null($value) ) {
931 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
932 $list .= "$field IS ";
933 } elseif ( $mode == LIST_SET
) {
934 $list .= "$field = ";
938 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
939 $list .= "$field = ";
941 if ( $mode == LIST_NAMES
) {
944 // Leo: Can't insert quoted numbers into numeric columns
945 // (?) Might cause other problems. May have to check column type before insertion.
946 else if ( is_numeric($value) ) {
950 $list .= $this->addQuotes( $value );
958 * Construct a LIMIT query with optional offset
959 * This is used for query pages
960 * $sql string SQL query we will append the limit too
961 * $limit integer the SQL limit
962 * $offset integer the SQL offset (default false)
964 public function limitResult($sql, $limit, $offset=false) {
965 if( !is_numeric($limit) ) {
966 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
969 $this->installPrint("Offset parameter not supported in limitResult()\n");
971 // TODO implement proper offset handling
972 // idea: get all the rows between 0 and offset, advance cursor to offset
973 return "$sql FETCH FIRST $limit ROWS ONLY ";
977 * Handle reserved keyword replacement in table names
979 * @param $name Object
981 public function tableName( $name ) {
982 # Replace reserved words with better ones
987 // return 'pagecontent';
991 // we want maximum compatibility with MySQL schema
996 * Generates a timestamp in an insertable format
997 * @return string timestamp value
998 * @param timestamp $ts
1000 public function timestamp( $ts=0 ) {
1001 // TS_MW cannot be easily distinguished from an integer
1002 return wfTimestamp(TS_DB2
,$ts);
1006 * Return the next in a sequence, save the value for retrieval via insertId()
1007 * @param string seqName Name of a defined sequence in the database
1008 * @return next value in that sequence
1010 public function nextSequenceValue( $seqName ) {
1011 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1012 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1014 $safeseq = preg_replace( "/'/", "''", $seqName );
1015 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1016 $row = $this->fetchRow( $res );
1017 $this->mInsertId = $row[0];
1018 $this->freeResult( $res );
1019 return $this->mInsertId;
1025 * This must be called after nextSequenceVal
1026 * @return Last sequence value used as a primary key
1028 public function insertId() {
1029 return $this->mInsertId
;
1033 * INSERT wrapper, inserts an array into a table
1035 * $args may be a single associative array, or an array of these with numeric keys,
1036 * for multi-row insert
1038 * @param array $table String: Name of the table to insert to.
1039 * @param array $args Array: Items to insert into the table.
1040 * @param array $fname String: Name of the function, for profiling
1041 * @param mixed $options String or Array. Valid options: IGNORE
1043 * @return bool Success of insert operation. IGNORE always returns true.
1045 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1046 $this->installPrint("DB2::insert($table)\n");
1047 if ( !count( $args ) ) {
1050 // get database-specific table name (not used)
1051 $table = $this->tableName( $table );
1052 // format options as an array
1053 if ( !is_array( $options ) ) $options = array( $options );
1054 // format args as an array of arrays
1055 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1056 $args = array($args);
1058 // prevent insertion of NULL into primary key columns
1059 $args = $this->removeNullPrimaryKeys($table, $args);
1062 $keys = array_keys( $args[0] );
1063 $key_count = count($keys);
1065 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1066 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1068 // If we are not in a transaction, we need to be for savepoint trickery
1070 if (! $this->mTrxLevel
) {
1075 $olde = error_reporting( 0 );
1076 // For future use, we may want to track the number of actual inserts
1077 // Right now, insert (all writes) simply return true/false
1078 $numrowsinserted = 0;
1081 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1082 switch($key_count) {
1088 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1090 $stmt = $this->prepare($sql);
1094 foreach ( $args as $row ) {
1095 // insert each row into the database
1096 $this->execute($stmt, $row);
1100 // we must have autocommit turned off -- transaction mode on
1104 foreach ( $args as $row ) {
1106 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1107 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1110 $this->execute($sql, $row);
1112 $bar = $this->lastError();
1114 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1117 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1124 // commit either way
1128 $olde = error_reporting( $olde );
1129 // Set the affected row count for the whole operation
1130 $this->mAffectedRows
= $numrowsinserted;
1132 // IGNORE always returns true
1140 * Given a table name and a hash of columns with values
1141 * Removes primary key columns from the hash where the value is NULL
1143 * @param string $table Name of the table
1144 * @param array $args Array of hashes of column names with values
1145 * @return array Filtered array of hashes
1147 private function removeNullPrimaryKeys($table, $args) {
1148 $schema = $this->mSchema
;
1149 // find out the primary keys
1150 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1152 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1153 $keys[] = strtolower($row->column_name
);
1155 // remove primary keys
1156 foreach ($args as $ai => $row) {
1157 foreach ($keys as $ki => $key) {
1158 if ($row[$key] == NULL) {
1164 // return modified hash
1169 * UPDATE wrapper, takes a condition array and a SET array
1171 * @param string $table The table to UPDATE
1172 * @param array $values An array of values to SET
1173 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1174 * @param string $fname The Class::Function calling this function
1176 * @param array $options An array of UPDATE options, can be one or
1177 * more of IGNORE, LOW_PRIORITY
1180 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1181 $table = $this->tableName( $table );
1182 $opts = $this->makeUpdateOptions( $options );
1183 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1184 if ( $conds != '*' ) {
1185 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1187 return $this->query( $sql, $fname );
1191 * DELETE query wrapper
1193 * Use $conds == "*" to delete all rows
1195 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1197 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1199 $table = $this->tableName( $table );
1200 $sql = "DELETE FROM $table";
1201 if ( $conds != '*' ) {
1202 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1204 return $this->query( $sql, $fname );
1208 * Returns the number of rows affected by the last query or 0
1209 * @return int the number of rows affected by the last query
1211 public function affectedRows() {
1212 if ( !is_null( $this->mAffectedRows
) ) {
1213 // Forced result for simulated queries
1214 return $this->mAffectedRows
;
1216 if( empty( $this->mLastResult
) )
1218 return db2_num_rows( $this->mLastResult
);
1222 * Simulates REPLACE with a DELETE followed by INSERT
1223 * @param $table Object
1224 * @param array $uniqueIndexes array consisting of indexes and arrays of indexes
1225 * @param array $rows Rows to insert
1226 * @param string $fname Name of the function for profiling
1229 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1230 $table = $this->tableName( $table );
1232 if (count($rows)==0) {
1237 if ( !is_array( reset( $rows ) ) ) {
1238 $rows = array( $rows );
1241 foreach( $rows as $row ) {
1242 # Delete rows which collide
1243 if ( $uniqueIndexes ) {
1244 $sql = "DELETE FROM $table WHERE ";
1246 foreach ( $uniqueIndexes as $index ) {
1253 if ( is_array( $index ) ) {
1255 foreach ( $index as $col ) {
1261 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1264 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1268 $this->query( $sql, $fname );
1271 # Now insert the row
1272 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1273 $this->makeList( $row, LIST_COMMA
) . ')';
1274 $this->query( $sql, $fname );
1279 * Returns the number of rows in the result set
1280 * Has to be called right after the corresponding select query
1281 * @param object $res result set
1282 * @return int number of rows
1284 public function numRows( $res ) {
1285 if ( $res instanceof ResultWrapper
) {
1286 $res = $res->result
;
1288 if ( $this->mNumRows
) {
1289 return $this->mNumRows
;
1297 * Moves the row pointer of the result set
1298 * @param object $res result set
1299 * @param int $row row number
1300 * @return success or failure
1302 public function dataSeek( $res, $row ) {
1303 if ( $res instanceof ResultWrapper
) {
1304 $res = $res->result
;
1306 return db2_fetch_row( $res, $row );
1310 # Fix notices in Block.php
1314 * Frees memory associated with a statement resource
1315 * @param object $res Statement resource to free
1316 * @return bool success or failure
1318 public function freeResult( $res ) {
1319 if ( $res instanceof ResultWrapper
) {
1320 $res = $res->result
;
1322 if ( !@db2_free_result
( $res ) ) {
1323 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1328 * Returns the number of columns in a resource
1329 * @param object $res Statement resource
1330 * @return Number of fields/columns in resource
1332 public function numFields( $res ) {
1333 if ( $res instanceof ResultWrapper
) {
1334 $res = $res->result
;
1336 return db2_num_fields( $res );
1340 * Returns the nth column name
1341 * @param object $res Statement resource
1342 * @param int $n Index of field or column
1343 * @return string name of nth column
1345 public function fieldName( $res, $n ) {
1346 if ( $res instanceof ResultWrapper
) {
1347 $res = $res->result
;
1349 return db2_field_name( $res, $n );
1355 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1356 * @param mixed $vars Array or string, field name(s) to be retrieved
1357 * @param mixed $conds Array or string, condition(s) for WHERE
1358 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1359 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1360 * see Database::makeSelectOptions code for list of supported stuff
1361 * @param array $join_conds Associative array of table join conditions (optional)
1362 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1363 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1365 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1367 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1369 // We must adjust for offset
1370 if ( isset( $options['LIMIT'] ) ) {
1371 if ( isset ($options['OFFSET'] ) ) {
1372 $limit = $options['LIMIT'];
1373 $offset = $options['OFFSET'];
1378 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1379 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1382 // we want the count
1383 $vars2 = array('count(*) as num_rows');
1384 // respecting just the limit option
1385 $options2 = array();
1386 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1387 // but don't try to emulate for GROUP BY
1388 if ( isset( $options['GROUP BY'] ) ) return $res;
1390 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1391 $obj = $this->fetchObject($res2);
1392 $this->mNumRows
= $obj->num_rows
;
1394 $this->installPrint("DatabaseIbm_db2::select: There are $this->mNumRows rows.\n");
1400 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1401 * Has limited support for per-column options (colnum => 'DISTINCT')
1405 * @param array $options an associative array of options to be turned into
1406 * an SQL query, valid keys are listed in the function.
1409 function makeSelectOptions( $options ) {
1410 $preLimitTail = $postLimitTail = '';
1413 $noKeyOptions = array();
1414 foreach ( $options as $key => $option ) {
1415 if ( is_numeric( $key ) ) {
1416 $noKeyOptions[$option] = true;
1420 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1421 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1422 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1424 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1426 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1430 * Returns link to IBM DB2 free download
1431 * @return string wikitext of a link to the server software's web site
1433 public function getSoftwareLink() {
1434 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1438 * @return String: Database type for use in messages
1440 function getDBtypeForMsg() {
1445 * Get search engine class. All subclasses of this
1446 * need to implement this if they wish to use searching.
1450 public function getSearchEngine() {
1451 return "SearchIBM_DB2";
1455 * Did the last database access fail because of deadlock?
1458 public function wasDeadlock() {
1460 $err = $this->lastErrno();
1462 case '40001': // sql0911n, Deadlock or timeout, rollback
1463 case '57011': // sql0904n, Resource unavailable, no rollback
1464 case '57033': // sql0913n, Deadlock or timeout, no rollback
1465 $this->installPrint("In a deadlock because of SQLSTATE $err");
1472 * Ping the server and try to reconnect if it there is no connection
1473 * The connection may be closed and reopened while this happens
1474 * @return bool whether the connection exists
1476 public function ping() {
1477 // db2_ping() doesn't exist
1480 if ($this->mCataloged
== NULL) {
1483 else if ($this->mCataloged
) {
1484 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1486 else if (!$this->mCataloged
) {
1487 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1491 ######################################
1492 # Unimplemented and not applicable
1493 ######################################
1499 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1509 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1514 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1517 * @return string $sql
1520 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1523 * Only useful with fake prepare like in base Database class
1526 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1528 ######################################
1530 ######################################
1533 * Query whether a given column exists in the mediawiki schema
1534 * @param string $table name of the table
1535 * @param string $field name of the column
1536 * @param string $fname function name for logging and profiling
1538 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1539 $table = $this->tableName( $table );
1540 $schema = $this->mSchema
;
1541 $etable = preg_replace("/'/", "''", $table);
1542 $eschema = preg_replace("/'/", "''", $schema);
1543 $ecol = preg_replace("/'/", "''", $field);
1545 SELECT 1 as fieldexists
1546 FROM sysibm.syscolumns sc
1547 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1549 $res = $this->query( $sql, $fname );
1550 $count = $res ?
$this->numRows($res) : 0;
1552 $this->freeResult( $res );
1557 * Returns information about an index
1558 * If errors are explicitly ignored, returns NULL on failure
1559 * @param string $table table name
1560 * @param string $index index name
1562 * @return object query row in object form
1564 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1565 $table = $this->tableName( $table );
1567 SELECT name as indexname
1568 FROM sysibm.sysindexes si
1569 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1571 $res = $this->query( $sql, $fname );
1575 $row = $this->fetchObject( $res );
1576 if ($row != NULL) return $row;
1581 * Returns an information object on a table column
1582 * @param string $table table name
1583 * @param string $field column name
1584 * @return IBM_DB2Field
1586 public function fieldInfo( $table, $field ) {
1587 return IBM_DB2Field
::fromText($this, $table, $field);
1591 * db2_field_type() wrapper
1592 * @param object $res Result of executed statement
1593 * @param mixed $index number or name of the column
1594 * @return string column type
1596 public function fieldType( $res, $index ) {
1597 if ( $res instanceof ResultWrapper
) {
1598 $res = $res->result
;
1600 return db2_field_type( $res, $index );
1604 * Verifies that an index was created as unique
1605 * @param string $table table name
1606 * @param string $index index name
1607 * @param string $fnam function name for profiling
1610 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1611 $table = $this->tableName( $table );
1613 SELECT si.name as indexname
1614 FROM sysibm.sysindexes si
1615 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1616 AND si.uniquerule IN ('U', 'P')
1618 $res = $this->query( $sql, $fname );
1622 if ($this->fetchObject( $res )) {
1630 * Returns the size of a text field, or -1 for "unlimited"
1631 * @param string $table table name
1632 * @param string $field column name
1633 * @return int length or -1 for unlimited
1635 public function textFieldSize( $table, $field ) {
1636 $table = $this->tableName( $table );
1638 SELECT length as size
1639 FROM sysibm.syscolumns sc
1640 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1642 $res = $this->query($sql);
1643 $row = $this->fetchObject($res);
1645 $this->freeResult( $res );
1650 * DELETE where the condition is a join
1651 * @param string $delTable deleting from this table
1652 * @param string $joinTable using data from this table
1653 * @param string $delVar variable in deleteable table
1654 * @param string $joinVar variable in data table
1655 * @param array $conds conditionals for join table
1656 * @param string $fname function name for profiling
1658 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1660 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1663 $delTable = $this->tableName( $delTable );
1664 $joinTable = $this->tableName( $joinTable );
1665 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1666 if ( $conds != '*' ) {
1667 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1671 $this->query( $sql, $fname );
1675 * Estimate rows in dataset
1676 * Returns estimated count, based on COUNT(*) output
1677 * Takes same arguments as Database::select()
1678 * @param string $table table name
1679 * @param array $vars unused
1680 * @param array $conds filters on the table
1681 * @param string $fname function name for profiling
1682 * @param array $options options for select
1683 * @return int row count
1685 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1687 $res = $this->select ($table, 'COUNT(*) as mwrowcount', $conds, $fname, $options );
1689 $row = $this->fetchRow($res);
1690 $rows = (isset($row['mwrowcount'])) ?
$row['mwrowcount'] : 0;
1692 $this->freeResult($res);
1697 * Description is left as an exercise for the reader
1698 * @param mixed $b data to be encoded
1699 * @return IBM_DB2Blob
1701 public function encodeBlob($b) {
1702 return new IBM_DB2Blob($b);
1706 * Description is left as an exercise for the reader
1707 * @param IBM_DB2Blob $b data to be decoded
1710 public function decodeBlob($b) {
1711 return $b->getData();
1715 * Convert into a list of string being concatenated
1716 * @param array $stringList strings that need to be joined together by the SQL engine
1717 * @return string joined by the concatenation operator
1719 public function buildConcat( $stringList ) {
1720 // || is equivalent to CONCAT
1721 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1722 return implode( ' || ', $stringList );
1726 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1727 * @param string $column name of timestamp column
1728 * @return string SQL code
1730 public function extractUnixEpoch( $column ) {
1732 // see SpecialAncientpages
1735 ######################################
1736 # Prepared statements
1737 ######################################
1740 * Intended to be compatible with the PEAR::DB wrapper functions.
1741 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1743 * ? = scalar value, quoted as necessary
1744 * ! = raw SQL bit (a function for instance)
1745 * & = filename; reads the file and inserts as a blob
1746 * (we don't use this though...)
1747 * @param string $sql SQL statement with appropriate markers
1748 * @return resource a prepared DB2 SQL statement
1750 public function prepare( $sql, $func = 'DB2::prepare' ) {
1751 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1756 * Frees resources associated with a prepared statement
1757 * @return bool success or failure
1759 public function freePrepared( $prepared ) {
1760 return db2_free_stmt($prepared);
1764 * Execute a prepared query with the various arguments
1765 * @param string $prepared the prepared sql
1766 * @param mixed $args Either an array here, or put scalars as varargs
1767 * @return resource Results object
1769 public function execute( $prepared, $args = null ) {
1770 if( !is_array( $args ) ) {
1772 $args = func_get_args();
1773 array_shift( $args );
1775 $res = db2_execute($prepared, $args);
1780 * Prepare & execute an SQL statement, quoting and inserting arguments
1781 * in the appropriate places.
1782 * @param $query String
1785 public function safeQuery( $query, $args = null ) {
1786 // copied verbatim from Database.php
1787 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1788 if( !is_array( $args ) ) {
1790 $args = func_get_args();
1791 array_shift( $args );
1793 $retval = $this->execute( $prepared, $args );
1794 $this->freePrepared( $prepared );
1799 * For faking prepared SQL statements on DBs that don't support
1801 * @param resource $preparedQuery String: a 'preparable' SQL statement
1802 * @param array $args Array of arguments to fill it with
1803 * @return string executable statement
1805 public function fillPrepared( $preparedQuery, $args ) {
1807 $this->preparedArgs
=& $args;
1809 foreach ($args as $i => $arg) {
1810 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1813 return $preparedQuery;
1817 * Switches module between regular and install modes
1819 public function setMode($mode) {
1820 $old = $this->mMode
;
1821 $this->mMode
= $mode;
1826 * Bitwise negation of a column or value in SQL
1827 * Same as (~field) in C
1828 * @param string $field
1831 function bitNot($field) {
1832 //expecting bit-fields smaller than 4bytes
1833 return 'BITNOT('.$bitField.')';
1837 * Bitwise AND of two columns or values in SQL
1838 * Same as (fieldLeft & fieldRight) in C
1839 * @param string $fieldLeft
1840 * @param string $fieldRight
1843 function bitAnd($fieldLeft, $fieldRight) {
1844 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1848 * Bitwise OR of two columns or values in SQL
1849 * Same as (fieldLeft | fieldRight) in C
1850 * @param string $fieldLeft
1851 * @param string $fieldRight
1854 function bitOr($fieldLeft, $fieldRight) {
1855 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';