3 * This is the IBM DB2 database abstraction layer.
4 * See maintenance/ibm_db2/README for development notes
5 * and other specific information
9 * @author leo.petr+mediawiki@gmail.com
13 * This represents a column in a DB2 database
18 private $tablename = '';
20 private $nullable = false;
21 private $max_length = 0;
24 * Builder method for the class
25 * @param $db DatabaseIbm_db2: Database interface
26 * @param $table String: table name
27 * @param $field String: column name
28 * @return IBM_DB2Field
30 static function fromText( $db, $table, $field ) {
35 lcase( coltype ) AS typname,
36 nulls AS attnotnull, length AS attlen
37 FROM sysibm.syscolumns
38 WHERE tbcreator=%s AND tbname=%s AND name=%s;
40 $res = $db->query( sprintf( $q,
41 $db->addQuotes( $wgDBmwschema ),
42 $db->addQuotes( $table ),
43 $db->addQuotes( $field )) );
44 $row = $db->fetchObject( $res );
47 $n = new IBM_DB2Field
;
48 $n->type
= $row->typname
;
49 $n->nullable
= ( $row->attnotnull
== 'N' );
51 $n->tablename
= $table;
52 $n->max_length
= $row->attlen
;
57 * @return string column name
59 function name() { return $this->name
; }
62 * @return string table name
64 function tableName() { return $this->tablename
; }
67 * @return string column type
69 function type() { return $this->type
; }
72 * @return bool true or false
74 function nullable() { return $this->nullable
; }
76 * How much can you fit in the column per row?
79 function maxLength() { return $this->max_length
; }
83 * Wrapper around binary large objects
89 public function __construct( $data ) {
93 public function getData() {
97 public function __toString()
104 * Primary database interface
107 class DatabaseIbm_db2
extends DatabaseBase
{
110 protected $mLastQuery = '';
111 protected $mPHPError = false;
113 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
114 protected $mOut, $mOpened = false;
116 protected $mFailFunction;
117 protected $mTablePrefix;
119 protected $mTrxLevel = 0;
120 protected $mErrorCount = 0;
121 protected $mLBInfo = array();
122 protected $mFakeSlaveLag = null, $mFakeMaster = false;
126 /** Database server port */
127 protected $mPort = 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;
139 /** Connection config options - see constructor */
140 public $mConnOptions = array();
141 /** Statement config options -- see constructor */
142 public $mStmtOptions = array();
144 /** Default schema */
145 const USE_GLOBAL
= "mediawiki";
147 /** Option that applies to nothing */
148 const NONE_OPTION
= 0x00;
149 /** Option that applies to connection objects */
150 const CONN_OPTION
= 0x01;
151 /** Option that applies to statement objects */
152 const STMT_OPTION
= 0x02;
154 /** Regular operation mode -- minimal debug messages */
155 const REGULAR_MODE
= 'regular';
156 /** Installation mode -- lots of debug messages */
157 const INSTALL_MODE
= 'install';
159 /** Controls the level of debug message output */
160 protected $mMode = self
::REGULAR_MODE
;
162 /** Last sequence value used for a primary key */
163 protected $mInsertId = null;
165 ######################################
166 # Getters and Setters
167 ######################################
170 * Returns true if this database supports (and uses) cascading deletes
172 function cascadingDeletes() {
177 * Returns true if this database supports (and uses) triggers (e.g. on the
180 function cleanupTriggers() {
185 * Returns true if this database is strict about what can be put into an
187 * Specifically, it uses a NULL value instead of an empty string.
189 function strictIPs() {
194 * Returns true if this database uses timestamps rather than integers
196 function realTimestamps() {
201 * Returns true if this database does an implicit sort when doing GROUP BY
203 function implicitGroupby() {
208 * Returns true if this database does an implicit order by when the column
210 * For example: SELECT page_title FROM page LIMIT 1
212 function implicitOrderby() {
217 * Returns true if this database can do a native search on IP columns
218 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
220 function searchableIPs() {
225 * Returns true if this database can use functional indexes
227 function functionalIndexes() {
232 * Returns a unique string representing the wiki on the server
234 function getWikiID() {
235 if( $this->mSchema
) {
236 return "{$this->mDBname}-{$this->mSchema}";
238 return $this->mDBname
;
246 ######################################
248 ######################################
253 * @param $server String: hostname of database server
254 * @param $user String: username
255 * @param $password String: password
256 * @param $dbName String: database name on the server
257 * @param $failFunction Callback (optional)
258 * @param $flags Integer: database behaviour flags (optional, unused)
259 * @param $schema String
261 public function DatabaseIbm_db2( $server = false, $user = false,
263 $dbName = false, $failFunction = false, $flags = 0,
264 $schema = self
::USE_GLOBAL
)
267 global $wgOut, $wgDBmwschema;
268 # Can't get a reference if it hasn't been set yet
269 if ( !isset( $wgOut ) ) {
272 $this->mOut
=& $wgOut;
273 $this->mFailFunction
= $failFunction;
274 $this->mFlags
= DBO_TRX |
$flags;
276 if ( $schema == self
::USE_GLOBAL
) {
277 $this->mSchema
= $wgDBmwschema;
280 $this->mSchema
= $schema;
283 // configure the connection and statement objects
284 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
285 self
::CONN_OPTION | self
::STMT_OPTION
);
286 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
288 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
291 $this->open( $server, $user, $password, $dbName );
295 * Enables options only if the ibm_db2 extension version supports them
296 * @param $name String: name of the option in the options array
297 * @param $const String: name of the constant holding the right option value
298 * @param $type Integer: whether this is a Connection or Statement otion
300 private function setDB2Option( $name, $const, $type ) {
301 if ( defined( $const )) {
302 if ( $type & self
::CONN_OPTION
) {
303 $this->mConnOptions
[$name] = constant( $const );
305 if ( $type & self
::STMT_OPTION
) {
306 $this->mStmtOptions
[$name] = constant( $const );
311 "$const is not defined. ibm_db2 version is likely too low." );
316 * Outputs debug information in the appropriate place
317 * @param $string String: the relevant debug message
319 private function installPrint( $string ) {
320 wfDebug( "$string\n" );
321 if ( $this->mMode
== self
::INSTALL_MODE
) {
322 print "<li><pre>$string</pre></li>";
328 * Opens a database connection and returns it
329 * Closes any existing connection
330 * @return a fresh connection
331 * @param $server String: hostname
332 * @param $user String
333 * @param $password String
334 * @param $dbName String: database name
336 public function open( $server, $user, $password, $dbName )
338 // Load the port number
340 wfProfileIn( __METHOD__
);
342 // Load IBM DB2 driver if missing
345 // Test for IBM DB2 support, to avoid suppressed fatal error
346 if ( !function_exists( 'db2_connect' ) ) {
348 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
351 $this->installPrint( $error );
352 $this->reportConnectionError( $error );
355 if ( strlen( $user ) < 1) {
359 // Close existing connection
362 $this->mServer
= $server;
363 $this->mPort
= $port = $wgDBport;
364 $this->mUser
= $user;
365 $this->mPassword
= $password;
366 $this->mDBname
= $dbName;
368 $this->openUncataloged( $dbName, $user, $password, $server, $port );
370 // Apply connection config
371 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
372 // Some MediaWiki code is still transaction-less (?).
373 // The strategy is to keep AutoCommit on for that code
374 // but switch it off whenever a transaction is begun.
375 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
377 if ( !$this->mConn
) {
378 $this->installPrint( "DB connection error\n" );
380 "Server: $server, Database: $dbName, User: $user, Password: "
381 . substr( $password, 0, 3 ) . "...\n" );
382 $this->installPrint( $this->lastError() . "\n" );
386 $this->mOpened
= true;
387 $this->applySchema();
389 wfProfileOut( __METHOD__
);
394 * Opens a cataloged database connection, sets mConn
396 protected function openCataloged( $dbName, $user, $password )
398 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
402 * Opens an uncataloged database connection, sets mConn
404 protected function openUncataloged( $dbName, $user, $password, $server, $port )
406 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
407 $str .= "DATABASE=$dbName;";
408 $str .= "HOSTNAME=$server;";
409 // port was formerly validated to not be 0
410 $str .= "PORT=$port;";
411 $str .= "PROTOCOL=TCPIP;";
412 $str .= "UID=$user;";
413 $str .= "PWD=$password;";
415 @$this->mConn
= db2_pconnect( $str, $user, $password );
419 * Closes a database connection, if it is open
420 * Returns success, true if already closed
422 public function close() {
423 $this->mOpened
= false;
424 if ( $this->mConn
) {
425 if ($this->trxLevel() > 0) {
428 return db2_close( $this->mConn
);
436 * Returns a fresh instance of this class
438 * @param $server String: hostname of database server
439 * @param $user String: username
440 * @param $password String
441 * @param $dbName String: database name on the server
442 * @param $failFunction Callback (optional)
443 * @param $flags Integer: database behaviour flags (optional, unused)
444 * @return DatabaseIbm_db2 object
446 static function newFromParams( $server, $user, $password, $dbName,
447 $failFunction = false, $flags = 0 )
449 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
450 $failFunction, $flags );
454 * Retrieves the most current database error
455 * Forces a database rollback
457 public function lastError() {
458 $connerr = db2_conn_errormsg();
463 $stmterr = db2_stmt_errormsg();
473 * Get the last error number
474 * Return 0 if no error
477 public function lastErrno() {
478 $connerr = db2_conn_error();
482 $stmterr = db2_stmt_error();
490 * Is a database connection open?
493 public function isOpen() { return $this->mOpened
; }
496 * The DBMS-dependent part of query()
497 * @param $sql String: SQL query.
498 * @return object Result object for fetch functions or false on failure
502 public function doQuery( $sql ) {
503 $this->applySchema();
505 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
506 if( $ret == FALSE ) {
507 $error = db2_stmt_errormsg();
508 $this->installPrint( "<pre>$sql</pre>" );
509 $this->installPrint( $error );
510 throw new DBUnexpectedError( $this, 'SQL error: '
511 . htmlspecialchars( $error ) );
513 $this->mLastResult
= $ret;
514 $this->mAffectedRows
= null; // Not calculated until asked for
519 * @return string Version information from the database
521 public function getServerVersion() {
522 $info = db2_server_info( $this->mConn
);
523 return $info->DBMS_VER
;
527 * Queries whether a given table exists
530 public function tableExists( $table ) {
531 $schema = $this->mSchema
;
533 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
534 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
536 $res = $this->query( $sql );
537 if ( !$res ) return false;
539 // If the table exists, there should be one of it
540 @$row = $this->fetchRow( $res );
542 if ( $count == '1' or $count == 1 ) {
550 * Fetch the next row from the given result object, in object form.
551 * Fields can be retrieved with $row->fieldname, with fields acting like
554 * @param $res SQL result object as returned from Database::query(), etc.
555 * @return DB2 row object
556 * @throws DBUnexpectedError Thrown if the database returns an error
558 public function fetchObject( $res ) {
559 if ( $res instanceof ResultWrapper
) {
562 @$row = db2_fetch_object( $res );
563 if( $this->lastErrno() ) {
564 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
565 . htmlspecialchars( $this->lastError() ) );
571 * Fetch the next row from the given result object, in associative array
572 * form. Fields are retrieved with $row['fieldname'].
574 * @param $res SQL result object as returned from Database::query(), etc.
575 * @return DB2 row object
576 * @throws DBUnexpectedError Thrown if the database returns an error
578 public function fetchRow( $res ) {
579 if ( $res instanceof ResultWrapper
) {
582 @$row = db2_fetch_array( $res );
583 if ( $this->lastErrno() ) {
584 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
585 . htmlspecialchars( $this->lastError() ) );
591 * Override if introduced to base Database class
593 public function initial_setup() {
598 * Create tables, stored procedures, and so on
600 public function setup_database() {
602 // TODO: switch to root login if available
604 // Switch into the correct namespace
605 $this->applySchema();
608 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
609 if ( $res !== true ) {
610 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
614 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
615 if ( $res !== true ) {
616 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
618 print "<li>Foreign keys done</li>";
622 // TODO: populate interwiki links
624 if ( $this->lastError() ) {
626 "Errors encountered during table creation -- rolled back" );
627 $this->installPrint( "Please install again" );
634 catch ( MWException
$mwe )
636 print "<br><pre>$mwe</pre><br>";
642 * Doesn't escape numbers
643 * @param $s String: string to escape
644 * @return escaped string
646 public function addQuotes( $s ) {
647 //$this->installPrint( "DB2::addQuotes( $s )\n" );
648 if ( is_null( $s ) ) {
650 } else if ( $s instanceof Blob
) {
651 return "'" . $s->fetch( $s ) . "'";
652 } else if ( $s instanceof IBM_DB2Blob
) {
653 return "'" . $this->decodeBlob( $s ) . "'";
655 $s = $this->strencode( $s );
656 if ( is_numeric( $s ) ) {
665 * Verifies that a DB2 column/field type is numeric
666 * @return bool true if numeric
667 * @param $type String: DB2 column type
669 public function is_numeric_type( $type ) {
670 switch ( strtoupper( $type )) {
685 * Alias for addQuotes()
686 * @param $s String: string to escape
687 * @return escaped string
689 public function strencode( $s ) {
690 // Bloody useless function
691 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
692 // But also necessary
693 $s = db2_escape_string( $s );
694 // Wide characters are evil -- some of them look like '
695 $s = utf8_encode( $s );
697 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
698 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
699 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
704 * Switch into the database schema
706 protected function applySchema() {
707 if ( !( $this->mSchemaSet
) ) {
708 $this->mSchemaSet
= true;
710 $this->doQuery( "SET SCHEMA = $this->mSchema" );
716 * Start a transaction (mandatory)
718 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
719 // BEGIN is implicit for DB2
720 // However, it requires that AutoCommit be off.
722 // Some MediaWiki code is still transaction-less (?).
723 // The strategy is to keep AutoCommit on for that code
724 // but switch it off whenever a transaction is begun.
725 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
727 $this->mTrxLevel
= 1;
732 * Must have a preceding begin()
734 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
735 db2_commit( $this->mConn
);
737 // Some MediaWiki code is still transaction-less (?).
738 // The strategy is to keep AutoCommit on for that code
739 // but switch it off whenever a transaction is begun.
740 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
742 $this->mTrxLevel
= 0;
746 * Cancel a transaction
748 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
749 db2_rollback( $this->mConn
);
750 // turn auto-commit back on
751 // not sure if this is appropriate
752 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
753 $this->mTrxLevel
= 0;
757 * Makes an encoded list of strings from an array
759 * LIST_COMMA - comma separated, no field names
760 * LIST_AND - ANDed WHERE clause (without the WHERE)
761 * LIST_OR - ORed WHERE clause (without the WHERE)
762 * LIST_SET - comma separated with field names, like a SET clause
763 * LIST_NAMES - comma separated field names
764 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
766 function makeList( $a, $mode = LIST_COMMA
) {
767 if ( !is_array( $a ) ) {
768 throw new DBUnexpectedError( $this,
769 'DatabaseBase::makeList called with incorrect parameters' );
772 // if this is for a prepared UPDATE statement
773 // (this should be promoted to the parent class
774 // once other databases use prepared statements)
775 if ( $mode == LIST_SET_PREPARED
) {
778 foreach ( $a as $field => $value ) {
780 $list .= ", $field = ?";
783 $list .= "$field = ?";
792 // otherwise, call the usual function
793 return parent
::makeList( $a, $mode );
797 * Construct a LIMIT query with optional offset
798 * This is used for query pages
799 * @param $sql string SQL query we will append the limit too
800 * @param $limit integer the SQL limit
801 * @param $offset integer the SQL offset (default false)
803 public function limitResult( $sql, $limit, $offset=false ) {
804 if( !is_numeric( $limit ) ) {
805 throw new DBUnexpectedError( $this,
806 "Invalid non-numeric limit passed to limitResult()\n" );
809 if ( stripos( $sql, 'where' ) === false ) {
810 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
813 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
816 return "$sql FETCH FIRST $limit ROWS ONLY ";
820 * Handle reserved keyword replacement in table names
822 * @param $name Object
824 public function tableName( $name ) {
825 // we want maximum compatibility with MySQL schema
830 * Generates a timestamp in an insertable format
831 * @return string timestamp value
832 * @param $ts timestamp
834 public function timestamp( $ts=0 ) {
835 // TS_MW cannot be easily distinguished from an integer
836 return wfTimestamp( TS_DB2
, $ts );
840 * Return the next in a sequence, save the value for retrieval via insertId()
841 * @param $seqName String: name of a defined sequence in the database
842 * @return next value in that sequence
844 public function nextSequenceValue( $seqName ) {
845 // Not using sequences in the primary schema to allow for easier migration
847 // Emulating MySQL behaviour of using NULL to signal that sequences
850 $safeseq = preg_replace( "/'/", "''", $seqName );
851 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
852 $row = $this->fetchRow( $res );
853 $this->mInsertId = $row[0];
854 return $this->mInsertId;
860 * This must be called after nextSequenceVal
861 * @return Last sequence value used as a primary key
863 public function insertId() {
864 return $this->mInsertId
;
868 * Updates the mInsertId property with the value of the last insert
869 * into a generated column
870 * @param $table String: sanitized table name
871 * @param $primaryKey Mixed: string name of the primary key
872 * @param $stmt Resource: prepared statement resource
873 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
875 private function calcInsertId( $table, $primaryKey, $stmt ) {
877 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
882 * INSERT wrapper, inserts an array into a table
884 * $args may be a single associative array, or an array of arrays
885 * with numeric keys, for multi-row insert
887 * @param $table String: Name of the table to insert to.
888 * @param $args Array: Items to insert into the table.
889 * @param $fname String: Name of the function, for profiling
890 * @param $options String or Array. Valid options: IGNORE
892 * @return bool Success of insert operation. IGNORE always returns true.
894 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
897 if ( !count( $args ) ) {
900 // get database-specific table name (not used)
901 $table = $this->tableName( $table );
902 // format options as an array
903 $options = IBM_DB2Helper
::makeArray( $options );
904 // format args as an array of arrays
905 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
906 $args = array( $args );
909 // prevent insertion of NULL into primary key columns
910 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
911 // if there's only one primary key
912 // we'll be able to read its value after insertion
914 if ( count( $primaryKeys ) == 1 ) {
915 $primaryKey = $primaryKeys[0];
919 $keys = array_keys( $args[0] );
920 $key_count = count( $keys );
922 // If IGNORE is set, we use savepoints to emulate mysql's behavior
923 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
927 // If we are not in a transaction, we need to be for savepoint trickery
928 if ( ! $this->mTrxLevel
) {
932 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
933 if ( $key_count == 1 ) {
936 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
938 //$this->installPrint( "Preparing the following SQL:" );
939 //$this->installPrint( "$sql" );
940 //$this->installPrint( print_r( $args, true ));
941 $stmt = $this->prepare( $sql );
943 // start a transaction/enter transaction mode
948 foreach ( $args as $row ) {
949 //$this->installPrint( "Inserting " . print_r( $row, true ));
950 // insert each row into the database
951 $res = $res & $this->execute( $stmt, $row );
953 $this->installPrint( "Last error:" );
954 $this->installPrint( $this->lastError() );
956 // get the last inserted value into a generated column
957 $this->calcInsertId( $table, $primaryKey, $stmt );
961 $olde = error_reporting( 0 );
962 // For future use, we may want to track the number of actual inserts
963 // Right now, insert (all writes) simply return true/false
964 $numrowsinserted = 0;
966 // always return true
969 foreach ( $args as $row ) {
970 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
971 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
974 $this->execute( $stmt, $row );
977 $this->installPrint( "Last error:" );
978 $this->installPrint( $this->lastError() );
980 // get the last inserted value into a generated column
981 $this->calcInsertId( $table, $primaryKey, $stmt );
983 $errNum = $this->lastErrno();
985 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
986 $this->mStmtOptions
);
989 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
990 $this->mStmtOptions
);
995 $olde = error_reporting( $olde );
996 // Set the affected row count for the whole operation
997 $this->mAffectedRows
= $numrowsinserted;
1001 $this->freePrepared( $stmt );
1007 * Given a table name and a hash of columns with values
1008 * Removes primary key columns from the hash where the value is NULL
1010 * @param $table String: name of the table
1011 * @param $args Array of hashes of column names with values
1012 * @return Array: tuple( filtered array of columns, array of primary keys )
1014 private function removeNullPrimaryKeys( $table, $args ) {
1015 $schema = $this->mSchema
;
1016 // find out the primary keys
1017 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1018 strtoupper( $table ));
1021 $row = $this->fetchObject( $keyres );
1023 $row = $this->fetchObject( $keyres ))
1025 $keys[] = strtolower( $row->column_name
);
1027 // remove primary keys
1028 foreach ( $args as $ai => $row ) {
1029 foreach ( $keys as $ki => $key ) {
1030 if ( $row[$key] == null ) {
1031 unset( $row[$key] );
1036 // return modified hash
1037 return array( $args, $keys );
1041 * UPDATE wrapper, takes a condition array and a SET array
1043 * @param $table String: The table to UPDATE
1044 * @param $values An array of values to SET
1045 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1046 * @param $fname String: The Class::Function calling this function
1048 * @param $options An array of UPDATE options, can be one or
1049 * more of IGNORE, LOW_PRIORITY
1052 public function update( $table, $values, $conds, $fname = 'Database::update',
1053 $options = array() )
1055 $table = $this->tableName( $table );
1056 $opts = $this->makeUpdateOptions( $options );
1057 $sql = "UPDATE $opts $table SET "
1058 . $this->makeList( $values, LIST_SET_PREPARED
);
1059 if ( $conds != '*' ) {
1060 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1062 $stmt = $this->prepare( $sql );
1063 $this->installPrint( "UPDATE: " . print_r( $values, TRUE ));
1064 // assuming for now that an array with string keys will work
1065 // if not, convert to simple array first
1066 $result = $this->execute( $stmt, $values );
1067 $this->freePrepared( $stmt );
1073 * DELETE query wrapper
1075 * Use $conds == "*" to delete all rows
1077 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1079 throw new DBUnexpectedError( $this,
1080 'Database::delete() called with no conditions' );
1082 $table = $this->tableName( $table );
1083 $sql = "DELETE FROM $table";
1084 if ( $conds != '*' ) {
1085 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1087 $result = $this->query( $sql, $fname );
1093 * Returns the number of rows affected by the last query or 0
1094 * @return Integer: the number of rows affected by the last query
1096 public function affectedRows() {
1097 if ( !is_null( $this->mAffectedRows
) ) {
1098 // Forced result for simulated queries
1099 return $this->mAffectedRows
;
1101 if( empty( $this->mLastResult
) )
1103 return db2_num_rows( $this->mLastResult
);
1107 * Simulates REPLACE with a DELETE followed by INSERT
1108 * @param $table Object
1109 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1110 * @param $rows Array: rows to insert
1111 * @param $fname String: name of the function for profiling
1114 function replace( $table, $uniqueIndexes, $rows,
1115 $fname = 'DatabaseIbm_db2::replace' )
1117 $table = $this->tableName( $table );
1119 if ( count( $rows )==0 ) {
1124 if ( !is_array( reset( $rows ) ) ) {
1125 $rows = array( $rows );
1128 foreach( $rows as $row ) {
1129 # Delete rows which collide
1130 if ( $uniqueIndexes ) {
1131 $sql = "DELETE FROM $table WHERE ";
1133 foreach ( $uniqueIndexes as $index ) {
1140 if ( is_array( $index ) ) {
1142 foreach ( $index as $col ) {
1148 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1151 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1155 $this->query( $sql, $fname );
1158 # Now insert the row
1159 $sql = "INSERT INTO $table ( "
1160 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1161 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1162 $this->query( $sql, $fname );
1167 * Returns the number of rows in the result set
1168 * Has to be called right after the corresponding select query
1169 * @param $res Object result set
1170 * @return Integer: number of rows
1172 public function numRows( $res ) {
1173 if ( $res instanceof ResultWrapper
) {
1174 $res = $res->result
;
1176 if ( $this->mNumRows
) {
1177 return $this->mNumRows
;
1185 * Moves the row pointer of the result set
1186 * @param $res Object: result set
1187 * @param $row Integer: row number
1188 * @return success or failure
1190 public function dataSeek( $res, $row ) {
1191 if ( $res instanceof ResultWrapper
) {
1192 $res = $res->result
;
1194 return db2_fetch_row( $res, $row );
1198 # Fix notices in Block.php
1202 * Frees memory associated with a statement resource
1203 * @param $res Object: statement resource to free
1204 * @return Boolean success or failure
1206 public function freeResult( $res ) {
1207 if ( $res instanceof ResultWrapper
) {
1208 $res = $res->result
;
1210 if ( !@db2_free_result
( $res ) ) {
1211 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1216 * Returns the number of columns in a resource
1217 * @param $res Object: statement resource
1218 * @return Number of fields/columns in resource
1220 public function numFields( $res ) {
1221 if ( $res instanceof ResultWrapper
) {
1222 $res = $res->result
;
1224 return db2_num_fields( $res );
1228 * Returns the nth column name
1229 * @param $res Object: statement resource
1230 * @param $n Integer: Index of field or column
1231 * @return String name of nth column
1233 public function fieldName( $res, $n ) {
1234 if ( $res instanceof ResultWrapper
) {
1235 $res = $res->result
;
1237 return db2_field_name( $res, $n );
1243 * @param $table Array or string, table name(s) (prefix auto-added)
1244 * @param $vars Array or string, field name(s) to be retrieved
1245 * @param $conds Array or string, condition(s) for WHERE
1246 * @param $fname String: calling function name (use __METHOD__)
1247 * for logs/profiling
1248 * @param $options Associative array of options
1249 * (e.g. array('GROUP BY' => 'page_title')),
1250 * see Database::makeSelectOptions code for list of
1252 * @param $join_conds Associative array of table join conditions (optional)
1253 * (e.g. array( 'page' => array('LEFT JOIN',
1254 * 'page_latest=rev_id') )
1255 * @return Mixed: database result resource for fetch functions or false
1258 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1260 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1263 // We must adjust for offset
1264 if ( isset( $options['LIMIT'] ) ) {
1265 if ( isset ( $options['OFFSET'] ) ) {
1266 $limit = $options['LIMIT'];
1267 $offset = $options['OFFSET'];
1272 // DB2 does not have a proper num_rows() function yet, so we must emulate
1273 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1277 // we want the count
1278 $vars2 = array( 'count( * ) as num_rows' );
1279 // respecting just the limit option
1280 $options2 = array();
1281 if ( isset( $options['LIMIT'] ) ) {
1282 $options2['LIMIT'] = $options['LIMIT'];
1284 // but don't try to emulate for GROUP BY
1285 if ( isset( $options['GROUP BY'] ) ) {
1289 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1291 $obj = $this->fetchObject( $res2 );
1292 $this->mNumRows
= $obj->num_rows
;
1299 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1300 * Has limited support for per-column options (colnum => 'DISTINCT')
1304 * @param $options Associative array of options to be turned into
1305 * an SQL query, valid keys are listed in the function.
1308 function makeSelectOptions( $options ) {
1309 $preLimitTail = $postLimitTail = '';
1312 $noKeyOptions = array();
1313 foreach ( $options as $key => $option ) {
1314 if ( is_numeric( $key ) ) {
1315 $noKeyOptions[$option] = true;
1319 if ( isset( $options['GROUP BY'] ) ) {
1320 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1322 if ( isset( $options['HAVING'] ) ) {
1323 $preLimitTail .= " HAVING {$options['HAVING']}";
1325 if ( isset( $options['ORDER BY'] ) ) {
1326 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1329 if ( isset( $noKeyOptions['DISTINCT'] )
1330 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1332 $startOpts .= 'DISTINCT';
1335 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1339 * Returns link to IBM DB2 free download
1340 * @return string wikitext of a link to the server software's web site
1342 public static function getSoftwareLink() {
1343 return "[http://www.ibm.com/db2/express/ IBM DB2]";
1347 * Get search engine class. All subclasses of this
1348 * need to implement this if they wish to use searching.
1352 public function getSearchEngine() {
1353 return "SearchIBM_DB2";
1357 * Did the last database access fail because of deadlock?
1360 public function wasDeadlock() {
1362 $err = $this->lastErrno();
1364 // This is literal port of the MySQL logic and may be wrong for DB2
1365 case '40001': // sql0911n, Deadlock or timeout, rollback
1366 case '57011': // sql0904n, Resource unavailable, no rollback
1367 case '57033': // sql0913n, Deadlock or timeout, no rollback
1368 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1375 * Ping the server and try to reconnect if it there is no connection
1376 * The connection may be closed and reopened while this happens
1377 * @return Boolean: whether the connection exists
1379 public function ping() {
1380 // db2_ping() doesn't exist
1383 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1384 $this->mPassword
, $this->mServer
, $this->mPort
);
1388 ######################################
1389 # Unimplemented and not applicable
1390 ######################################
1395 public function getStatus( $which="%" ) {
1396 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1401 * @return string $sql
1403 public function limitResultForUpdate( $sql, $num ) {
1404 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1409 * Only useful with fake prepare like in base Database class
1412 public function fillPreparedArg( $matches ) {
1413 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1417 ######################################
1419 ######################################
1422 * Returns information about an index
1423 * If errors are explicitly ignored, returns NULL on failure
1424 * @param $table String: table name
1425 * @param $index String: index name
1426 * @param $fname String: function name for logging and profiling
1427 * @return Object query row in object form
1429 public function indexInfo( $table, $index,
1430 $fname = 'DatabaseIbm_db2::indexExists' )
1432 $table = $this->tableName( $table );
1434 SELECT name as indexname
1435 FROM sysibm.sysindexes si
1436 WHERE si.name='$index' AND si.tbname='$table'
1437 AND sc.tbcreator='$this->mSchema'
1439 $res = $this->query( $sql, $fname );
1443 $row = $this->fetchObject( $res );
1444 if ( $row != null ) {
1451 * Returns an information object on a table column
1452 * @param $table String: table name
1453 * @param $field String: column name
1454 * @return IBM_DB2Field
1456 public function fieldInfo( $table, $field ) {
1457 return IBM_DB2Field
::fromText( $this, $table, $field );
1461 * db2_field_type() wrapper
1462 * @param $res Object: result of executed statement
1463 * @param $index Mixed: number or name of the column
1464 * @return String column type
1466 public function fieldType( $res, $index ) {
1467 if ( $res instanceof ResultWrapper
) {
1468 $res = $res->result
;
1470 return db2_field_type( $res, $index );
1474 * Verifies that an index was created as unique
1475 * @param $table String: table name
1476 * @param $index String: index name
1477 * @param $fname function name for profiling
1480 public function indexUnique ( $table, $index,
1481 $fname = 'Database::indexUnique' )
1483 $table = $this->tableName( $table );
1485 SELECT si.name as indexname
1486 FROM sysibm.sysindexes si
1487 WHERE si.name='$index' AND si.tbname='$table'
1488 AND sc.tbcreator='$this->mSchema'
1489 AND si.uniquerule IN ( 'U', 'P' )
1491 $res = $this->query( $sql, $fname );
1495 if ( $this->fetchObject( $res ) ) {
1503 * Returns the size of a text field, or -1 for "unlimited"
1504 * @param $table String: table name
1505 * @param $field String: column name
1506 * @return Integer: length or -1 for unlimited
1508 public function textFieldSize( $table, $field ) {
1509 $table = $this->tableName( $table );
1511 SELECT length as size
1512 FROM sysibm.syscolumns sc
1513 WHERE sc.name='$field' AND sc.tbname='$table'
1514 AND sc.tbcreator='$this->mSchema'
1516 $res = $this->query( $sql );
1517 $row = $this->fetchObject( $res );
1523 * DELETE where the condition is a join
1524 * @param $delTable String: deleting from this table
1525 * @param $joinTable String: using data from this table
1526 * @param $delVar String: variable in deleteable table
1527 * @param $joinVar String: variable in data table
1528 * @param $conds Array: conditionals for join table
1529 * @param $fname String: function name for profiling
1531 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1532 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1535 throw new DBUnexpectedError( $this,
1536 'Database::deleteJoin() called with empty $conds' );
1539 $delTable = $this->tableName( $delTable );
1540 $joinTable = $this->tableName( $joinTable );
1542 DELETE FROM $delTable
1544 SELECT $joinVar FROM $joinTable
1547 if ( $conds != '*' ) {
1548 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1552 $this->query( $sql, $fname );
1556 * Description is left as an exercise for the reader
1557 * @param $b Mixed: data to be encoded
1558 * @return IBM_DB2Blob
1560 public function encodeBlob( $b ) {
1561 return new IBM_DB2Blob( $b );
1565 * Description is left as an exercise for the reader
1566 * @param $b IBM_DB2Blob: data to be decoded
1569 public function decodeBlob( $b ) {
1574 * Convert into a list of string being concatenated
1575 * @param $stringList Array: strings that need to be joined together
1577 * @return String: joined by the concatenation operator
1579 public function buildConcat( $stringList ) {
1580 // || is equivalent to CONCAT
1581 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1582 return implode( ' || ', $stringList );
1586 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1587 * @param $column String: name of timestamp column
1588 * @return String: SQL code
1590 public function extractUnixEpoch( $column ) {
1592 // see SpecialAncientpages
1595 ######################################
1596 # Prepared statements
1597 ######################################
1600 * Intended to be compatible with the PEAR::DB wrapper functions.
1601 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1603 * ? = scalar value, quoted as necessary
1604 * ! = raw SQL bit (a function for instance)
1605 * & = filename; reads the file and inserts as a blob
1606 * (we don't use this though...)
1607 * @param $sql String: SQL statement with appropriate markers
1608 * @param $func String: Name of the function, for profiling
1609 * @return resource a prepared DB2 SQL statement
1611 public function prepare( $sql, $func = 'DB2::prepare' ) {
1612 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1617 * Frees resources associated with a prepared statement
1618 * @return Boolean success or failure
1620 public function freePrepared( $prepared ) {
1621 return db2_free_stmt( $prepared );
1625 * Execute a prepared query with the various arguments
1626 * @param $prepared String: the prepared sql
1627 * @param $args Mixed: either an array here, or put scalars as varargs
1628 * @return Resource: results object
1630 public function execute( $prepared, $args = null ) {
1631 if( !is_array( $args ) ) {
1633 $args = func_get_args();
1634 array_shift( $args );
1636 $res = db2_execute( $prepared, $args );
1638 $this->installPrint( db2_stmt_errormsg() );
1644 * Prepare & execute an SQL statement, quoting and inserting arguments
1645 * in the appropriate places.
1646 * @param $query String
1649 public function safeQuery( $query, $args = null ) {
1650 // copied verbatim from Database.php
1651 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1652 if( !is_array( $args ) ) {
1654 $args = func_get_args();
1655 array_shift( $args );
1657 $retval = $this->execute( $prepared, $args );
1658 $this->freePrepared( $prepared );
1663 * For faking prepared SQL statements on DBs that don't support
1665 * @param $preparedQuery String: a 'preparable' SQL statement
1666 * @param $args Array of arguments to fill it with
1667 * @return String: executable statement
1669 public function fillPrepared( $preparedQuery, $args ) {
1671 $this->preparedArgs
=& $args;
1673 foreach ( $args as $i => $arg ) {
1674 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1677 return $preparedQuery;
1681 * Switches module between regular and install modes
1683 public function setMode( $mode ) {
1684 $old = $this->mMode
;
1685 $this->mMode
= $mode;
1690 * Bitwise negation of a column or value in SQL
1691 * Same as (~field) in C
1692 * @param $field String
1695 function bitNot( $field ) {
1696 //expecting bit-fields smaller than 4bytes
1697 return "BITNOT( $field )";
1701 * Bitwise AND of two columns or values in SQL
1702 * Same as (fieldLeft & fieldRight) in C
1703 * @param $fieldLeft String
1704 * @param $fieldRight String
1707 function bitAnd( $fieldLeft, $fieldRight ) {
1708 return "BITAND( $fieldLeft, $fieldRight )";
1712 * Bitwise OR of two columns or values in SQL
1713 * Same as (fieldLeft | fieldRight) in C
1714 * @param $fieldLeft String
1715 * @param $fieldRight String
1718 function bitOr( $fieldLeft, $fieldRight ) {
1719 return "BITOR( $fieldLeft, $fieldRight )";
1723 class IBM_DB2Helper
{
1724 public static function makeArray( $maybeArray ) {
1725 if ( !is_array( $maybeArray ) ) {
1726 return array( $maybeArray );