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 * Create tables, stored procedures, and so on
594 public function setup_database() {
596 // TODO: switch to root login if available
598 // Switch into the correct namespace
599 $this->applySchema();
602 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
603 if ( $res !== true ) {
604 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
608 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
609 if ( $res !== true ) {
610 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
612 print '<li>Foreign keys done</li>';
616 // TODO: populate interwiki links
618 if ( $this->lastError() ) {
620 'Errors encountered during table creation -- rolled back' );
621 $this->installPrint( 'Please install again' );
626 } catch ( MWException
$mwe ) {
627 print "<br><pre>$mwe</pre><br>";
633 * Doesn't escape numbers
635 * @param $s String: string to escape
636 * @return escaped string
638 public function addQuotes( $s ) {
639 //$this->installPrint( "DB2::addQuotes( $s )\n" );
640 if ( is_null( $s ) ) {
642 } elseif ( $s instanceof Blob
) {
643 return "'" . $s->fetch( $s ) . "'";
644 } elseif ( $s instanceof IBM_DB2Blob
) {
645 return "'" . $this->decodeBlob( $s ) . "'";
647 $s = $this->strencode( $s );
648 if ( is_numeric( $s ) ) {
656 * Verifies that a DB2 column/field type is numeric
658 * @param $type String: DB2 column type
659 * @return Boolean: true if numeric
661 public function is_numeric_type( $type ) {
662 switch ( strtoupper( $type ) ) {
677 * Alias for addQuotes()
678 * @param $s String: string to escape
679 * @return escaped string
681 public function strencode( $s ) {
682 // Bloody useless function
683 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
684 // But also necessary
685 $s = db2_escape_string( $s );
686 // Wide characters are evil -- some of them look like '
687 $s = utf8_encode( $s );
689 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
690 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
691 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
696 * Switch into the database schema
698 protected function applySchema() {
699 if ( !( $this->mSchemaSet
) ) {
700 $this->mSchemaSet
= true;
702 $this->doQuery( "SET SCHEMA = $this->mSchema" );
708 * Start a transaction (mandatory)
710 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
711 // BEGIN is implicit for DB2
712 // However, it requires that AutoCommit be off.
714 // Some MediaWiki code is still transaction-less (?).
715 // The strategy is to keep AutoCommit on for that code
716 // but switch it off whenever a transaction is begun.
717 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
719 $this->mTrxLevel
= 1;
724 * Must have a preceding begin()
726 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
727 db2_commit( $this->mConn
);
729 // Some MediaWiki code is still transaction-less (?).
730 // The strategy is to keep AutoCommit on for that code
731 // but switch it off whenever a transaction is begun.
732 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
734 $this->mTrxLevel
= 0;
738 * Cancel a transaction
740 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
741 db2_rollback( $this->mConn
);
742 // turn auto-commit back on
743 // not sure if this is appropriate
744 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
745 $this->mTrxLevel
= 0;
749 * Makes an encoded list of strings from an array
751 * LIST_COMMA - comma separated, no field names
752 * LIST_AND - ANDed WHERE clause (without the WHERE)
753 * LIST_OR - ORed WHERE clause (without the WHERE)
754 * LIST_SET - comma separated with field names, like a SET clause
755 * LIST_NAMES - comma separated field names
756 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
758 function makeList( $a, $mode = LIST_COMMA
) {
759 if ( !is_array( $a ) ) {
760 throw new DBUnexpectedError( $this,
761 'DatabaseBase::makeList called with incorrect parameters' );
764 // if this is for a prepared UPDATE statement
765 // (this should be promoted to the parent class
766 // once other databases use prepared statements)
767 if ( $mode == LIST_SET_PREPARED
) {
770 foreach ( $a as $field => $value ) {
772 $list .= ", $field = ?";
774 $list .= "$field = ?";
783 // otherwise, call the usual function
784 return parent
::makeList( $a, $mode );
788 * Construct a LIMIT query with optional offset
789 * This is used for query pages
791 * @param $sql string SQL query we will append the limit too
792 * @param $limit integer the SQL limit
793 * @param $offset integer the SQL offset (default false)
795 public function limitResult( $sql, $limit, $offset=false ) {
796 if( !is_numeric( $limit ) ) {
797 throw new DBUnexpectedError( $this,
798 "Invalid non-numeric limit passed to limitResult()\n" );
801 if ( stripos( $sql, 'where' ) === false ) {
802 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
804 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
807 return "$sql FETCH FIRST $limit ROWS ONLY ";
811 * Handle reserved keyword replacement in table names
813 * @param $name Object
816 public function tableName( $name ) {
817 // we want maximum compatibility with MySQL schema
822 * Generates a timestamp in an insertable format
824 * @param $ts timestamp
825 * @return String: timestamp value
827 public function timestamp( $ts = 0 ) {
828 // TS_MW cannot be easily distinguished from an integer
829 return wfTimestamp( TS_DB2
, $ts );
833 * Return the next in a sequence, save the value for retrieval via insertId()
834 * @param $seqName String: name of a defined sequence in the database
835 * @return next value in that sequence
837 public function nextSequenceValue( $seqName ) {
838 // Not using sequences in the primary schema to allow for easier migration
840 // Emulating MySQL behaviour of using NULL to signal that sequences
843 $safeseq = preg_replace( "/'/", "''", $seqName );
844 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
845 $row = $this->fetchRow( $res );
846 $this->mInsertId = $row[0];
847 return $this->mInsertId;
853 * This must be called after nextSequenceVal
854 * @return Last sequence value used as a primary key
856 public function insertId() {
857 return $this->mInsertId
;
861 * Updates the mInsertId property with the value of the last insert
862 * into a generated column
864 * @param $table String: sanitized table name
865 * @param $primaryKey Mixed: string name of the primary key
866 * @param $stmt Resource: prepared statement resource
867 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
869 private function calcInsertId( $table, $primaryKey, $stmt ) {
871 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
876 * INSERT wrapper, inserts an array into a table
878 * $args may be a single associative array, or an array of arrays
879 * with numeric keys, for multi-row insert
881 * @param $table String: Name of the table to insert to.
882 * @param $args Array: Items to insert into the table.
883 * @param $fname String: Name of the function, for profiling
884 * @param $options String or Array. Valid options: IGNORE
886 * @return bool Success of insert operation. IGNORE always returns true.
888 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
891 if ( !count( $args ) ) {
894 // get database-specific table name (not used)
895 $table = $this->tableName( $table );
896 // format options as an array
897 $options = IBM_DB2Helper
::makeArray( $options );
898 // format args as an array of arrays
899 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
900 $args = array( $args );
903 // prevent insertion of NULL into primary key columns
904 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
905 // if there's only one primary key
906 // we'll be able to read its value after insertion
908 if ( count( $primaryKeys ) == 1 ) {
909 $primaryKey = $primaryKeys[0];
913 $keys = array_keys( $args[0] );
914 $key_count = count( $keys );
916 // If IGNORE is set, we use savepoints to emulate mysql's behavior
917 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
921 // If we are not in a transaction, we need to be for savepoint trickery
922 if ( !$this->mTrxLevel
) {
926 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
927 if ( $key_count == 1 ) {
930 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
932 //$this->installPrint( "Preparing the following SQL:" );
933 //$this->installPrint( "$sql" );
934 //$this->installPrint( print_r( $args, true ));
935 $stmt = $this->prepare( $sql );
937 // start a transaction/enter transaction mode
942 foreach ( $args as $row ) {
943 //$this->installPrint( "Inserting " . print_r( $row, true ));
944 // insert each row into the database
945 $res = $res & $this->execute( $stmt, $row );
947 $this->installPrint( 'Last error:' );
948 $this->installPrint( $this->lastError() );
950 // get the last inserted value into a generated column
951 $this->calcInsertId( $table, $primaryKey, $stmt );
954 $olde = error_reporting( 0 );
955 // For future use, we may want to track the number of actual inserts
956 // Right now, insert (all writes) simply return true/false
957 $numrowsinserted = 0;
959 // always return true
962 foreach ( $args as $row ) {
963 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
964 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
966 $this->execute( $stmt, $row );
969 $this->installPrint( 'Last error:' );
970 $this->installPrint( $this->lastError() );
972 // get the last inserted value into a generated column
973 $this->calcInsertId( $table, $primaryKey, $stmt );
975 $errNum = $this->lastErrno();
977 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
978 $this->mStmtOptions
);
980 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
981 $this->mStmtOptions
);
986 $olde = error_reporting( $olde );
987 // Set the affected row count for the whole operation
988 $this->mAffectedRows
= $numrowsinserted;
992 $this->freePrepared( $stmt );
998 * Given a table name and a hash of columns with values
999 * Removes primary key columns from the hash where the value is NULL
1001 * @param $table String: name of the table
1002 * @param $args Array of hashes of column names with values
1003 * @return Array: tuple( filtered array of columns, array of primary keys )
1005 private function removeNullPrimaryKeys( $table, $args ) {
1006 $schema = $this->mSchema
;
1007 // find out the primary keys
1008 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1009 strtoupper( $table )
1013 $row = $this->fetchObject( $keyres );
1015 $row = $this->fetchObject( $keyres )
1018 $keys[] = strtolower( $row->column_name
);
1020 // remove primary keys
1021 foreach ( $args as $ai => $row ) {
1022 foreach ( $keys as $ki => $key ) {
1023 if ( $row[$key] == null ) {
1024 unset( $row[$key] );
1029 // return modified hash
1030 return array( $args, $keys );
1034 * UPDATE wrapper, takes a condition array and a SET array
1036 * @param $table String: The table to UPDATE
1037 * @param $values An array of values to SET
1038 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1039 * @param $fname String: The Class::Function calling this function
1041 * @param $options An array of UPDATE options, can be one or
1042 * more of IGNORE, LOW_PRIORITY
1045 public function update( $table, $values, $conds, $fname = 'Database::update',
1046 $options = array() )
1048 $table = $this->tableName( $table );
1049 $opts = $this->makeUpdateOptions( $options );
1050 $sql = "UPDATE $opts $table SET "
1051 . $this->makeList( $values, LIST_SET_PREPARED
);
1052 if ( $conds != '*' ) {
1053 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1055 $stmt = $this->prepare( $sql );
1056 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1057 // assuming for now that an array with string keys will work
1058 // if not, convert to simple array first
1059 $result = $this->execute( $stmt, $values );
1060 $this->freePrepared( $stmt );
1066 * DELETE query wrapper
1068 * Use $conds == "*" to delete all rows
1070 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1072 throw new DBUnexpectedError( $this,
1073 'Database::delete() called with no conditions' );
1075 $table = $this->tableName( $table );
1076 $sql = "DELETE FROM $table";
1077 if ( $conds != '*' ) {
1078 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1080 $result = $this->query( $sql, $fname );
1086 * Returns the number of rows affected by the last query or 0
1087 * @return Integer: the number of rows affected by the last query
1089 public function affectedRows() {
1090 if ( !is_null( $this->mAffectedRows
) ) {
1091 // Forced result for simulated queries
1092 return $this->mAffectedRows
;
1094 if( empty( $this->mLastResult
) ) {
1097 return db2_num_rows( $this->mLastResult
);
1101 * Simulates REPLACE with a DELETE followed by INSERT
1102 * @param $table Object
1103 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1104 * @param $rows Array: rows to insert
1105 * @param $fname String: name of the function for profiling
1108 function replace( $table, $uniqueIndexes, $rows,
1109 $fname = 'DatabaseIbm_db2::replace' )
1111 $table = $this->tableName( $table );
1113 if ( count( $rows )==0 ) {
1118 if ( !is_array( reset( $rows ) ) ) {
1119 $rows = array( $rows );
1122 foreach( $rows as $row ) {
1123 # Delete rows which collide
1124 if ( $uniqueIndexes ) {
1125 $sql = "DELETE FROM $table WHERE ";
1127 foreach ( $uniqueIndexes as $index ) {
1134 if ( is_array( $index ) ) {
1136 foreach ( $index as $col ) {
1142 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1145 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1149 $this->query( $sql, $fname );
1152 # Now insert the row
1153 $sql = "INSERT INTO $table ( "
1154 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1155 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1156 $this->query( $sql, $fname );
1161 * Returns the number of rows in the result set
1162 * Has to be called right after the corresponding select query
1163 * @param $res Object result set
1164 * @return Integer: number of rows
1166 public function numRows( $res ) {
1167 if ( $res instanceof ResultWrapper
) {
1168 $res = $res->result
;
1170 if ( $this->mNumRows
) {
1171 return $this->mNumRows
;
1178 * Moves the row pointer of the result set
1179 * @param $res Object: result set
1180 * @param $row Integer: row number
1181 * @return success or failure
1183 public function dataSeek( $res, $row ) {
1184 if ( $res instanceof ResultWrapper
) {
1185 $res = $res->result
;
1187 return db2_fetch_row( $res, $row );
1191 # Fix notices in Block.php
1195 * Frees memory associated with a statement resource
1196 * @param $res Object: statement resource to free
1197 * @return Boolean success or failure
1199 public function freeResult( $res ) {
1200 if ( $res instanceof ResultWrapper
) {
1201 $res = $res->result
;
1203 if ( !@db2_free_result
( $res ) ) {
1204 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1209 * Returns the number of columns in a resource
1210 * @param $res Object: statement resource
1211 * @return Number of fields/columns in resource
1213 public function numFields( $res ) {
1214 if ( $res instanceof ResultWrapper
) {
1215 $res = $res->result
;
1217 return db2_num_fields( $res );
1221 * Returns the nth column name
1222 * @param $res Object: statement resource
1223 * @param $n Integer: Index of field or column
1224 * @return String name of nth column
1226 public function fieldName( $res, $n ) {
1227 if ( $res instanceof ResultWrapper
) {
1228 $res = $res->result
;
1230 return db2_field_name( $res, $n );
1236 * @param $table Array or string, table name(s) (prefix auto-added)
1237 * @param $vars Array or string, field name(s) to be retrieved
1238 * @param $conds Array or string, condition(s) for WHERE
1239 * @param $fname String: calling function name (use __METHOD__)
1240 * for logs/profiling
1241 * @param $options Associative array of options
1242 * (e.g. array('GROUP BY' => 'page_title')),
1243 * see Database::makeSelectOptions code for list of
1245 * @param $join_conds Associative array of table join conditions (optional)
1246 * (e.g. array( 'page' => array('LEFT JOIN',
1247 * 'page_latest=rev_id') )
1248 * @return Mixed: database result resource for fetch functions or false
1251 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1253 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1256 // We must adjust for offset
1257 if ( isset( $options['LIMIT'] ) ) {
1258 if ( isset ( $options['OFFSET'] ) ) {
1259 $limit = $options['LIMIT'];
1260 $offset = $options['OFFSET'];
1265 // DB2 does not have a proper num_rows() function yet, so we must emulate
1266 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1270 // we want the count
1271 $vars2 = array( 'count( * ) as num_rows' );
1272 // respecting just the limit option
1273 $options2 = array();
1274 if ( isset( $options['LIMIT'] ) ) {
1275 $options2['LIMIT'] = $options['LIMIT'];
1277 // but don't try to emulate for GROUP BY
1278 if ( isset( $options['GROUP BY'] ) ) {
1282 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1284 $obj = $this->fetchObject( $res2 );
1285 $this->mNumRows
= $obj->num_rows
;
1291 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1292 * Has limited support for per-column options (colnum => 'DISTINCT')
1296 * @param $options Associative array of options to be turned into
1297 * an SQL query, valid keys are listed in the function.
1300 function makeSelectOptions( $options ) {
1301 $preLimitTail = $postLimitTail = '';
1304 $noKeyOptions = array();
1305 foreach ( $options as $key => $option ) {
1306 if ( is_numeric( $key ) ) {
1307 $noKeyOptions[$option] = true;
1311 if ( isset( $options['GROUP BY'] ) ) {
1312 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1314 if ( isset( $options['HAVING'] ) ) {
1315 $preLimitTail .= " HAVING {$options['HAVING']}";
1317 if ( isset( $options['ORDER BY'] ) ) {
1318 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1321 if ( isset( $noKeyOptions['DISTINCT'] )
1322 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1324 $startOpts .= 'DISTINCT';
1327 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1331 * Returns link to IBM DB2 free download
1332 * @return String: wikitext of a link to the server software's web site
1334 public static function getSoftwareLink() {
1335 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1339 * Get search engine class. All subclasses of this
1340 * need to implement this if they wish to use searching.
1344 public function getSearchEngine() {
1345 return 'SearchIBM_DB2';
1349 * Did the last database access fail because of deadlock?
1352 public function wasDeadlock() {
1354 $err = $this->lastErrno();
1356 // This is literal port of the MySQL logic and may be wrong for DB2
1357 case '40001': // sql0911n, Deadlock or timeout, rollback
1358 case '57011': // sql0904n, Resource unavailable, no rollback
1359 case '57033': // sql0913n, Deadlock or timeout, no rollback
1360 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1367 * Ping the server and try to reconnect if it there is no connection
1368 * The connection may be closed and reopened while this happens
1369 * @return Boolean: whether the connection exists
1371 public function ping() {
1372 // db2_ping() doesn't exist
1375 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1376 $this->mPassword
, $this->mServer
, $this->mPort
);
1380 ######################################
1381 # Unimplemented and not applicable
1382 ######################################
1387 public function getStatus( $which = '%' ) {
1388 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1393 * @return string $sql
1395 public function limitResultForUpdate( $sql, $num ) {
1396 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1401 * Only useful with fake prepare like in base Database class
1404 public function fillPreparedArg( $matches ) {
1405 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1409 ######################################
1411 ######################################
1414 * Returns information about an index
1415 * If errors are explicitly ignored, returns NULL on failure
1416 * @param $table String: table name
1417 * @param $index String: index name
1418 * @param $fname String: function name for logging and profiling
1419 * @return Object query row in object form
1421 public function indexInfo( $table, $index,
1422 $fname = 'DatabaseIbm_db2::indexExists' )
1424 $table = $this->tableName( $table );
1426 SELECT name as indexname
1427 FROM sysibm.sysindexes si
1428 WHERE si.name='$index' AND si.tbname='$table'
1429 AND sc.tbcreator='$this->mSchema'
1431 $res = $this->query( $sql, $fname );
1435 $row = $this->fetchObject( $res );
1436 if ( $row != null ) {
1444 * Returns an information object on a table column
1445 * @param $table String: table name
1446 * @param $field String: column name
1447 * @return IBM_DB2Field
1449 public function fieldInfo( $table, $field ) {
1450 return IBM_DB2Field
::fromText( $this, $table, $field );
1454 * db2_field_type() wrapper
1455 * @param $res Object: result of executed statement
1456 * @param $index Mixed: number or name of the column
1457 * @return String column type
1459 public function fieldType( $res, $index ) {
1460 if ( $res instanceof ResultWrapper
) {
1461 $res = $res->result
;
1463 return db2_field_type( $res, $index );
1467 * Verifies that an index was created as unique
1468 * @param $table String: table name
1469 * @param $index String: index name
1470 * @param $fname function name for profiling
1473 public function indexUnique ( $table, $index,
1474 $fname = 'Database::indexUnique' )
1476 $table = $this->tableName( $table );
1478 SELECT si.name as indexname
1479 FROM sysibm.sysindexes si
1480 WHERE si.name='$index' AND si.tbname='$table'
1481 AND sc.tbcreator='$this->mSchema'
1482 AND si.uniquerule IN ( 'U', 'P' )
1484 $res = $this->query( $sql, $fname );
1488 if ( $this->fetchObject( $res ) ) {
1496 * Returns the size of a text field, or -1 for "unlimited"
1497 * @param $table String: table name
1498 * @param $field String: column name
1499 * @return Integer: length or -1 for unlimited
1501 public function textFieldSize( $table, $field ) {
1502 $table = $this->tableName( $table );
1504 SELECT length as size
1505 FROM sysibm.syscolumns sc
1506 WHERE sc.name='$field' AND sc.tbname='$table'
1507 AND sc.tbcreator='$this->mSchema'
1509 $res = $this->query( $sql );
1510 $row = $this->fetchObject( $res );
1516 * DELETE where the condition is a join
1517 * @param $delTable String: deleting from this table
1518 * @param $joinTable String: using data from this table
1519 * @param $delVar String: variable in deleteable table
1520 * @param $joinVar String: variable in data table
1521 * @param $conds Array: conditionals for join table
1522 * @param $fname String: function name for profiling
1524 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1525 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1528 throw new DBUnexpectedError( $this,
1529 'Database::deleteJoin() called with empty $conds' );
1532 $delTable = $this->tableName( $delTable );
1533 $joinTable = $this->tableName( $joinTable );
1535 DELETE FROM $delTable
1537 SELECT $joinVar FROM $joinTable
1540 if ( $conds != '*' ) {
1541 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1545 $this->query( $sql, $fname );
1549 * Description is left as an exercise for the reader
1550 * @param $b Mixed: data to be encoded
1551 * @return IBM_DB2Blob
1553 public function encodeBlob( $b ) {
1554 return new IBM_DB2Blob( $b );
1558 * Description is left as an exercise for the reader
1559 * @param $b IBM_DB2Blob: data to be decoded
1562 public function decodeBlob( $b ) {
1567 * Convert into a list of string being concatenated
1568 * @param $stringList Array: strings that need to be joined together
1570 * @return String: joined by the concatenation operator
1572 public function buildConcat( $stringList ) {
1573 // || is equivalent to CONCAT
1574 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1575 return implode( ' || ', $stringList );
1579 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1580 * @param $column String: name of timestamp column
1581 * @return String: SQL code
1583 public function extractUnixEpoch( $column ) {
1585 // see SpecialAncientpages
1588 ######################################
1589 # Prepared statements
1590 ######################################
1593 * Intended to be compatible with the PEAR::DB wrapper functions.
1594 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1596 * ? = scalar value, quoted as necessary
1597 * ! = raw SQL bit (a function for instance)
1598 * & = filename; reads the file and inserts as a blob
1599 * (we don't use this though...)
1600 * @param $sql String: SQL statement with appropriate markers
1601 * @param $func String: Name of the function, for profiling
1602 * @return resource a prepared DB2 SQL statement
1604 public function prepare( $sql, $func = 'DB2::prepare' ) {
1605 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1610 * Frees resources associated with a prepared statement
1611 * @return Boolean success or failure
1613 public function freePrepared( $prepared ) {
1614 return db2_free_stmt( $prepared );
1618 * Execute a prepared query with the various arguments
1619 * @param $prepared String: the prepared sql
1620 * @param $args Mixed: either an array here, or put scalars as varargs
1621 * @return Resource: results object
1623 public function execute( $prepared, $args = null ) {
1624 if( !is_array( $args ) ) {
1626 $args = func_get_args();
1627 array_shift( $args );
1629 $res = db2_execute( $prepared, $args );
1631 $this->installPrint( db2_stmt_errormsg() );
1637 * Prepare & execute an SQL statement, quoting and inserting arguments
1638 * in the appropriate places.
1639 * @param $query String
1642 public function safeQuery( $query, $args = null ) {
1643 // copied verbatim from Database.php
1644 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1645 if( !is_array( $args ) ) {
1647 $args = func_get_args();
1648 array_shift( $args );
1650 $retval = $this->execute( $prepared, $args );
1651 $this->freePrepared( $prepared );
1656 * For faking prepared SQL statements on DBs that don't support
1658 * @param $preparedQuery String: a 'preparable' SQL statement
1659 * @param $args Array of arguments to fill it with
1660 * @return String: executable statement
1662 public function fillPrepared( $preparedQuery, $args ) {
1664 $this->preparedArgs
=& $args;
1666 foreach ( $args as $i => $arg ) {
1667 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1670 return $preparedQuery;
1674 * Switches module between regular and install modes
1676 public function setMode( $mode ) {
1677 $old = $this->mMode
;
1678 $this->mMode
= $mode;
1683 * Bitwise negation of a column or value in SQL
1684 * Same as (~field) in C
1685 * @param $field String
1688 function bitNot( $field ) {
1689 // expecting bit-fields smaller than 4bytes
1690 return "BITNOT( $field )";
1694 * Bitwise AND of two columns or values in SQL
1695 * Same as (fieldLeft & fieldRight) in C
1696 * @param $fieldLeft String
1697 * @param $fieldRight String
1700 function bitAnd( $fieldLeft, $fieldRight ) {
1701 return "BITAND( $fieldLeft, $fieldRight )";
1705 * Bitwise OR of two columns or values in SQL
1706 * Same as (fieldLeft | fieldRight) in C
1707 * @param $fieldLeft String
1708 * @param $fieldRight String
1711 function bitOr( $fieldLeft, $fieldRight ) {
1712 return "BITOR( $fieldLeft, $fieldRight )";
1716 class IBM_DB2Helper
{
1717 public static function makeArray( $maybeArray ) {
1718 if ( !is_array( $maybeArray ) ) {
1719 return array( $maybeArray );