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;
42 $db->addQuotes( $wgDBmwschema ),
43 $db->addQuotes( $table ),
44 $db->addQuotes( $field )
47 $row = $db->fetchObject( $res );
51 $n = new IBM_DB2Field
;
52 $n->type
= $row->typname
;
53 $n->nullable
= ( $row->attnotnull
== 'N' );
55 $n->tablename
= $table;
56 $n->max_length
= $row->attlen
;
61 * @return string column name
63 function name() { return $this->name
; }
66 * @return string table name
68 function tableName() { return $this->tablename
; }
71 * @return string column type
73 function type() { return $this->type
; }
76 * @return bool true or false
78 function nullable() { return $this->nullable
; }
80 * How much can you fit in the column per row?
83 function maxLength() { return $this->max_length
; }
87 * Wrapper around binary large objects
93 public function __construct( $data ) {
97 public function getData() {
101 public function __toString() {
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 /** Database server port */
130 protected $mPort = null;
131 /** Schema for tables, stored procedures, triggers */
132 protected $mSchema = null;
133 /** Whether the schema has been applied in this session */
134 protected $mSchemaSet = false;
135 /** Result of last query */
136 protected $mLastResult = null;
137 /** Number of rows affected by last INSERT/UPDATE/DELETE */
138 protected $mAffectedRows = null;
139 /** Number of rows returned by last SELECT */
140 protected $mNumRows = null;
142 /** Connection config options - see constructor */
143 public $mConnOptions = array();
144 /** Statement config options -- see constructor */
145 public $mStmtOptions = array();
147 /** Default schema */
148 const USE_GLOBAL
= 'mediawiki';
150 /** Option that applies to nothing */
151 const NONE_OPTION
= 0x00;
152 /** Option that applies to connection objects */
153 const CONN_OPTION
= 0x01;
154 /** Option that applies to statement objects */
155 const STMT_OPTION
= 0x02;
157 /** Regular operation mode -- minimal debug messages */
158 const REGULAR_MODE
= 'regular';
159 /** Installation mode -- lots of debug messages */
160 const INSTALL_MODE
= 'install';
162 /** Controls the level of debug message output */
163 protected $mMode = self
::REGULAR_MODE
;
165 /** Last sequence value used for a primary key */
166 protected $mInsertId = null;
168 ######################################
169 # Getters and Setters
170 ######################################
173 * Returns true if this database supports (and uses) cascading deletes
175 function cascadingDeletes() {
180 * Returns true if this database supports (and uses) triggers (e.g. on the
183 function cleanupTriggers() {
188 * Returns true if this database is strict about what can be put into an
190 * Specifically, it uses a NULL value instead of an empty string.
192 function strictIPs() {
197 * Returns true if this database uses timestamps rather than integers
199 function realTimestamps() {
204 * Returns true if this database does an implicit sort when doing GROUP BY
206 function implicitGroupby() {
211 * Returns true if this database does an implicit order by when the column
213 * For example: SELECT page_title FROM page LIMIT 1
215 function implicitOrderby() {
220 * Returns true if this database can do a native search on IP columns
221 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
223 function searchableIPs() {
228 * Returns true if this database can use functional indexes
230 function functionalIndexes() {
235 * Returns a unique string representing the wiki on the server
237 function getWikiID() {
238 if( $this->mSchema
) {
239 return "{$this->mDBname}-{$this->mSchema}";
241 return $this->mDBname
;
249 ######################################
251 ######################################
256 * @param $server String: hostname of database server
257 * @param $user String: username
258 * @param $password String: password
259 * @param $dbName String: database name on the server
260 * @param $failFunction Callback (optional)
261 * @param $flags Integer: database behaviour flags (optional, unused)
262 * @param $schema String
264 public function DatabaseIbm_db2( $server = false, $user = false,
266 $dbName = false, $failFunction = false, $flags = 0,
267 $schema = self
::USE_GLOBAL
)
270 global $wgOut, $wgDBmwschema;
271 # Can't get a reference if it hasn't been set yet
272 if ( !isset( $wgOut ) ) {
275 $this->mOut
=& $wgOut;
276 $this->mFailFunction
= $failFunction;
277 $this->mFlags
= DBO_TRX |
$flags;
279 if ( $schema == self
::USE_GLOBAL
) {
280 $this->mSchema
= $wgDBmwschema;
282 $this->mSchema
= $schema;
285 // configure the connection and statement objects
286 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
287 self
::CONN_OPTION | self
::STMT_OPTION
);
288 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
290 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
293 $this->open( $server, $user, $password, $dbName );
297 * Enables options only if the ibm_db2 extension version supports them
298 * @param $name String: name of the option in the options array
299 * @param $const String: name of the constant holding the right option value
300 * @param $type Integer: whether this is a Connection or Statement otion
302 private function setDB2Option( $name, $const, $type ) {
303 if ( defined( $const ) ) {
304 if ( $type & self
::CONN_OPTION
) {
305 $this->mConnOptions
[$name] = constant( $const );
307 if ( $type & self
::STMT_OPTION
) {
308 $this->mStmtOptions
[$name] = constant( $const );
312 "$const is not defined. ibm_db2 version is likely too low." );
317 * Outputs debug information in the appropriate place
318 * @param $string String: the relevant debug message
320 private function installPrint( $string ) {
321 wfDebug( "$string\n" );
322 if ( $this->mMode
== self
::INSTALL_MODE
) {
323 print "<li><pre>$string</pre></li>";
329 * Opens a database connection and returns it
330 * Closes any existing connection
332 * @param $server String: hostname
333 * @param $user String
334 * @param $password String
335 * @param $dbName String: database name
336 * @return a fresh connection
338 public function open( $server, $user, $password, $dbName ) {
339 // Load the port number
341 wfProfileIn( __METHOD__
);
343 // Load IBM DB2 driver if missing
346 // Test for IBM DB2 support, to avoid suppressed fatal error
347 if ( !function_exists( 'db2_connect' ) ) {
349 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
352 $this->installPrint( $error );
353 $this->reportConnectionError( $error );
356 if ( strlen( $user ) < 1 ) {
360 // Close existing connection
363 $this->mServer
= $server;
364 $this->mPort
= $port = $wgDBport;
365 $this->mUser
= $user;
366 $this->mPassword
= $password;
367 $this->mDBname
= $dbName;
369 $this->openUncataloged( $dbName, $user, $password, $server, $port );
371 // Apply connection config
372 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
373 // Some MediaWiki code is still transaction-less (?).
374 // The strategy is to keep AutoCommit on for that code
375 // but switch it off whenever a transaction is begun.
376 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
378 if ( !$this->mConn
) {
379 $this->installPrint( "DB connection error\n" );
381 "Server: $server, Database: $dbName, User: $user, Password: "
382 . substr( $password, 0, 3 ) . "...\n" );
383 $this->installPrint( $this->lastError() . "\n" );
387 $this->mOpened
= true;
388 $this->applySchema();
390 wfProfileOut( __METHOD__
);
395 * Opens a cataloged database connection, sets mConn
397 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
);
435 * Returns a fresh instance of this class
437 * @param $server String: hostname of database server
438 * @param $user String: username
439 * @param $password String
440 * @param $dbName String: database name on the server
441 * @param $failFunction Callback (optional)
442 * @param $flags Integer: database behaviour flags (optional, unused)
443 * @return DatabaseIbm_db2 object
445 static function newFromParams( $server, $user, $password, $dbName,
446 $failFunction = false, $flags = 0 )
448 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
449 $failFunction, $flags );
453 * Retrieves the most current database error
454 * Forces a database rollback
456 public function lastError() {
457 $connerr = db2_conn_errormsg();
462 $stmterr = db2_stmt_errormsg();
472 * Get the last error number
473 * Return 0 if no error
476 public function lastErrno() {
477 $connerr = db2_conn_error();
481 $stmterr = db2_stmt_error();
489 * Is a database connection open?
492 public function isOpen() { return $this->mOpened
; }
495 * The DBMS-dependent part of query()
496 * @param $sql String: SQL query.
497 * @return object Result object for fetch functions or false on failure
501 public function doQuery( $sql ) {
502 $this->applySchema();
504 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
505 if( $ret == false ) {
506 $error = db2_stmt_errormsg();
507 $this->installPrint( "<pre>$sql</pre>" );
508 $this->installPrint( $error );
509 throw new DBUnexpectedError( $this, 'SQL error: '
510 . htmlspecialchars( $error ) );
512 $this->mLastResult
= $ret;
513 $this->mAffectedRows
= null; // Not calculated until asked for
518 * @return string Version information from the database
520 public function getServerVersion() {
521 $info = db2_server_info( $this->mConn
);
522 return $info->DBMS_VER
;
526 * Queries whether a given table exists
529 public function tableExists( $table ) {
530 $schema = $this->mSchema
;
532 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
533 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
535 $res = $this->query( $sql );
540 // If the table exists, there should be one of it
541 @$row = $this->fetchRow( $res );
543 if ( $count == '1' ||
$count == 1 ) {
551 * Fetch the next row from the given result object, in object form.
552 * Fields can be retrieved with $row->fieldname, with fields acting like
555 * @param $res SQL result object as returned from Database::query(), etc.
556 * @return DB2 row object
557 * @throws DBUnexpectedError Thrown if the database returns an error
559 public function fetchObject( $res ) {
560 if ( $res instanceof ResultWrapper
) {
563 @$row = db2_fetch_object( $res );
564 if( $this->lastErrno() ) {
565 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
566 . htmlspecialchars( $this->lastError() ) );
572 * Fetch the next row from the given result object, in associative array
573 * form. Fields are retrieved with $row['fieldname'].
575 * @param $res SQL result object as returned from Database::query(), etc.
576 * @return DB2 row object
577 * @throws DBUnexpectedError Thrown if the database returns an error
579 public function fetchRow( $res ) {
580 if ( $res instanceof ResultWrapper
) {
583 @$row = db2_fetch_array( $res );
584 if ( $this->lastErrno() ) {
585 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
586 . htmlspecialchars( $this->lastError() ) );
592 * Override if introduced to base Database class
594 public function initial_setup() {
599 * Create tables, stored procedures, and so on
601 public function setup_database() {
603 // TODO: switch to root login if available
605 // Switch into the correct namespace
606 $this->applySchema();
609 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
610 if ( $res !== true ) {
611 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
615 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
616 if ( $res !== true ) {
617 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
619 print '<li>Foreign keys done</li>';
623 // TODO: populate interwiki links
625 if ( $this->lastError() ) {
627 'Errors encountered during table creation -- rolled back' );
628 $this->installPrint( 'Please install again' );
633 } catch ( MWException
$mwe ) {
634 print "<br><pre>$mwe</pre><br>";
640 * Doesn't escape numbers
642 * @param $s String: string to escape
643 * @return escaped string
645 public function addQuotes( $s ) {
646 //$this->installPrint( "DB2::addQuotes( $s )\n" );
647 if ( is_null( $s ) ) {
649 } elseif ( $s instanceof Blob
) {
650 return "'" . $s->fetch( $s ) . "'";
651 } elseif ( $s instanceof IBM_DB2Blob
) {
652 return "'" . $this->decodeBlob( $s ) . "'";
654 $s = $this->strencode( $s );
655 if ( is_numeric( $s ) ) {
663 * Verifies that a DB2 column/field type is numeric
665 * @param $type String: DB2 column type
666 * @return Boolean: true if numeric
668 public function is_numeric_type( $type ) {
669 switch ( strtoupper( $type ) ) {
684 * Alias for addQuotes()
685 * @param $s String: string to escape
686 * @return escaped string
688 public function strencode( $s ) {
689 // Bloody useless function
690 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
691 // But also necessary
692 $s = db2_escape_string( $s );
693 // Wide characters are evil -- some of them look like '
694 $s = utf8_encode( $s );
696 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
697 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
698 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
703 * Switch into the database schema
705 protected function applySchema() {
706 if ( !( $this->mSchemaSet
) ) {
707 $this->mSchemaSet
= true;
709 $this->doQuery( "SET SCHEMA = $this->mSchema" );
715 * Start a transaction (mandatory)
717 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
718 // BEGIN is implicit for DB2
719 // However, it requires that AutoCommit be off.
721 // Some MediaWiki code is still transaction-less (?).
722 // The strategy is to keep AutoCommit on for that code
723 // but switch it off whenever a transaction is begun.
724 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
726 $this->mTrxLevel
= 1;
731 * Must have a preceding begin()
733 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
734 db2_commit( $this->mConn
);
736 // Some MediaWiki code is still transaction-less (?).
737 // The strategy is to keep AutoCommit on for that code
738 // but switch it off whenever a transaction is begun.
739 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
741 $this->mTrxLevel
= 0;
745 * Cancel a transaction
747 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
748 db2_rollback( $this->mConn
);
749 // turn auto-commit back on
750 // not sure if this is appropriate
751 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
752 $this->mTrxLevel
= 0;
756 * Makes an encoded list of strings from an array
758 * LIST_COMMA - comma separated, no field names
759 * LIST_AND - ANDed WHERE clause (without the WHERE)
760 * LIST_OR - ORed WHERE clause (without the WHERE)
761 * LIST_SET - comma separated with field names, like a SET clause
762 * LIST_NAMES - comma separated field names
763 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
765 function makeList( $a, $mode = LIST_COMMA
) {
766 if ( !is_array( $a ) ) {
767 throw new DBUnexpectedError( $this,
768 'DatabaseBase::makeList called with incorrect parameters' );
771 // if this is for a prepared UPDATE statement
772 // (this should be promoted to the parent class
773 // once other databases use prepared statements)
774 if ( $mode == LIST_SET_PREPARED
) {
777 foreach ( $a as $field => $value ) {
779 $list .= ", $field = ?";
781 $list .= "$field = ?";
790 // otherwise, call the usual function
791 return parent
::makeList( $a, $mode );
795 * Construct a LIMIT query with optional offset
796 * This is used for query pages
798 * @param $sql string SQL query we will append the limit too
799 * @param $limit integer the SQL limit
800 * @param $offset integer the SQL offset (default false)
802 public function limitResult( $sql, $limit, $offset=false ) {
803 if( !is_numeric( $limit ) ) {
804 throw new DBUnexpectedError( $this,
805 "Invalid non-numeric limit passed to limitResult()\n" );
808 if ( stripos( $sql, 'where' ) === false ) {
809 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
811 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
814 return "$sql FETCH FIRST $limit ROWS ONLY ";
818 * Handle reserved keyword replacement in table names
820 * @param $name Object
823 public function tableName( $name ) {
824 // we want maximum compatibility with MySQL schema
829 * Generates a timestamp in an insertable format
831 * @param $ts timestamp
832 * @return String: timestamp value
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
871 * @param $table String: sanitized table name
872 * @param $primaryKey Mixed: string name of the primary key
873 * @param $stmt Resource: prepared statement resource
874 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
876 private function calcInsertId( $table, $primaryKey, $stmt ) {
878 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
883 * INSERT wrapper, inserts an array into a table
885 * $args may be a single associative array, or an array of arrays
886 * with numeric keys, for multi-row insert
888 * @param $table String: Name of the table to insert to.
889 * @param $args Array: Items to insert into the table.
890 * @param $fname String: Name of the function, for profiling
891 * @param $options String or Array. Valid options: IGNORE
893 * @return bool Success of insert operation. IGNORE always returns true.
895 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
898 if ( !count( $args ) ) {
901 // get database-specific table name (not used)
902 $table = $this->tableName( $table );
903 // format options as an array
904 $options = IBM_DB2Helper
::makeArray( $options );
905 // format args as an array of arrays
906 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
907 $args = array( $args );
910 // prevent insertion of NULL into primary key columns
911 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
912 // if there's only one primary key
913 // we'll be able to read its value after insertion
915 if ( count( $primaryKeys ) == 1 ) {
916 $primaryKey = $primaryKeys[0];
920 $keys = array_keys( $args[0] );
921 $key_count = count( $keys );
923 // If IGNORE is set, we use savepoints to emulate mysql's behavior
924 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
928 // If we are not in a transaction, we need to be for savepoint trickery
929 if ( !$this->mTrxLevel
) {
933 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
934 if ( $key_count == 1 ) {
937 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
939 //$this->installPrint( "Preparing the following SQL:" );
940 //$this->installPrint( "$sql" );
941 //$this->installPrint( print_r( $args, true ));
942 $stmt = $this->prepare( $sql );
944 // start a transaction/enter transaction mode
949 foreach ( $args as $row ) {
950 //$this->installPrint( "Inserting " . print_r( $row, true ));
951 // insert each row into the database
952 $res = $res & $this->execute( $stmt, $row );
954 $this->installPrint( 'Last error:' );
955 $this->installPrint( $this->lastError() );
957 // get the last inserted value into a generated column
958 $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
);
973 $this->execute( $stmt, $row );
976 $this->installPrint( 'Last error:' );
977 $this->installPrint( $this->lastError() );
979 // get the last inserted value into a generated column
980 $this->calcInsertId( $table, $primaryKey, $stmt );
982 $errNum = $this->lastErrno();
984 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
985 $this->mStmtOptions
);
987 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
988 $this->mStmtOptions
);
993 $olde = error_reporting( $olde );
994 // Set the affected row count for the whole operation
995 $this->mAffectedRows
= $numrowsinserted;
999 $this->freePrepared( $stmt );
1005 * Given a table name and a hash of columns with values
1006 * Removes primary key columns from the hash where the value is NULL
1008 * @param $table String: name of the table
1009 * @param $args Array of hashes of column names with values
1010 * @return Array: tuple( filtered array of columns, array of primary keys )
1012 private function removeNullPrimaryKeys( $table, $args ) {
1013 $schema = $this->mSchema
;
1014 // find out the primary keys
1015 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1016 strtoupper( $table )
1020 $row = $this->fetchObject( $keyres );
1022 $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
) ) {
1104 return db2_num_rows( $this->mLastResult
);
1108 * Simulates REPLACE with a DELETE followed by INSERT
1109 * @param $table Object
1110 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1111 * @param $rows Array: rows to insert
1112 * @param $fname String: name of the function for profiling
1115 function replace( $table, $uniqueIndexes, $rows,
1116 $fname = 'DatabaseIbm_db2::replace' )
1118 $table = $this->tableName( $table );
1120 if ( count( $rows )==0 ) {
1125 if ( !is_array( reset( $rows ) ) ) {
1126 $rows = array( $rows );
1129 foreach( $rows as $row ) {
1130 # Delete rows which collide
1131 if ( $uniqueIndexes ) {
1132 $sql = "DELETE FROM $table WHERE ";
1134 foreach ( $uniqueIndexes as $index ) {
1141 if ( is_array( $index ) ) {
1143 foreach ( $index as $col ) {
1149 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1152 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1156 $this->query( $sql, $fname );
1159 # Now insert the row
1160 $sql = "INSERT INTO $table ( "
1161 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1162 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1163 $this->query( $sql, $fname );
1168 * Returns the number of rows in the result set
1169 * Has to be called right after the corresponding select query
1170 * @param $res Object result set
1171 * @return Integer: number of rows
1173 public function numRows( $res ) {
1174 if ( $res instanceof ResultWrapper
) {
1175 $res = $res->result
;
1177 if ( $this->mNumRows
) {
1178 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
;
1298 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1299 * Has limited support for per-column options (colnum => 'DISTINCT')
1303 * @param $options Associative array of options to be turned into
1304 * an SQL query, valid keys are listed in the function.
1307 function makeSelectOptions( $options ) {
1308 $preLimitTail = $postLimitTail = '';
1311 $noKeyOptions = array();
1312 foreach ( $options as $key => $option ) {
1313 if ( is_numeric( $key ) ) {
1314 $noKeyOptions[$option] = true;
1318 if ( isset( $options['GROUP BY'] ) ) {
1319 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1321 if ( isset( $options['HAVING'] ) ) {
1322 $preLimitTail .= " HAVING {$options['HAVING']}";
1324 if ( isset( $options['ORDER BY'] ) ) {
1325 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1328 if ( isset( $noKeyOptions['DISTINCT'] )
1329 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1331 $startOpts .= 'DISTINCT';
1334 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1338 * Returns link to IBM DB2 free download
1339 * @return String: wikitext of a link to the server software's web site
1341 public static function getSoftwareLink() {
1342 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1346 * Get search engine class. All subclasses of this
1347 * need to implement this if they wish to use searching.
1351 public function getSearchEngine() {
1352 return 'SearchIBM_DB2';
1356 * Did the last database access fail because of deadlock?
1359 public function wasDeadlock() {
1361 $err = $this->lastErrno();
1363 // This is literal port of the MySQL logic and may be wrong for DB2
1364 case '40001': // sql0911n, Deadlock or timeout, rollback
1365 case '57011': // sql0904n, Resource unavailable, no rollback
1366 case '57033': // sql0913n, Deadlock or timeout, no rollback
1367 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1374 * Ping the server and try to reconnect if it there is no connection
1375 * The connection may be closed and reopened while this happens
1376 * @return Boolean: whether the connection exists
1378 public function ping() {
1379 // db2_ping() doesn't exist
1382 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1383 $this->mPassword
, $this->mServer
, $this->mPort
);
1387 ######################################
1388 # Unimplemented and not applicable
1389 ######################################
1394 public function getStatus( $which = '%' ) {
1395 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1400 * @return string $sql
1402 public function limitResultForUpdate( $sql, $num ) {
1403 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1408 * Only useful with fake prepare like in base Database class
1411 public function fillPreparedArg( $matches ) {
1412 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1416 ######################################
1418 ######################################
1421 * Returns information about an index
1422 * If errors are explicitly ignored, returns NULL on failure
1423 * @param $table String: table name
1424 * @param $index String: index name
1425 * @param $fname String: function name for logging and profiling
1426 * @return Object query row in object form
1428 public function indexInfo( $table, $index,
1429 $fname = 'DatabaseIbm_db2::indexExists' )
1431 $table = $this->tableName( $table );
1433 SELECT name as indexname
1434 FROM sysibm.sysindexes si
1435 WHERE si.name='$index' AND si.tbname='$table'
1436 AND sc.tbcreator='$this->mSchema'
1438 $res = $this->query( $sql, $fname );
1442 $row = $this->fetchObject( $res );
1443 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 );