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
16 class IBM_DB2Field
implements Field
{
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 isNullable() { 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 $mTablePrefix;
121 protected $mTrxLevel = 0;
122 protected $mErrorCount = 0;
123 protected $mLBInfo = array();
124 protected $mFakeSlaveLag = null, $mFakeMaster = false;
128 /** Database server port */
129 protected $mPort = null;
130 /** Schema for tables, stored procedures, triggers */
131 protected $mSchema = null;
132 /** Whether the schema has been applied in this session */
133 protected $mSchemaSet = false;
134 /** Result of last query */
135 protected $mLastResult = null;
136 /** Number of rows affected by last INSERT/UPDATE/DELETE */
137 protected $mAffectedRows = null;
138 /** Number of rows returned by last SELECT */
139 protected $mNumRows = null;
141 /** Connection config options - see constructor */
142 public $mConnOptions = array();
143 /** Statement config options -- see constructor */
144 public $mStmtOptions = array();
146 /** Default schema */
147 const USE_GLOBAL
= 'mediawiki';
149 /** Option that applies to nothing */
150 const NONE_OPTION
= 0x00;
151 /** Option that applies to connection objects */
152 const CONN_OPTION
= 0x01;
153 /** Option that applies to statement objects */
154 const STMT_OPTION
= 0x02;
156 /** Regular operation mode -- minimal debug messages */
157 const REGULAR_MODE
= 'regular';
158 /** Installation mode -- lots of debug messages */
159 const INSTALL_MODE
= 'install';
161 /** Controls the level of debug message output */
162 protected $mMode = self
::REGULAR_MODE
;
164 /** Last sequence value used for a primary key */
165 protected $mInsertId = null;
167 ######################################
168 # Getters and Setters
169 ######################################
172 * Returns true if this database supports (and uses) cascading deletes
174 function cascadingDeletes() {
179 * Returns true if this database supports (and uses) triggers (e.g. on the
182 function cleanupTriggers() {
187 * Returns true if this database is strict about what can be put into an
189 * Specifically, it uses a NULL value instead of an empty string.
191 function strictIPs() {
196 * Returns true if this database uses timestamps rather than integers
198 function realTimestamps() {
203 * Returns true if this database does an implicit sort when doing GROUP BY
205 function implicitGroupby() {
210 * Returns true if this database does an implicit order by when the column
212 * For example: SELECT page_title FROM page LIMIT 1
214 function implicitOrderby() {
219 * Returns true if this database can do a native search on IP columns
220 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
222 function searchableIPs() {
227 * Returns true if this database can use functional indexes
229 function functionalIndexes() {
234 * Returns a unique string representing the wiki on the server
236 function getWikiID() {
237 if( $this->mSchema
) {
238 return "{$this->mDBname}-{$this->mSchema}";
240 return $this->mDBname
;
248 ######################################
250 ######################################
255 * @param $server String: hostname of database server
256 * @param $user String: username
257 * @param $password String: password
258 * @param $dbName String: database name on the server
259 * @param $flags Integer: database behaviour flags (optional, unused)
260 * @param $schema String
262 public function DatabaseIbm_db2( $server = false, $user = false,
264 $dbName = false, $flags = 0,
265 $schema = self
::USE_GLOBAL
)
268 global $wgOut, $wgDBmwschema;
269 # Can't get a reference if it hasn't been set yet
270 if ( !isset( $wgOut ) ) {
273 $this->mOut
=& $wgOut;
274 $this->mFlags
= DBO_TRX |
$flags;
276 if ( $schema == self
::USE_GLOBAL
) {
277 $this->mSchema
= $wgDBmwschema;
279 $this->mSchema
= $schema;
282 // configure the connection and statement objects
283 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
284 self
::CONN_OPTION | self
::STMT_OPTION
);
285 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
287 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
290 $this->open( $server, $user, $password, $dbName );
294 * Enables options only if the ibm_db2 extension version supports them
295 * @param $name String: name of the option in the options array
296 * @param $const String: name of the constant holding the right option value
297 * @param $type Integer: whether this is a Connection or Statement otion
299 private function setDB2Option( $name, $const, $type ) {
300 if ( defined( $const ) ) {
301 if ( $type & self
::CONN_OPTION
) {
302 $this->mConnOptions
[$name] = constant( $const );
304 if ( $type & self
::STMT_OPTION
) {
305 $this->mStmtOptions
[$name] = constant( $const );
309 "$const is not defined. ibm_db2 version is likely too low." );
314 * Outputs debug information in the appropriate place
315 * @param $string String: the relevant debug message
317 private function installPrint( $string ) {
318 wfDebug( "$string\n" );
319 if ( $this->mMode
== self
::INSTALL_MODE
) {
320 print "<li><pre>$string</pre></li>";
326 * Opens a database connection and returns it
327 * Closes any existing connection
329 * @param $server String: hostname
330 * @param $user String
331 * @param $password String
332 * @param $dbName String: database name
333 * @return a fresh connection
335 public function open( $server, $user, $password, $dbName ) {
336 // Load the port number
338 wfProfileIn( __METHOD__
);
340 // Load IBM DB2 driver if missing
343 // Test for IBM DB2 support, to avoid suppressed fatal error
344 if ( !function_exists( 'db2_connect' ) ) {
346 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
349 $this->installPrint( $error );
350 $this->reportConnectionError( $error );
353 if ( strlen( $user ) < 1 ) {
357 // Close existing connection
360 $this->mServer
= $server;
361 $this->mPort
= $port = $wgDBport;
362 $this->mUser
= $user;
363 $this->mPassword
= $password;
364 $this->mDBname
= $dbName;
366 $this->openUncataloged( $dbName, $user, $password, $server, $port );
368 // Apply connection config
369 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
370 // Some MediaWiki code is still transaction-less (?).
371 // The strategy is to keep AutoCommit on for that code
372 // but switch it off whenever a transaction is begun.
373 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
375 if ( !$this->mConn
) {
376 $this->installPrint( "DB connection error\n" );
378 "Server: $server, Database: $dbName, User: $user, Password: "
379 . substr( $password, 0, 3 ) . "...\n" );
380 $this->installPrint( $this->lastError() . "\n" );
384 $this->mOpened
= true;
385 $this->applySchema();
387 wfProfileOut( __METHOD__
);
392 * Opens a cataloged database connection, sets mConn
394 protected function openCataloged( $dbName, $user, $password ) {
395 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
399 * Opens an uncataloged database connection, sets mConn
401 protected function openUncataloged( $dbName, $user, $password, $server, $port )
403 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
404 $str .= "DATABASE=$dbName;";
405 $str .= "HOSTNAME=$server;";
406 // port was formerly validated to not be 0
407 $str .= "PORT=$port;";
408 $str .= "PROTOCOL=TCPIP;";
409 $str .= "UID=$user;";
410 $str .= "PWD=$password;";
412 @$this->mConn
= db2_pconnect( $str, $user, $password );
416 * Closes a database connection, if it is open
417 * Returns success, true if already closed
419 public function close() {
420 $this->mOpened
= false;
421 if ( $this->mConn
) {
422 if ( $this->trxLevel() > 0 ) {
425 return db2_close( $this->mConn
);
432 * Returns a fresh instance of this class
434 * @param $server String: hostname of database server
435 * @param $user String: username
436 * @param $password String
437 * @param $dbName String: database name on the server
438 * @param $flags Integer: database behaviour flags (optional, unused)
439 * @return DatabaseIbm_db2 object
441 static function newFromParams( $server, $user, $password, $dbName,
444 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
449 * Retrieves the most current database error
450 * Forces a database rollback
452 public function lastError() {
453 $connerr = db2_conn_errormsg();
458 $stmterr = db2_stmt_errormsg();
468 * Get the last error number
469 * Return 0 if no error
472 public function lastErrno() {
473 $connerr = db2_conn_error();
477 $stmterr = db2_stmt_error();
485 * Is a database connection open?
488 public function isOpen() { return $this->mOpened
; }
491 * The DBMS-dependent part of query()
492 * @param $sql String: SQL query.
493 * @return object Result object for fetch functions or false on failure
497 public function doQuery( $sql ) {
498 $this->applySchema();
500 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
501 if( $ret == false ) {
502 $error = db2_stmt_errormsg();
503 $this->installPrint( "<pre>$sql</pre>" );
504 $this->installPrint( $error );
505 throw new DBUnexpectedError( $this, 'SQL error: '
506 . htmlspecialchars( $error ) );
508 $this->mLastResult
= $ret;
509 $this->mAffectedRows
= null; // Not calculated until asked for
514 * @return string Version information from the database
516 public function getServerVersion() {
517 $info = db2_server_info( $this->mConn
);
518 return $info->DBMS_VER
;
522 * Queries whether a given table exists
525 public function tableExists( $table ) {
526 $schema = $this->mSchema
;
528 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
529 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
531 $res = $this->query( $sql );
536 // If the table exists, there should be one of it
537 @$row = $this->fetchRow( $res );
539 if ( $count == '1' ||
$count == 1 ) {
547 * Fetch the next row from the given result object, in object form.
548 * Fields can be retrieved with $row->fieldname, with fields acting like
551 * @param $res SQL result object as returned from Database::query(), etc.
552 * @return DB2 row object
553 * @throws DBUnexpectedError Thrown if the database returns an error
555 public function fetchObject( $res ) {
556 if ( $res instanceof ResultWrapper
) {
559 @$row = db2_fetch_object( $res );
560 if( $this->lastErrno() ) {
561 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
562 . htmlspecialchars( $this->lastError() ) );
568 * Fetch the next row from the given result object, in associative array
569 * form. Fields are retrieved with $row['fieldname'].
571 * @param $res SQL result object as returned from Database::query(), etc.
572 * @return DB2 row object
573 * @throws DBUnexpectedError Thrown if the database returns an error
575 public function fetchRow( $res ) {
576 if ( $res instanceof ResultWrapper
) {
579 @$row = db2_fetch_array( $res );
580 if ( $this->lastErrno() ) {
581 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
582 . htmlspecialchars( $this->lastError() ) );
588 * Create tables, stored procedures, and so on
590 public function setup_database() {
592 // TODO: switch to root login if available
594 // Switch into the correct namespace
595 $this->applySchema();
598 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
599 if ( $res !== true ) {
600 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
604 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
605 if ( $res !== true ) {
606 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
608 print '<li>Foreign keys done</li>';
611 // TODO: populate interwiki links
613 if ( $this->lastError() ) {
615 'Errors encountered during table creation -- rolled back' );
616 $this->installPrint( 'Please install again' );
621 } catch ( MWException
$mwe ) {
622 print "<br><pre>$mwe</pre><br>";
628 * Doesn't escape numbers
630 * @param $s String: string to escape
631 * @return escaped string
633 public function addQuotes( $s ) {
634 //$this->installPrint( "DB2::addQuotes( $s )\n" );
635 if ( is_null( $s ) ) {
637 } elseif ( $s instanceof Blob
) {
638 return "'" . $s->fetch( $s ) . "'";
639 } elseif ( $s instanceof IBM_DB2Blob
) {
640 return "'" . $this->decodeBlob( $s ) . "'";
642 $s = $this->strencode( $s );
643 if ( is_numeric( $s ) ) {
651 * Verifies that a DB2 column/field type is numeric
653 * @param $type String: DB2 column type
654 * @return Boolean: true if numeric
656 public function is_numeric_type( $type ) {
657 switch ( strtoupper( $type ) ) {
672 * Alias for addQuotes()
673 * @param $s String: string to escape
674 * @return escaped string
676 public function strencode( $s ) {
677 // Bloody useless function
678 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
679 // But also necessary
680 $s = db2_escape_string( $s );
681 // Wide characters are evil -- some of them look like '
682 $s = utf8_encode( $s );
684 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
685 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
686 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
691 * Switch into the database schema
693 protected function applySchema() {
694 if ( !( $this->mSchemaSet
) ) {
695 $this->mSchemaSet
= true;
697 $this->doQuery( "SET SCHEMA = $this->mSchema" );
703 * Start a transaction (mandatory)
705 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
706 // BEGIN is implicit for DB2
707 // However, it requires that AutoCommit be off.
709 // Some MediaWiki code is still transaction-less (?).
710 // The strategy is to keep AutoCommit on for that code
711 // but switch it off whenever a transaction is begun.
712 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
714 $this->mTrxLevel
= 1;
719 * Must have a preceding begin()
721 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
722 db2_commit( $this->mConn
);
724 // Some MediaWiki code is still transaction-less (?).
725 // The strategy is to keep AutoCommit on for that code
726 // but switch it off whenever a transaction is begun.
727 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
729 $this->mTrxLevel
= 0;
733 * Cancel a transaction
735 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
736 db2_rollback( $this->mConn
);
737 // turn auto-commit back on
738 // not sure if this is appropriate
739 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
740 $this->mTrxLevel
= 0;
744 * Makes an encoded list of strings from an array
746 * LIST_COMMA - comma separated, no field names
747 * LIST_AND - ANDed WHERE clause (without the WHERE)
748 * LIST_OR - ORed WHERE clause (without the WHERE)
749 * LIST_SET - comma separated with field names, like a SET clause
750 * LIST_NAMES - comma separated field names
751 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
753 function makeList( $a, $mode = LIST_COMMA
) {
754 if ( !is_array( $a ) ) {
755 throw new DBUnexpectedError( $this,
756 'DatabaseIbm_db2::makeList called with incorrect parameters' );
759 // if this is for a prepared UPDATE statement
760 // (this should be promoted to the parent class
761 // once other databases use prepared statements)
762 if ( $mode == LIST_SET_PREPARED
) {
765 foreach ( $a as $field => $value ) {
767 $list .= ", $field = ?";
769 $list .= "$field = ?";
778 // otherwise, call the usual function
779 return parent
::makeList( $a, $mode );
783 * Construct a LIMIT query with optional offset
784 * This is used for query pages
786 * @param $sql string SQL query we will append the limit too
787 * @param $limit integer the SQL limit
788 * @param $offset integer the SQL offset (default false)
790 public function limitResult( $sql, $limit, $offset=false ) {
791 if( !is_numeric( $limit ) ) {
792 throw new DBUnexpectedError( $this,
793 "Invalid non-numeric limit passed to limitResult()\n" );
796 if ( stripos( $sql, 'where' ) === false ) {
797 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
799 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
802 return "$sql FETCH FIRST $limit ROWS ONLY ";
806 * Handle reserved keyword replacement in table names
808 * @param $name Object
811 public function tableName( $name ) {
812 // we want maximum compatibility with MySQL schema
817 * Generates a timestamp in an insertable format
819 * @param $ts timestamp
820 * @return String: timestamp value
822 public function timestamp( $ts = 0 ) {
823 // TS_MW cannot be easily distinguished from an integer
824 return wfTimestamp( TS_DB2
, $ts );
828 * Return the next in a sequence, save the value for retrieval via insertId()
829 * @param $seqName String: name of a defined sequence in the database
830 * @return next value in that sequence
832 public function nextSequenceValue( $seqName ) {
833 // Not using sequences in the primary schema to allow for easier migration
835 // Emulating MySQL behaviour of using NULL to signal that sequences
838 $safeseq = preg_replace( "/'/", "''", $seqName );
839 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
840 $row = $this->fetchRow( $res );
841 $this->mInsertId = $row[0];
842 return $this->mInsertId;
848 * This must be called after nextSequenceVal
849 * @return Last sequence value used as a primary key
851 public function insertId() {
852 return $this->mInsertId
;
856 * Updates the mInsertId property with the value of the last insert
857 * into a generated column
859 * @param $table String: sanitized table name
860 * @param $primaryKey Mixed: string name of the primary key
861 * @param $stmt Resource: prepared statement resource
862 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
864 private function calcInsertId( $table, $primaryKey, $stmt ) {
866 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
871 * INSERT wrapper, inserts an array into a table
873 * $args may be a single associative array, or an array of arrays
874 * with numeric keys, for multi-row insert
876 * @param $table String: Name of the table to insert to.
877 * @param $args Array: Items to insert into the table.
878 * @param $fname String: Name of the function, for profiling
879 * @param $options String or Array. Valid options: IGNORE
881 * @return bool Success of insert operation. IGNORE always returns true.
883 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
886 if ( !count( $args ) ) {
889 // get database-specific table name (not used)
890 $table = $this->tableName( $table );
891 // format options as an array
892 $options = IBM_DB2Helper
::makeArray( $options );
893 // format args as an array of arrays
894 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
895 $args = array( $args );
898 // prevent insertion of NULL into primary key columns
899 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
900 // if there's only one primary key
901 // we'll be able to read its value after insertion
903 if ( count( $primaryKeys ) == 1 ) {
904 $primaryKey = $primaryKeys[0];
908 $keys = array_keys( $args[0] );
909 $key_count = count( $keys );
911 // If IGNORE is set, we use savepoints to emulate mysql's behavior
912 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
916 // If we are not in a transaction, we need to be for savepoint trickery
917 if ( !$this->mTrxLevel
) {
921 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
922 if ( $key_count == 1 ) {
925 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
927 //$this->installPrint( "Preparing the following SQL:" );
928 //$this->installPrint( "$sql" );
929 //$this->installPrint( print_r( $args, true ));
930 $stmt = $this->prepare( $sql );
932 // start a transaction/enter transaction mode
937 foreach ( $args as $row ) {
938 //$this->installPrint( "Inserting " . print_r( $row, true ));
939 // insert each row into the database
940 $res = $res & $this->execute( $stmt, $row );
942 $this->installPrint( 'Last error:' );
943 $this->installPrint( $this->lastError() );
945 // get the last inserted value into a generated column
946 $this->calcInsertId( $table, $primaryKey, $stmt );
949 $olde = error_reporting( 0 );
950 // For future use, we may want to track the number of actual inserts
951 // Right now, insert (all writes) simply return true/false
952 $numrowsinserted = 0;
954 // always return true
957 foreach ( $args as $row ) {
958 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
959 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
961 $this->execute( $stmt, $row );
964 $this->installPrint( 'Last error:' );
965 $this->installPrint( $this->lastError() );
967 // get the last inserted value into a generated column
968 $this->calcInsertId( $table, $primaryKey, $stmt );
970 $errNum = $this->lastErrno();
972 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
973 $this->mStmtOptions
);
975 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
976 $this->mStmtOptions
);
981 $olde = error_reporting( $olde );
982 // Set the affected row count for the whole operation
983 $this->mAffectedRows
= $numrowsinserted;
987 $this->freePrepared( $stmt );
993 * Given a table name and a hash of columns with values
994 * Removes primary key columns from the hash where the value is NULL
996 * @param $table String: name of the table
997 * @param $args Array of hashes of column names with values
998 * @return Array: tuple( filtered array of columns, array of primary keys )
1000 private function removeNullPrimaryKeys( $table, $args ) {
1001 $schema = $this->mSchema
;
1002 // find out the primary keys
1003 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1004 strtoupper( $table )
1008 $row = $this->fetchObject( $keyres );
1010 $row = $this->fetchObject( $keyres )
1013 $keys[] = strtolower( $row->column_name
);
1015 // remove primary keys
1016 foreach ( $args as $ai => $row ) {
1017 foreach ( $keys as $key ) {
1018 if ( $row[$key] == null ) {
1019 unset( $row[$key] );
1024 // return modified hash
1025 return array( $args, $keys );
1029 * UPDATE wrapper, takes a condition array and a SET array
1031 * @param $table String: The table to UPDATE
1032 * @param $values An array of values to SET
1033 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1034 * @param $fname String: The Class::Function calling this function
1036 * @param $options An array of UPDATE options, can be one or
1037 * more of IGNORE, LOW_PRIORITY
1040 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1041 $options = array() )
1043 $table = $this->tableName( $table );
1044 $opts = $this->makeUpdateOptions( $options );
1045 $sql = "UPDATE $opts $table SET "
1046 . $this->makeList( $values, LIST_SET_PREPARED
);
1047 if ( $conds != '*' ) {
1048 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1050 $stmt = $this->prepare( $sql );
1051 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1052 // assuming for now that an array with string keys will work
1053 // if not, convert to simple array first
1054 $result = $this->execute( $stmt, $values );
1055 $this->freePrepared( $stmt );
1061 * DELETE query wrapper
1063 * Use $conds == "*" to delete all rows
1065 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1067 throw new DBUnexpectedError( $this,
1068 'DatabaseIbm_db2::delete() called with no conditions' );
1070 $table = $this->tableName( $table );
1071 $sql = "DELETE FROM $table";
1072 if ( $conds != '*' ) {
1073 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1075 $result = $this->query( $sql, $fname );
1081 * Returns the number of rows affected by the last query or 0
1082 * @return Integer: the number of rows affected by the last query
1084 public function affectedRows() {
1085 if ( !is_null( $this->mAffectedRows
) ) {
1086 // Forced result for simulated queries
1087 return $this->mAffectedRows
;
1089 if( empty( $this->mLastResult
) ) {
1092 return db2_num_rows( $this->mLastResult
);
1096 * Simulates REPLACE with a DELETE followed by INSERT
1097 * @param $table Object
1098 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1099 * @param $rows Array: rows to insert
1100 * @param $fname String: name of the function for profiling
1103 function replace( $table, $uniqueIndexes, $rows,
1104 $fname = 'DatabaseIbm_db2::replace' )
1106 $table = $this->tableName( $table );
1108 if ( count( $rows )==0 ) {
1113 if ( !is_array( reset( $rows ) ) ) {
1114 $rows = array( $rows );
1117 foreach( $rows as $row ) {
1118 # Delete rows which collide
1119 if ( $uniqueIndexes ) {
1120 $sql = "DELETE FROM $table WHERE ";
1122 foreach ( $uniqueIndexes as $index ) {
1129 if ( is_array( $index ) ) {
1131 foreach ( $index as $col ) {
1137 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1140 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1144 $this->query( $sql, $fname );
1147 # Now insert the row
1148 $sql = "INSERT INTO $table ( "
1149 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1150 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1151 $this->query( $sql, $fname );
1156 * Returns the number of rows in the result set
1157 * Has to be called right after the corresponding select query
1158 * @param $res Object result set
1159 * @return Integer: number of rows
1161 public function numRows( $res ) {
1162 if ( $res instanceof ResultWrapper
) {
1163 $res = $res->result
;
1165 if ( $this->mNumRows
) {
1166 return $this->mNumRows
;
1173 * Moves the row pointer of the result set
1174 * @param $res Object: result set
1175 * @param $row Integer: row number
1176 * @return success or failure
1178 public function dataSeek( $res, $row ) {
1179 if ( $res instanceof ResultWrapper
) {
1180 $res = $res->result
;
1182 return db2_fetch_row( $res, $row );
1186 # Fix notices in Block.php
1190 * Frees memory associated with a statement resource
1191 * @param $res Object: statement resource to free
1192 * @return Boolean success or failure
1194 public function freeResult( $res ) {
1195 if ( $res instanceof ResultWrapper
) {
1196 $res = $res->result
;
1198 if ( !@db2_free_result
( $res ) ) {
1199 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1204 * Returns the number of columns in a resource
1205 * @param $res Object: statement resource
1206 * @return Number of fields/columns in resource
1208 public function numFields( $res ) {
1209 if ( $res instanceof ResultWrapper
) {
1210 $res = $res->result
;
1212 return db2_num_fields( $res );
1216 * Returns the nth column name
1217 * @param $res Object: statement resource
1218 * @param $n Integer: Index of field or column
1219 * @return String name of nth column
1221 public function fieldName( $res, $n ) {
1222 if ( $res instanceof ResultWrapper
) {
1223 $res = $res->result
;
1225 return db2_field_name( $res, $n );
1231 * @param $table Array or string, table name(s) (prefix auto-added)
1232 * @param $vars Array or string, field name(s) to be retrieved
1233 * @param $conds Array or string, condition(s) for WHERE
1234 * @param $fname String: calling function name (use __METHOD__)
1235 * for logs/profiling
1236 * @param $options Associative array of options
1237 * (e.g. array('GROUP BY' => 'page_title')),
1238 * see Database::makeSelectOptions code for list of
1240 * @param $join_conds Associative array of table join conditions (optional)
1241 * (e.g. array( 'page' => array('LEFT JOIN',
1242 * 'page_latest=rev_id') )
1243 * @return Mixed: database result resource for fetch functions or false
1246 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1248 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1251 // We must adjust for offset
1252 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1253 $limit = $options['LIMIT'];
1254 $offset = $options['OFFSET'];
1257 // DB2 does not have a proper num_rows() function yet, so we must emulate
1258 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1262 // we want the count
1263 $vars2 = array( 'count( * ) as num_rows' );
1264 // respecting just the limit option
1265 $options2 = array();
1266 if ( isset( $options['LIMIT'] ) ) {
1267 $options2['LIMIT'] = $options['LIMIT'];
1269 // but don't try to emulate for GROUP BY
1270 if ( isset( $options['GROUP BY'] ) ) {
1274 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1276 $obj = $this->fetchObject( $res2 );
1277 $this->mNumRows
= $obj->num_rows
;
1283 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1284 * Has limited support for per-column options (colnum => 'DISTINCT')
1288 * @param $options Associative array of options to be turned into
1289 * an SQL query, valid keys are listed in the function.
1292 function makeSelectOptions( $options ) {
1293 $preLimitTail = $postLimitTail = '';
1296 $noKeyOptions = array();
1297 foreach ( $options as $key => $option ) {
1298 if ( is_numeric( $key ) ) {
1299 $noKeyOptions[$option] = true;
1303 if ( isset( $options['GROUP BY'] ) ) {
1304 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1306 if ( isset( $options['HAVING'] ) ) {
1307 $preLimitTail .= " HAVING {$options['HAVING']}";
1309 if ( isset( $options['ORDER BY'] ) ) {
1310 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1313 if ( isset( $noKeyOptions['DISTINCT'] )
1314 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1316 $startOpts .= 'DISTINCT';
1319 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1323 * Returns link to IBM DB2 free download
1324 * @return String: wikitext of a link to the server software's web site
1326 public static function getSoftwareLink() {
1327 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1331 * Get search engine class. All subclasses of this
1332 * need to implement this if they wish to use searching.
1336 public function getSearchEngine() {
1337 return 'SearchIBM_DB2';
1341 * Did the last database access fail because of deadlock?
1344 public function wasDeadlock() {
1346 $err = $this->lastErrno();
1348 // This is literal port of the MySQL logic and may be wrong for DB2
1349 case '40001': // sql0911n, Deadlock or timeout, rollback
1350 case '57011': // sql0904n, Resource unavailable, no rollback
1351 case '57033': // sql0913n, Deadlock or timeout, no rollback
1352 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1359 * Ping the server and try to reconnect if it there is no connection
1360 * The connection may be closed and reopened while this happens
1361 * @return Boolean: whether the connection exists
1363 public function ping() {
1364 // db2_ping() doesn't exist
1367 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1368 $this->mPassword
, $this->mServer
, $this->mPort
);
1372 ######################################
1373 # Unimplemented and not applicable
1374 ######################################
1379 public function getStatus( $which = '%' ) {
1380 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1385 * @return string $sql
1387 public function limitResultForUpdate( $sql, $num ) {
1388 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1393 * Only useful with fake prepare like in base Database class
1396 public function fillPreparedArg( $matches ) {
1397 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1401 ######################################
1403 ######################################
1406 * Returns information about an index
1407 * If errors are explicitly ignored, returns NULL on failure
1408 * @param $table String: table name
1409 * @param $index String: index name
1410 * @param $fname String: function name for logging and profiling
1411 * @return Object query row in object form
1413 public function indexInfo( $table, $index,
1414 $fname = 'DatabaseIbm_db2::indexExists' )
1416 $table = $this->tableName( $table );
1418 SELECT name as indexname
1419 FROM sysibm.sysindexes si
1420 WHERE si.name='$index' AND si.tbname='$table'
1421 AND sc.tbcreator='$this->mSchema'
1423 $res = $this->query( $sql, $fname );
1427 $row = $this->fetchObject( $res );
1428 if ( $row != null ) {
1436 * Returns an information object on a table column
1437 * @param $table String: table name
1438 * @param $field String: column name
1439 * @return IBM_DB2Field
1441 public function fieldInfo( $table, $field ) {
1442 return IBM_DB2Field
::fromText( $this, $table, $field );
1446 * db2_field_type() wrapper
1447 * @param $res Object: result of executed statement
1448 * @param $index Mixed: number or name of the column
1449 * @return String column type
1451 public function fieldType( $res, $index ) {
1452 if ( $res instanceof ResultWrapper
) {
1453 $res = $res->result
;
1455 return db2_field_type( $res, $index );
1459 * Verifies that an index was created as unique
1460 * @param $table String: table name
1461 * @param $index String: index name
1462 * @param $fname function name for profiling
1465 public function indexUnique ( $table, $index,
1466 $fname = 'DatabaseIbm_db2::indexUnique' )
1468 $table = $this->tableName( $table );
1470 SELECT si.name as indexname
1471 FROM sysibm.sysindexes si
1472 WHERE si.name='$index' AND si.tbname='$table'
1473 AND sc.tbcreator='$this->mSchema'
1474 AND si.uniquerule IN ( 'U', 'P' )
1476 $res = $this->query( $sql, $fname );
1480 if ( $this->fetchObject( $res ) ) {
1488 * Returns the size of a text field, or -1 for "unlimited"
1489 * @param $table String: table name
1490 * @param $field String: column name
1491 * @return Integer: length or -1 for unlimited
1493 public function textFieldSize( $table, $field ) {
1494 $table = $this->tableName( $table );
1496 SELECT length as size
1497 FROM sysibm.syscolumns sc
1498 WHERE sc.name='$field' AND sc.tbname='$table'
1499 AND sc.tbcreator='$this->mSchema'
1501 $res = $this->query( $sql );
1502 $row = $this->fetchObject( $res );
1508 * DELETE where the condition is a join
1509 * @param $delTable String: deleting from this table
1510 * @param $joinTable String: using data from this table
1511 * @param $delVar String: variable in deleteable table
1512 * @param $joinVar String: variable in data table
1513 * @param $conds Array: conditionals for join table
1514 * @param $fname String: function name for profiling
1516 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1517 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1520 throw new DBUnexpectedError( $this,
1521 'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
1524 $delTable = $this->tableName( $delTable );
1525 $joinTable = $this->tableName( $joinTable );
1527 DELETE FROM $delTable
1529 SELECT $joinVar FROM $joinTable
1532 if ( $conds != '*' ) {
1533 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1537 $this->query( $sql, $fname );
1541 * Description is left as an exercise for the reader
1542 * @param $b Mixed: data to be encoded
1543 * @return IBM_DB2Blob
1545 public function encodeBlob( $b ) {
1546 return new IBM_DB2Blob( $b );
1550 * Description is left as an exercise for the reader
1551 * @param $b IBM_DB2Blob: data to be decoded
1554 public function decodeBlob( $b ) {
1559 * Convert into a list of string being concatenated
1560 * @param $stringList Array: strings that need to be joined together
1562 * @return String: joined by the concatenation operator
1564 public function buildConcat( $stringList ) {
1565 // || is equivalent to CONCAT
1566 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1567 return implode( ' || ', $stringList );
1571 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1572 * @param $column String: name of timestamp column
1573 * @return String: SQL code
1575 public function extractUnixEpoch( $column ) {
1577 // see SpecialAncientpages
1580 ######################################
1581 # Prepared statements
1582 ######################################
1585 * Intended to be compatible with the PEAR::DB wrapper functions.
1586 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1588 * ? = scalar value, quoted as necessary
1589 * ! = raw SQL bit (a function for instance)
1590 * & = filename; reads the file and inserts as a blob
1591 * (we don't use this though...)
1592 * @param $sql String: SQL statement with appropriate markers
1593 * @param $func String: Name of the function, for profiling
1594 * @return resource a prepared DB2 SQL statement
1596 public function prepare( $sql, $func = 'DB2::prepare' ) {
1597 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1602 * Frees resources associated with a prepared statement
1603 * @return Boolean success or failure
1605 public function freePrepared( $prepared ) {
1606 return db2_free_stmt( $prepared );
1610 * Execute a prepared query with the various arguments
1611 * @param $prepared String: the prepared sql
1612 * @param $args Mixed: either an array here, or put scalars as varargs
1613 * @return Resource: results object
1615 public function execute( $prepared, $args = null ) {
1616 if( !is_array( $args ) ) {
1618 $args = func_get_args();
1619 array_shift( $args );
1621 $res = db2_execute( $prepared, $args );
1623 $this->installPrint( db2_stmt_errormsg() );
1629 * Prepare & execute an SQL statement, quoting and inserting arguments
1630 * in the appropriate places.
1631 * @param $query String
1634 public function safeQuery( $query, $args = null ) {
1635 // copied verbatim from Database.php
1636 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1637 if( !is_array( $args ) ) {
1639 $args = func_get_args();
1640 array_shift( $args );
1642 $retval = $this->execute( $prepared, $args );
1643 $this->freePrepared( $prepared );
1648 * For faking prepared SQL statements on DBs that don't support
1650 * @param $preparedQuery String: a 'preparable' SQL statement
1651 * @param $args Array of arguments to fill it with
1652 * @return String: executable statement
1654 public function fillPrepared( $preparedQuery, $args ) {
1656 $this->preparedArgs
=& $args;
1658 foreach ( $args as $i => $arg ) {
1659 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1662 return $preparedQuery;
1666 * Switches module between regular and install modes
1668 public function setMode( $mode ) {
1669 $old = $this->mMode
;
1670 $this->mMode
= $mode;
1675 * Bitwise negation of a column or value in SQL
1676 * Same as (~field) in C
1677 * @param $field String
1680 function bitNot( $field ) {
1681 // expecting bit-fields smaller than 4bytes
1682 return "BITNOT( $field )";
1686 * Bitwise AND of two columns or values in SQL
1687 * Same as (fieldLeft & fieldRight) in C
1688 * @param $fieldLeft String
1689 * @param $fieldRight String
1692 function bitAnd( $fieldLeft, $fieldRight ) {
1693 return "BITAND( $fieldLeft, $fieldRight )";
1697 * Bitwise OR of two columns or values in SQL
1698 * Same as (fieldLeft | fieldRight) in C
1699 * @param $fieldLeft String
1700 * @param $fieldRight String
1703 function bitOr( $fieldLeft, $fieldRight ) {
1704 return "BITOR( $fieldLeft, $fieldRight )";
1708 class IBM_DB2Helper
{
1709 public static function makeArray( $maybeArray ) {
1710 if ( !is_array( $maybeArray ) ) {
1711 return array( $maybeArray );