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->mFlags
= DBO_TRX |
$flags;
278 if ( $schema == self
::USE_GLOBAL
) {
279 $this->mSchema
= $wgDBmwschema;
281 $this->mSchema
= $schema;
284 // configure the connection and statement objects
285 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
286 self
::CONN_OPTION | self
::STMT_OPTION
);
287 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
289 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
292 $this->open( $server, $user, $password, $dbName );
296 * Enables options only if the ibm_db2 extension version supports them
297 * @param $name String: name of the option in the options array
298 * @param $const String: name of the constant holding the right option value
299 * @param $type Integer: whether this is a Connection or Statement otion
301 private function setDB2Option( $name, $const, $type ) {
302 if ( defined( $const ) ) {
303 if ( $type & self
::CONN_OPTION
) {
304 $this->mConnOptions
[$name] = constant( $const );
306 if ( $type & self
::STMT_OPTION
) {
307 $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
331 * @param $server String: hostname
332 * @param $user String
333 * @param $password String
334 * @param $dbName String: database name
335 * @return a fresh connection
337 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 ) {
397 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
401 * Opens an uncataloged database connection, sets mConn
403 protected function openUncataloged( $dbName, $user, $password, $server, $port )
405 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
406 $str .= "DATABASE=$dbName;";
407 $str .= "HOSTNAME=$server;";
408 // port was formerly validated to not be 0
409 $str .= "PORT=$port;";
410 $str .= "PROTOCOL=TCPIP;";
411 $str .= "UID=$user;";
412 $str .= "PWD=$password;";
414 @$this->mConn
= db2_pconnect( $str, $user, $password );
418 * Closes a database connection, if it is open
419 * Returns success, true if already closed
421 public function close() {
422 $this->mOpened
= false;
423 if ( $this->mConn
) {
424 if ( $this->trxLevel() > 0 ) {
427 return db2_close( $this->mConn
);
434 * Returns a fresh instance of this class
436 * @param $server String: hostname of database server
437 * @param $user String: username
438 * @param $password String
439 * @param $dbName String: database name on the server
440 * @param $failFunction Callback (optional)
441 * @param $flags Integer: database behaviour flags (optional, unused)
442 * @return DatabaseIbm_db2 object
444 static function newFromParams( $server, $user, $password, $dbName,
445 $failFunction = false, $flags = 0 )
447 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
448 $failFunction, $flags );
452 * Retrieves the most current database error
453 * Forces a database rollback
455 public function lastError() {
456 $connerr = db2_conn_errormsg();
461 $stmterr = db2_stmt_errormsg();
471 * Get the last error number
472 * Return 0 if no error
475 public function lastErrno() {
476 $connerr = db2_conn_error();
480 $stmterr = db2_stmt_error();
488 * Is a database connection open?
491 public function isOpen() { return $this->mOpened
; }
494 * The DBMS-dependent part of query()
495 * @param $sql String: SQL query.
496 * @return object Result object for fetch functions or false on failure
500 public function doQuery( $sql ) {
501 $this->applySchema();
503 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
504 if( $ret == false ) {
505 $error = db2_stmt_errormsg();
506 $this->installPrint( "<pre>$sql</pre>" );
507 $this->installPrint( $error );
508 throw new DBUnexpectedError( $this, 'SQL error: '
509 . htmlspecialchars( $error ) );
511 $this->mLastResult
= $ret;
512 $this->mAffectedRows
= null; // Not calculated until asked for
517 * @return string Version information from the database
519 public function getServerVersion() {
520 $info = db2_server_info( $this->mConn
);
521 return $info->DBMS_VER
;
525 * Queries whether a given table exists
528 public function tableExists( $table ) {
529 $schema = $this->mSchema
;
531 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
532 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
534 $res = $this->query( $sql );
539 // If the table exists, there should be one of it
540 @$row = $this->fetchRow( $res );
542 if ( $count == '1' ||
$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 * Create tables, stored procedures, and so on
593 public function setup_database() {
595 // TODO: switch to root login if available
597 // Switch into the correct namespace
598 $this->applySchema();
601 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
602 if ( $res !== true ) {
603 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
607 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
608 if ( $res !== true ) {
609 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
611 print '<li>Foreign keys done</li>';
615 // TODO: populate interwiki links
617 if ( $this->lastError() ) {
619 'Errors encountered during table creation -- rolled back' );
620 $this->installPrint( 'Please install again' );
625 } catch ( MWException
$mwe ) {
626 print "<br><pre>$mwe</pre><br>";
632 * Doesn't escape numbers
634 * @param $s String: string to escape
635 * @return escaped string
637 public function addQuotes( $s ) {
638 //$this->installPrint( "DB2::addQuotes( $s )\n" );
639 if ( is_null( $s ) ) {
641 } elseif ( $s instanceof Blob
) {
642 return "'" . $s->fetch( $s ) . "'";
643 } elseif ( $s instanceof IBM_DB2Blob
) {
644 return "'" . $this->decodeBlob( $s ) . "'";
646 $s = $this->strencode( $s );
647 if ( is_numeric( $s ) ) {
655 * Verifies that a DB2 column/field type is numeric
657 * @param $type String: DB2 column type
658 * @return Boolean: true if numeric
660 public function is_numeric_type( $type ) {
661 switch ( strtoupper( $type ) ) {
676 * Alias for addQuotes()
677 * @param $s String: string to escape
678 * @return escaped string
680 public function strencode( $s ) {
681 // Bloody useless function
682 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
683 // But also necessary
684 $s = db2_escape_string( $s );
685 // Wide characters are evil -- some of them look like '
686 $s = utf8_encode( $s );
688 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
689 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
690 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
695 * Switch into the database schema
697 protected function applySchema() {
698 if ( !( $this->mSchemaSet
) ) {
699 $this->mSchemaSet
= true;
701 $this->doQuery( "SET SCHEMA = $this->mSchema" );
707 * Start a transaction (mandatory)
709 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
710 // BEGIN is implicit for DB2
711 // However, it requires that AutoCommit be off.
713 // Some MediaWiki code is still transaction-less (?).
714 // The strategy is to keep AutoCommit on for that code
715 // but switch it off whenever a transaction is begun.
716 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
718 $this->mTrxLevel
= 1;
723 * Must have a preceding begin()
725 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
726 db2_commit( $this->mConn
);
728 // Some MediaWiki code is still transaction-less (?).
729 // The strategy is to keep AutoCommit on for that code
730 // but switch it off whenever a transaction is begun.
731 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
733 $this->mTrxLevel
= 0;
737 * Cancel a transaction
739 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
740 db2_rollback( $this->mConn
);
741 // turn auto-commit back on
742 // not sure if this is appropriate
743 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
744 $this->mTrxLevel
= 0;
748 * Makes an encoded list of strings from an array
750 * LIST_COMMA - comma separated, no field names
751 * LIST_AND - ANDed WHERE clause (without the WHERE)
752 * LIST_OR - ORed WHERE clause (without the WHERE)
753 * LIST_SET - comma separated with field names, like a SET clause
754 * LIST_NAMES - comma separated field names
755 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
757 function makeList( $a, $mode = LIST_COMMA
) {
758 if ( !is_array( $a ) ) {
759 throw new DBUnexpectedError( $this,
760 'DatabaseBase::makeList called with incorrect parameters' );
763 // if this is for a prepared UPDATE statement
764 // (this should be promoted to the parent class
765 // once other databases use prepared statements)
766 if ( $mode == LIST_SET_PREPARED
) {
769 foreach ( $a as $field => $value ) {
771 $list .= ", $field = ?";
773 $list .= "$field = ?";
782 // otherwise, call the usual function
783 return parent
::makeList( $a, $mode );
787 * Construct a LIMIT query with optional offset
788 * This is used for query pages
790 * @param $sql string SQL query we will append the limit too
791 * @param $limit integer the SQL limit
792 * @param $offset integer the SQL offset (default false)
794 public function limitResult( $sql, $limit, $offset=false ) {
795 if( !is_numeric( $limit ) ) {
796 throw new DBUnexpectedError( $this,
797 "Invalid non-numeric limit passed to limitResult()\n" );
800 if ( stripos( $sql, 'where' ) === false ) {
801 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
803 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
806 return "$sql FETCH FIRST $limit ROWS ONLY ";
810 * Handle reserved keyword replacement in table names
812 * @param $name Object
815 public function tableName( $name ) {
816 // we want maximum compatibility with MySQL schema
821 * Generates a timestamp in an insertable format
823 * @param $ts timestamp
824 * @return String: timestamp value
826 public function timestamp( $ts = 0 ) {
827 // TS_MW cannot be easily distinguished from an integer
828 return wfTimestamp( TS_DB2
, $ts );
832 * Return the next in a sequence, save the value for retrieval via insertId()
833 * @param $seqName String: name of a defined sequence in the database
834 * @return next value in that sequence
836 public function nextSequenceValue( $seqName ) {
837 // Not using sequences in the primary schema to allow for easier migration
839 // Emulating MySQL behaviour of using NULL to signal that sequences
842 $safeseq = preg_replace( "/'/", "''", $seqName );
843 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
844 $row = $this->fetchRow( $res );
845 $this->mInsertId = $row[0];
846 return $this->mInsertId;
852 * This must be called after nextSequenceVal
853 * @return Last sequence value used as a primary key
855 public function insertId() {
856 return $this->mInsertId
;
860 * Updates the mInsertId property with the value of the last insert
861 * into a generated column
863 * @param $table String: sanitized table name
864 * @param $primaryKey Mixed: string name of the primary key
865 * @param $stmt Resource: prepared statement resource
866 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
868 private function calcInsertId( $table, $primaryKey, $stmt ) {
870 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
875 * INSERT wrapper, inserts an array into a table
877 * $args may be a single associative array, or an array of arrays
878 * with numeric keys, for multi-row insert
880 * @param $table String: Name of the table to insert to.
881 * @param $args Array: Items to insert into the table.
882 * @param $fname String: Name of the function, for profiling
883 * @param $options String or Array. Valid options: IGNORE
885 * @return bool Success of insert operation. IGNORE always returns true.
887 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
890 if ( !count( $args ) ) {
893 // get database-specific table name (not used)
894 $table = $this->tableName( $table );
895 // format options as an array
896 $options = IBM_DB2Helper
::makeArray( $options );
897 // format args as an array of arrays
898 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
899 $args = array( $args );
902 // prevent insertion of NULL into primary key columns
903 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
904 // if there's only one primary key
905 // we'll be able to read its value after insertion
907 if ( count( $primaryKeys ) == 1 ) {
908 $primaryKey = $primaryKeys[0];
912 $keys = array_keys( $args[0] );
913 $key_count = count( $keys );
915 // If IGNORE is set, we use savepoints to emulate mysql's behavior
916 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
920 // If we are not in a transaction, we need to be for savepoint trickery
921 if ( !$this->mTrxLevel
) {
925 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
926 if ( $key_count == 1 ) {
929 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
931 //$this->installPrint( "Preparing the following SQL:" );
932 //$this->installPrint( "$sql" );
933 //$this->installPrint( print_r( $args, true ));
934 $stmt = $this->prepare( $sql );
936 // start a transaction/enter transaction mode
941 foreach ( $args as $row ) {
942 //$this->installPrint( "Inserting " . print_r( $row, true ));
943 // insert each row into the database
944 $res = $res & $this->execute( $stmt, $row );
946 $this->installPrint( 'Last error:' );
947 $this->installPrint( $this->lastError() );
949 // get the last inserted value into a generated column
950 $this->calcInsertId( $table, $primaryKey, $stmt );
953 $olde = error_reporting( 0 );
954 // For future use, we may want to track the number of actual inserts
955 // Right now, insert (all writes) simply return true/false
956 $numrowsinserted = 0;
958 // always return true
961 foreach ( $args as $row ) {
962 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
963 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
965 $this->execute( $stmt, $row );
968 $this->installPrint( 'Last error:' );
969 $this->installPrint( $this->lastError() );
971 // get the last inserted value into a generated column
972 $this->calcInsertId( $table, $primaryKey, $stmt );
974 $errNum = $this->lastErrno();
976 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
977 $this->mStmtOptions
);
979 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
980 $this->mStmtOptions
);
985 $olde = error_reporting( $olde );
986 // Set the affected row count for the whole operation
987 $this->mAffectedRows
= $numrowsinserted;
991 $this->freePrepared( $stmt );
997 * Given a table name and a hash of columns with values
998 * Removes primary key columns from the hash where the value is NULL
1000 * @param $table String: name of the table
1001 * @param $args Array of hashes of column names with values
1002 * @return Array: tuple( filtered array of columns, array of primary keys )
1004 private function removeNullPrimaryKeys( $table, $args ) {
1005 $schema = $this->mSchema
;
1006 // find out the primary keys
1007 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1008 strtoupper( $table )
1012 $row = $this->fetchObject( $keyres );
1014 $row = $this->fetchObject( $keyres )
1017 $keys[] = strtolower( $row->column_name
);
1019 // remove primary keys
1020 foreach ( $args as $ai => $row ) {
1021 foreach ( $keys as $key ) {
1022 if ( $row[$key] == null ) {
1023 unset( $row[$key] );
1028 // return modified hash
1029 return array( $args, $keys );
1033 * UPDATE wrapper, takes a condition array and a SET array
1035 * @param $table String: The table to UPDATE
1036 * @param $values An array of values to SET
1037 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1038 * @param $fname String: The Class::Function calling this function
1040 * @param $options An array of UPDATE options, can be one or
1041 * more of IGNORE, LOW_PRIORITY
1044 public function update( $table, $values, $conds, $fname = 'Database::update',
1045 $options = array() )
1047 $table = $this->tableName( $table );
1048 $opts = $this->makeUpdateOptions( $options );
1049 $sql = "UPDATE $opts $table SET "
1050 . $this->makeList( $values, LIST_SET_PREPARED
);
1051 if ( $conds != '*' ) {
1052 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1054 $stmt = $this->prepare( $sql );
1055 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1056 // assuming for now that an array with string keys will work
1057 // if not, convert to simple array first
1058 $result = $this->execute( $stmt, $values );
1059 $this->freePrepared( $stmt );
1065 * DELETE query wrapper
1067 * Use $conds == "*" to delete all rows
1069 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1071 throw new DBUnexpectedError( $this,
1072 'Database::delete() called with no conditions' );
1074 $table = $this->tableName( $table );
1075 $sql = "DELETE FROM $table";
1076 if ( $conds != '*' ) {
1077 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1079 $result = $this->query( $sql, $fname );
1085 * Returns the number of rows affected by the last query or 0
1086 * @return Integer: the number of rows affected by the last query
1088 public function affectedRows() {
1089 if ( !is_null( $this->mAffectedRows
) ) {
1090 // Forced result for simulated queries
1091 return $this->mAffectedRows
;
1093 if( empty( $this->mLastResult
) ) {
1096 return db2_num_rows( $this->mLastResult
);
1100 * Simulates REPLACE with a DELETE followed by INSERT
1101 * @param $table Object
1102 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1103 * @param $rows Array: rows to insert
1104 * @param $fname String: name of the function for profiling
1107 function replace( $table, $uniqueIndexes, $rows,
1108 $fname = 'DatabaseIbm_db2::replace' )
1110 $table = $this->tableName( $table );
1112 if ( count( $rows )==0 ) {
1117 if ( !is_array( reset( $rows ) ) ) {
1118 $rows = array( $rows );
1121 foreach( $rows as $row ) {
1122 # Delete rows which collide
1123 if ( $uniqueIndexes ) {
1124 $sql = "DELETE FROM $table WHERE ";
1126 foreach ( $uniqueIndexes as $index ) {
1133 if ( is_array( $index ) ) {
1135 foreach ( $index as $col ) {
1141 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1144 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1148 $this->query( $sql, $fname );
1151 # Now insert the row
1152 $sql = "INSERT INTO $table ( "
1153 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1154 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1155 $this->query( $sql, $fname );
1160 * Returns the number of rows in the result set
1161 * Has to be called right after the corresponding select query
1162 * @param $res Object result set
1163 * @return Integer: number of rows
1165 public function numRows( $res ) {
1166 if ( $res instanceof ResultWrapper
) {
1167 $res = $res->result
;
1169 if ( $this->mNumRows
) {
1170 return $this->mNumRows
;
1177 * Moves the row pointer of the result set
1178 * @param $res Object: result set
1179 * @param $row Integer: row number
1180 * @return success or failure
1182 public function dataSeek( $res, $row ) {
1183 if ( $res instanceof ResultWrapper
) {
1184 $res = $res->result
;
1186 return db2_fetch_row( $res, $row );
1190 # Fix notices in Block.php
1194 * Frees memory associated with a statement resource
1195 * @param $res Object: statement resource to free
1196 * @return Boolean success or failure
1198 public function freeResult( $res ) {
1199 if ( $res instanceof ResultWrapper
) {
1200 $res = $res->result
;
1202 if ( !@db2_free_result
( $res ) ) {
1203 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1208 * Returns the number of columns in a resource
1209 * @param $res Object: statement resource
1210 * @return Number of fields/columns in resource
1212 public function numFields( $res ) {
1213 if ( $res instanceof ResultWrapper
) {
1214 $res = $res->result
;
1216 return db2_num_fields( $res );
1220 * Returns the nth column name
1221 * @param $res Object: statement resource
1222 * @param $n Integer: Index of field or column
1223 * @return String name of nth column
1225 public function fieldName( $res, $n ) {
1226 if ( $res instanceof ResultWrapper
) {
1227 $res = $res->result
;
1229 return db2_field_name( $res, $n );
1235 * @param $table Array or string, table name(s) (prefix auto-added)
1236 * @param $vars Array or string, field name(s) to be retrieved
1237 * @param $conds Array or string, condition(s) for WHERE
1238 * @param $fname String: calling function name (use __METHOD__)
1239 * for logs/profiling
1240 * @param $options Associative array of options
1241 * (e.g. array('GROUP BY' => 'page_title')),
1242 * see Database::makeSelectOptions code for list of
1244 * @param $join_conds Associative array of table join conditions (optional)
1245 * (e.g. array( 'page' => array('LEFT JOIN',
1246 * 'page_latest=rev_id') )
1247 * @return Mixed: database result resource for fetch functions or false
1250 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1252 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1255 // We must adjust for offset
1256 if ( isset( $options['LIMIT'] ) ) {
1257 if ( isset ( $options['OFFSET'] ) ) {
1258 $limit = $options['LIMIT'];
1259 $offset = $options['OFFSET'];
1263 // DB2 does not have a proper num_rows() function yet, so we must emulate
1264 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1268 // we want the count
1269 $vars2 = array( 'count( * ) as num_rows' );
1270 // respecting just the limit option
1271 $options2 = array();
1272 if ( isset( $options['LIMIT'] ) ) {
1273 $options2['LIMIT'] = $options['LIMIT'];
1275 // but don't try to emulate for GROUP BY
1276 if ( isset( $options['GROUP BY'] ) ) {
1280 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1282 $obj = $this->fetchObject( $res2 );
1283 $this->mNumRows
= $obj->num_rows
;
1289 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1290 * Has limited support for per-column options (colnum => 'DISTINCT')
1294 * @param $options Associative array of options to be turned into
1295 * an SQL query, valid keys are listed in the function.
1298 function makeSelectOptions( $options ) {
1299 $preLimitTail = $postLimitTail = '';
1302 $noKeyOptions = array();
1303 foreach ( $options as $key => $option ) {
1304 if ( is_numeric( $key ) ) {
1305 $noKeyOptions[$option] = true;
1309 if ( isset( $options['GROUP BY'] ) ) {
1310 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1312 if ( isset( $options['HAVING'] ) ) {
1313 $preLimitTail .= " HAVING {$options['HAVING']}";
1315 if ( isset( $options['ORDER BY'] ) ) {
1316 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1319 if ( isset( $noKeyOptions['DISTINCT'] )
1320 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1322 $startOpts .= 'DISTINCT';
1325 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1329 * Returns link to IBM DB2 free download
1330 * @return String: wikitext of a link to the server software's web site
1332 public static function getSoftwareLink() {
1333 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1337 * Get search engine class. All subclasses of this
1338 * need to implement this if they wish to use searching.
1342 public function getSearchEngine() {
1343 return 'SearchIBM_DB2';
1347 * Did the last database access fail because of deadlock?
1350 public function wasDeadlock() {
1352 $err = $this->lastErrno();
1354 // This is literal port of the MySQL logic and may be wrong for DB2
1355 case '40001': // sql0911n, Deadlock or timeout, rollback
1356 case '57011': // sql0904n, Resource unavailable, no rollback
1357 case '57033': // sql0913n, Deadlock or timeout, no rollback
1358 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1365 * Ping the server and try to reconnect if it there is no connection
1366 * The connection may be closed and reopened while this happens
1367 * @return Boolean: whether the connection exists
1369 public function ping() {
1370 // db2_ping() doesn't exist
1373 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1374 $this->mPassword
, $this->mServer
, $this->mPort
);
1378 ######################################
1379 # Unimplemented and not applicable
1380 ######################################
1385 public function getStatus( $which = '%' ) {
1386 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1391 * @return string $sql
1393 public function limitResultForUpdate( $sql, $num ) {
1394 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1399 * Only useful with fake prepare like in base Database class
1402 public function fillPreparedArg( $matches ) {
1403 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1407 ######################################
1409 ######################################
1412 * Returns information about an index
1413 * If errors are explicitly ignored, returns NULL on failure
1414 * @param $table String: table name
1415 * @param $index String: index name
1416 * @param $fname String: function name for logging and profiling
1417 * @return Object query row in object form
1419 public function indexInfo( $table, $index,
1420 $fname = 'DatabaseIbm_db2::indexExists' )
1422 $table = $this->tableName( $table );
1424 SELECT name as indexname
1425 FROM sysibm.sysindexes si
1426 WHERE si.name='$index' AND si.tbname='$table'
1427 AND sc.tbcreator='$this->mSchema'
1429 $res = $this->query( $sql, $fname );
1433 $row = $this->fetchObject( $res );
1434 if ( $row != null ) {
1442 * Returns an information object on a table column
1443 * @param $table String: table name
1444 * @param $field String: column name
1445 * @return IBM_DB2Field
1447 public function fieldInfo( $table, $field ) {
1448 return IBM_DB2Field
::fromText( $this, $table, $field );
1452 * db2_field_type() wrapper
1453 * @param $res Object: result of executed statement
1454 * @param $index Mixed: number or name of the column
1455 * @return String column type
1457 public function fieldType( $res, $index ) {
1458 if ( $res instanceof ResultWrapper
) {
1459 $res = $res->result
;
1461 return db2_field_type( $res, $index );
1465 * Verifies that an index was created as unique
1466 * @param $table String: table name
1467 * @param $index String: index name
1468 * @param $fname function name for profiling
1471 public function indexUnique ( $table, $index,
1472 $fname = 'Database::indexUnique' )
1474 $table = $this->tableName( $table );
1476 SELECT si.name as indexname
1477 FROM sysibm.sysindexes si
1478 WHERE si.name='$index' AND si.tbname='$table'
1479 AND sc.tbcreator='$this->mSchema'
1480 AND si.uniquerule IN ( 'U', 'P' )
1482 $res = $this->query( $sql, $fname );
1486 if ( $this->fetchObject( $res ) ) {
1494 * Returns the size of a text field, or -1 for "unlimited"
1495 * @param $table String: table name
1496 * @param $field String: column name
1497 * @return Integer: length or -1 for unlimited
1499 public function textFieldSize( $table, $field ) {
1500 $table = $this->tableName( $table );
1502 SELECT length as size
1503 FROM sysibm.syscolumns sc
1504 WHERE sc.name='$field' AND sc.tbname='$table'
1505 AND sc.tbcreator='$this->mSchema'
1507 $res = $this->query( $sql );
1508 $row = $this->fetchObject( $res );
1514 * DELETE where the condition is a join
1515 * @param $delTable String: deleting from this table
1516 * @param $joinTable String: using data from this table
1517 * @param $delVar String: variable in deleteable table
1518 * @param $joinVar String: variable in data table
1519 * @param $conds Array: conditionals for join table
1520 * @param $fname String: function name for profiling
1522 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1523 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1526 throw new DBUnexpectedError( $this,
1527 'Database::deleteJoin() called with empty $conds' );
1530 $delTable = $this->tableName( $delTable );
1531 $joinTable = $this->tableName( $joinTable );
1533 DELETE FROM $delTable
1535 SELECT $joinVar FROM $joinTable
1538 if ( $conds != '*' ) {
1539 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1543 $this->query( $sql, $fname );
1547 * Description is left as an exercise for the reader
1548 * @param $b Mixed: data to be encoded
1549 * @return IBM_DB2Blob
1551 public function encodeBlob( $b ) {
1552 return new IBM_DB2Blob( $b );
1556 * Description is left as an exercise for the reader
1557 * @param $b IBM_DB2Blob: data to be decoded
1560 public function decodeBlob( $b ) {
1565 * Convert into a list of string being concatenated
1566 * @param $stringList Array: strings that need to be joined together
1568 * @return String: joined by the concatenation operator
1570 public function buildConcat( $stringList ) {
1571 // || is equivalent to CONCAT
1572 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1573 return implode( ' || ', $stringList );
1577 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1578 * @param $column String: name of timestamp column
1579 * @return String: SQL code
1581 public function extractUnixEpoch( $column ) {
1583 // see SpecialAncientpages
1586 ######################################
1587 # Prepared statements
1588 ######################################
1591 * Intended to be compatible with the PEAR::DB wrapper functions.
1592 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1594 * ? = scalar value, quoted as necessary
1595 * ! = raw SQL bit (a function for instance)
1596 * & = filename; reads the file and inserts as a blob
1597 * (we don't use this though...)
1598 * @param $sql String: SQL statement with appropriate markers
1599 * @param $func String: Name of the function, for profiling
1600 * @return resource a prepared DB2 SQL statement
1602 public function prepare( $sql, $func = 'DB2::prepare' ) {
1603 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1608 * Frees resources associated with a prepared statement
1609 * @return Boolean success or failure
1611 public function freePrepared( $prepared ) {
1612 return db2_free_stmt( $prepared );
1616 * Execute a prepared query with the various arguments
1617 * @param $prepared String: the prepared sql
1618 * @param $args Mixed: either an array here, or put scalars as varargs
1619 * @return Resource: results object
1621 public function execute( $prepared, $args = null ) {
1622 if( !is_array( $args ) ) {
1624 $args = func_get_args();
1625 array_shift( $args );
1627 $res = db2_execute( $prepared, $args );
1629 $this->installPrint( db2_stmt_errormsg() );
1635 * Prepare & execute an SQL statement, quoting and inserting arguments
1636 * in the appropriate places.
1637 * @param $query String
1640 public function safeQuery( $query, $args = null ) {
1641 // copied verbatim from Database.php
1642 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1643 if( !is_array( $args ) ) {
1645 $args = func_get_args();
1646 array_shift( $args );
1648 $retval = $this->execute( $prepared, $args );
1649 $this->freePrepared( $prepared );
1654 * For faking prepared SQL statements on DBs that don't support
1656 * @param $preparedQuery String: a 'preparable' SQL statement
1657 * @param $args Array of arguments to fill it with
1658 * @return String: executable statement
1660 public function fillPrepared( $preparedQuery, $args ) {
1662 $this->preparedArgs
=& $args;
1664 foreach ( $args as $i => $arg ) {
1665 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1668 return $preparedQuery;
1672 * Switches module between regular and install modes
1674 public function setMode( $mode ) {
1675 $old = $this->mMode
;
1676 $this->mMode
= $mode;
1681 * Bitwise negation of a column or value in SQL
1682 * Same as (~field) in C
1683 * @param $field String
1686 function bitNot( $field ) {
1687 // expecting bit-fields smaller than 4bytes
1688 return "BITNOT( $field )";
1692 * Bitwise AND of two columns or values in SQL
1693 * Same as (fieldLeft & fieldRight) in C
1694 * @param $fieldLeft String
1695 * @param $fieldRight String
1698 function bitAnd( $fieldLeft, $fieldRight ) {
1699 return "BITAND( $fieldLeft, $fieldRight )";
1703 * Bitwise OR of two columns or values in SQL
1704 * Same as (fieldLeft | fieldRight) in C
1705 * @param $fieldLeft String
1706 * @param $fieldRight String
1709 function bitOr( $fieldLeft, $fieldRight ) {
1710 return "BITOR( $fieldLeft, $fieldRight )";
1714 class IBM_DB2Helper
{
1715 public static function makeArray( $maybeArray ) {
1716 if ( !is_array( $maybeArray ) ) {
1717 return array( $maybeArray );