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 $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 __construct( $server = false, $user = false,
264 $dbName = false, $flags = 0,
265 $schema = self
::USE_GLOBAL
)
267 global $wgDBmwschema;
269 if ( $schema == self
::USE_GLOBAL
) {
270 $this->mSchema
= $wgDBmwschema;
272 $this->mSchema
= $schema;
275 // configure the connection and statement objects
276 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
277 self
::CONN_OPTION | self
::STMT_OPTION
);
278 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
280 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
283 parent
::__construct( $server, $user, $password, $dbName, DBO_TRX |
$flags );
287 * Enables options only if the ibm_db2 extension version supports them
288 * @param $name String: name of the option in the options array
289 * @param $const String: name of the constant holding the right option value
290 * @param $type Integer: whether this is a Connection or Statement otion
292 private function setDB2Option( $name, $const, $type ) {
293 if ( defined( $const ) ) {
294 if ( $type & self
::CONN_OPTION
) {
295 $this->mConnOptions
[$name] = constant( $const );
297 if ( $type & self
::STMT_OPTION
) {
298 $this->mStmtOptions
[$name] = constant( $const );
302 "$const is not defined. ibm_db2 version is likely too low." );
307 * Outputs debug information in the appropriate place
308 * @param $string String: the relevant debug message
310 private function installPrint( $string ) {
311 wfDebug( "$string\n" );
312 if ( $this->mMode
== self
::INSTALL_MODE
) {
313 print "<li><pre>$string</pre></li>";
319 * Opens a database connection and returns it
320 * Closes any existing connection
322 * @param $server String: hostname
323 * @param $user String
324 * @param $password String
325 * @param $dbName String: database name
326 * @return a fresh connection
328 public function open( $server, $user, $password, $dbName ) {
329 // Load the port number
331 wfProfileIn( __METHOD__
);
333 // Load IBM DB2 driver if missing
336 // Test for IBM DB2 support, to avoid suppressed fatal error
337 if ( !function_exists( 'db2_connect' ) ) {
339 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
342 $this->installPrint( $error );
343 $this->reportConnectionError( $error );
346 if ( strlen( $user ) < 1 ) {
347 wfProfileOut( __METHOD__
);
351 // Close existing connection
354 $this->mServer
= $server;
355 $this->mPort
= $port = $wgDBport;
356 $this->mUser
= $user;
357 $this->mPassword
= $password;
358 $this->mDBname
= $dbName;
360 $this->openUncataloged( $dbName, $user, $password, $server, $port );
362 // Apply connection config
363 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
364 // Some MediaWiki code is still transaction-less (?).
365 // The strategy is to keep AutoCommit on for that code
366 // but switch it off whenever a transaction is begun.
367 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
369 if ( !$this->mConn
) {
370 $this->installPrint( "DB connection error\n" );
372 "Server: $server, Database: $dbName, User: $user, Password: "
373 . substr( $password, 0, 3 ) . "...\n" );
374 $this->installPrint( $this->lastError() . "\n" );
376 wfProfileOut( __METHOD__
);
380 $this->mOpened
= true;
381 $this->applySchema();
383 wfProfileOut( __METHOD__
);
388 * Opens a cataloged database connection, sets mConn
390 protected function openCataloged( $dbName, $user, $password ) {
391 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
395 * Opens an uncataloged database connection, sets mConn
397 protected function openUncataloged( $dbName, $user, $password, $server, $port )
399 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
400 $str .= "DATABASE=$dbName;";
401 $str .= "HOSTNAME=$server;";
402 // port was formerly validated to not be 0
403 $str .= "PORT=$port;";
404 $str .= "PROTOCOL=TCPIP;";
405 $str .= "UID=$user;";
406 $str .= "PWD=$password;";
408 @$this->mConn
= db2_pconnect( $str, $user, $password );
412 * Closes a database connection, if it is open
413 * Returns success, true if already closed
415 public function close() {
416 $this->mOpened
= false;
417 if ( $this->mConn
) {
418 if ( $this->trxLevel() > 0 ) {
421 return db2_close( $this->mConn
);
428 * Retrieves the most current database error
429 * Forces a database rollback
431 public function lastError() {
432 $connerr = db2_conn_errormsg();
437 $stmterr = db2_stmt_errormsg();
447 * Get the last error number
448 * Return 0 if no error
451 public function lastErrno() {
452 $connerr = db2_conn_error();
456 $stmterr = db2_stmt_error();
464 * Is a database connection open?
467 public function isOpen() { return $this->mOpened
; }
470 * The DBMS-dependent part of query()
471 * @param $sql String: SQL query.
472 * @return object Result object for fetch functions or false on failure
476 public function doQuery( $sql ) {
477 $this->applySchema();
479 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
480 if( $ret == false ) {
481 $error = db2_stmt_errormsg();
482 $this->installPrint( "<pre>$sql</pre>" );
483 $this->installPrint( $error );
484 throw new DBUnexpectedError( $this, 'SQL error: '
485 . htmlspecialchars( $error ) );
487 $this->mLastResult
= $ret;
488 $this->mAffectedRows
= null; // Not calculated until asked for
493 * @return string Version information from the database
495 public function getServerVersion() {
496 $info = db2_server_info( $this->mConn
);
497 return $info->DBMS_VER
;
501 * Queries whether a given table exists
504 public function tableExists( $table ) {
505 $schema = $this->mSchema
;
507 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
508 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
510 $res = $this->query( $sql );
515 // If the table exists, there should be one of it
516 @$row = $this->fetchRow( $res );
518 if ( $count == '1' ||
$count == 1 ) {
526 * Fetch the next row from the given result object, in object form.
527 * Fields can be retrieved with $row->fieldname, with fields acting like
530 * @param $res SQL result object as returned from Database::query(), etc.
531 * @return DB2 row object
532 * @throws DBUnexpectedError Thrown if the database returns an error
534 public function fetchObject( $res ) {
535 if ( $res instanceof ResultWrapper
) {
538 @$row = db2_fetch_object( $res );
539 if( $this->lastErrno() ) {
540 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
541 . htmlspecialchars( $this->lastError() ) );
547 * Fetch the next row from the given result object, in associative array
548 * form. Fields are retrieved with $row['fieldname'].
550 * @param $res SQL result object as returned from Database::query(), etc.
551 * @return DB2 row object
552 * @throws DBUnexpectedError Thrown if the database returns an error
554 public function fetchRow( $res ) {
555 if ( $res instanceof ResultWrapper
) {
558 @$row = db2_fetch_array( $res );
559 if ( $this->lastErrno() ) {
560 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
561 . htmlspecialchars( $this->lastError() ) );
567 * Create tables, stored procedures, and so on
569 public function setup_database() {
571 // TODO: switch to root login if available
573 // Switch into the correct namespace
574 $this->applySchema();
577 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
578 if ( $res !== true ) {
579 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
583 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
584 if ( $res !== true ) {
585 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
587 print '<li>Foreign keys done</li>';
590 // TODO: populate interwiki links
592 if ( $this->lastError() ) {
594 'Errors encountered during table creation -- rolled back' );
595 $this->installPrint( 'Please install again' );
600 } catch ( MWException
$mwe ) {
601 print "<br><pre>$mwe</pre><br>";
607 * Doesn't escape numbers
609 * @param $s String: string to escape
610 * @return escaped string
612 public function addQuotes( $s ) {
613 //$this->installPrint( "DB2::addQuotes( $s )\n" );
614 if ( is_null( $s ) ) {
616 } elseif ( $s instanceof Blob
) {
617 return "'" . $s->fetch( $s ) . "'";
618 } elseif ( $s instanceof IBM_DB2Blob
) {
619 return "'" . $this->decodeBlob( $s ) . "'";
621 $s = $this->strencode( $s );
622 if ( is_numeric( $s ) ) {
630 * Verifies that a DB2 column/field type is numeric
632 * @param $type String: DB2 column type
633 * @return Boolean: true if numeric
635 public function is_numeric_type( $type ) {
636 switch ( strtoupper( $type ) ) {
651 * Alias for addQuotes()
652 * @param $s String: string to escape
653 * @return escaped string
655 public function strencode( $s ) {
656 // Bloody useless function
657 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
658 // But also necessary
659 $s = db2_escape_string( $s );
660 // Wide characters are evil -- some of them look like '
661 $s = utf8_encode( $s );
663 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
664 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
665 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
670 * Switch into the database schema
672 protected function applySchema() {
673 if ( !( $this->mSchemaSet
) ) {
674 $this->mSchemaSet
= true;
676 $this->doQuery( "SET SCHEMA = $this->mSchema" );
682 * Start a transaction (mandatory)
684 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
685 // BEGIN is implicit for DB2
686 // However, it requires that AutoCommit be off.
688 // Some MediaWiki code is still transaction-less (?).
689 // The strategy is to keep AutoCommit on for that code
690 // but switch it off whenever a transaction is begun.
691 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
693 $this->mTrxLevel
= 1;
698 * Must have a preceding begin()
700 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
701 db2_commit( $this->mConn
);
703 // Some MediaWiki code is still transaction-less (?).
704 // The strategy is to keep AutoCommit on for that code
705 // but switch it off whenever a transaction is begun.
706 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
708 $this->mTrxLevel
= 0;
712 * Cancel a transaction
714 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
715 db2_rollback( $this->mConn
);
716 // turn auto-commit back on
717 // not sure if this is appropriate
718 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
719 $this->mTrxLevel
= 0;
723 * Makes an encoded list of strings from an array
725 * LIST_COMMA - comma separated, no field names
726 * LIST_AND - ANDed WHERE clause (without the WHERE)
727 * LIST_OR - ORed WHERE clause (without the WHERE)
728 * LIST_SET - comma separated with field names, like a SET clause
729 * LIST_NAMES - comma separated field names
730 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
732 function makeList( $a, $mode = LIST_COMMA
) {
733 if ( !is_array( $a ) ) {
734 throw new DBUnexpectedError( $this,
735 'DatabaseIbm_db2::makeList called with incorrect parameters' );
738 // if this is for a prepared UPDATE statement
739 // (this should be promoted to the parent class
740 // once other databases use prepared statements)
741 if ( $mode == LIST_SET_PREPARED
) {
744 foreach ( $a as $field => $value ) {
746 $list .= ", $field = ?";
748 $list .= "$field = ?";
757 // otherwise, call the usual function
758 return parent
::makeList( $a, $mode );
762 * Construct a LIMIT query with optional offset
763 * This is used for query pages
765 * @param $sql string SQL query we will append the limit too
766 * @param $limit integer the SQL limit
767 * @param $offset integer the SQL offset (default false)
769 public function limitResult( $sql, $limit, $offset=false ) {
770 if( !is_numeric( $limit ) ) {
771 throw new DBUnexpectedError( $this,
772 "Invalid non-numeric limit passed to limitResult()\n" );
775 if ( stripos( $sql, 'where' ) === false ) {
776 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
778 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
781 return "$sql FETCH FIRST $limit ROWS ONLY ";
785 * Handle reserved keyword replacement in table names
787 * @param $name Object
790 public function tableName( $name ) {
791 // we want maximum compatibility with MySQL schema
796 * Generates a timestamp in an insertable format
798 * @param $ts timestamp
799 * @return String: timestamp value
801 public function timestamp( $ts = 0 ) {
802 // TS_MW cannot be easily distinguished from an integer
803 return wfTimestamp( TS_DB2
, $ts );
807 * Return the next in a sequence, save the value for retrieval via insertId()
808 * @param $seqName String: name of a defined sequence in the database
809 * @return next value in that sequence
811 public function nextSequenceValue( $seqName ) {
812 // Not using sequences in the primary schema to allow for easier migration
814 // Emulating MySQL behaviour of using NULL to signal that sequences
817 $safeseq = preg_replace( "/'/", "''", $seqName );
818 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
819 $row = $this->fetchRow( $res );
820 $this->mInsertId = $row[0];
821 return $this->mInsertId;
827 * This must be called after nextSequenceVal
828 * @return Last sequence value used as a primary key
830 public function insertId() {
831 return $this->mInsertId
;
835 * Updates the mInsertId property with the value of the last insert
836 * into a generated column
838 * @param $table String: sanitized table name
839 * @param $primaryKey Mixed: string name of the primary key
840 * @param $stmt Resource: prepared statement resource
841 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
843 private function calcInsertId( $table, $primaryKey, $stmt ) {
845 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
850 * INSERT wrapper, inserts an array into a table
852 * $args may be a single associative array, or an array of arrays
853 * with numeric keys, for multi-row insert
855 * @param $table String: Name of the table to insert to.
856 * @param $args Array: Items to insert into the table.
857 * @param $fname String: Name of the function, for profiling
858 * @param $options String or Array. Valid options: IGNORE
860 * @return bool Success of insert operation. IGNORE always returns true.
862 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
865 if ( !count( $args ) ) {
868 // get database-specific table name (not used)
869 $table = $this->tableName( $table );
870 // format options as an array
871 $options = IBM_DB2Helper
::makeArray( $options );
872 // format args as an array of arrays
873 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
874 $args = array( $args );
877 // prevent insertion of NULL into primary key columns
878 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
879 // if there's only one primary key
880 // we'll be able to read its value after insertion
882 if ( count( $primaryKeys ) == 1 ) {
883 $primaryKey = $primaryKeys[0];
887 $keys = array_keys( $args[0] );
888 $key_count = count( $keys );
890 // If IGNORE is set, we use savepoints to emulate mysql's behavior
891 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
895 // If we are not in a transaction, we need to be for savepoint trickery
896 if ( !$this->mTrxLevel
) {
900 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
901 if ( $key_count == 1 ) {
904 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
906 //$this->installPrint( "Preparing the following SQL:" );
907 //$this->installPrint( "$sql" );
908 //$this->installPrint( print_r( $args, true ));
909 $stmt = $this->prepare( $sql );
911 // start a transaction/enter transaction mode
916 foreach ( $args as $row ) {
917 //$this->installPrint( "Inserting " . print_r( $row, true ));
918 // insert each row into the database
919 $res = $res & $this->execute( $stmt, $row );
921 $this->installPrint( 'Last error:' );
922 $this->installPrint( $this->lastError() );
924 // get the last inserted value into a generated column
925 $this->calcInsertId( $table, $primaryKey, $stmt );
928 $olde = error_reporting( 0 );
929 // For future use, we may want to track the number of actual inserts
930 // Right now, insert (all writes) simply return true/false
931 $numrowsinserted = 0;
933 // always return true
936 foreach ( $args as $row ) {
937 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
938 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
940 $this->execute( $stmt, $row );
943 $this->installPrint( 'Last error:' );
944 $this->installPrint( $this->lastError() );
946 // get the last inserted value into a generated column
947 $this->calcInsertId( $table, $primaryKey, $stmt );
949 $errNum = $this->lastErrno();
951 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
952 $this->mStmtOptions
);
954 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
955 $this->mStmtOptions
);
960 $olde = error_reporting( $olde );
961 // Set the affected row count for the whole operation
962 $this->mAffectedRows
= $numrowsinserted;
966 $this->freePrepared( $stmt );
972 * Given a table name and a hash of columns with values
973 * Removes primary key columns from the hash where the value is NULL
975 * @param $table String: name of the table
976 * @param $args Array of hashes of column names with values
977 * @return Array: tuple( filtered array of columns, array of primary keys )
979 private function removeNullPrimaryKeys( $table, $args ) {
980 $schema = $this->mSchema
;
981 // find out the primary keys
982 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
987 $row = $this->fetchObject( $keyres );
989 $row = $this->fetchObject( $keyres )
992 $keys[] = strtolower( $row->column_name
);
994 // remove primary keys
995 foreach ( $args as $ai => $row ) {
996 foreach ( $keys as $key ) {
997 if ( $row[$key] == null ) {
1003 // return modified hash
1004 return array( $args, $keys );
1008 * UPDATE wrapper, takes a condition array and a SET array
1010 * @param $table String: The table to UPDATE
1011 * @param $values An array of values to SET
1012 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1013 * @param $fname String: The Class::Function calling this function
1015 * @param $options An array of UPDATE options, can be one or
1016 * more of IGNORE, LOW_PRIORITY
1019 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1020 $options = array() )
1022 $table = $this->tableName( $table );
1023 $opts = $this->makeUpdateOptions( $options );
1024 $sql = "UPDATE $opts $table SET "
1025 . $this->makeList( $values, LIST_SET_PREPARED
);
1026 if ( $conds != '*' ) {
1027 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1029 $stmt = $this->prepare( $sql );
1030 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1031 // assuming for now that an array with string keys will work
1032 // if not, convert to simple array first
1033 $result = $this->execute( $stmt, $values );
1034 $this->freePrepared( $stmt );
1040 * DELETE query wrapper
1042 * Use $conds == "*" to delete all rows
1044 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1046 throw new DBUnexpectedError( $this,
1047 'DatabaseIbm_db2::delete() called with no conditions' );
1049 $table = $this->tableName( $table );
1050 $sql = "DELETE FROM $table";
1051 if ( $conds != '*' ) {
1052 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1054 $result = $this->query( $sql, $fname );
1060 * Returns the number of rows affected by the last query or 0
1061 * @return Integer: the number of rows affected by the last query
1063 public function affectedRows() {
1064 if ( !is_null( $this->mAffectedRows
) ) {
1065 // Forced result for simulated queries
1066 return $this->mAffectedRows
;
1068 if( empty( $this->mLastResult
) ) {
1071 return db2_num_rows( $this->mLastResult
);
1075 * Simulates REPLACE with a DELETE followed by INSERT
1076 * @param $table Object
1077 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1078 * @param $rows Array: rows to insert
1079 * @param $fname String: name of the function for profiling
1082 function replace( $table, $uniqueIndexes, $rows,
1083 $fname = 'DatabaseIbm_db2::replace' )
1085 $table = $this->tableName( $table );
1087 if ( count( $rows )==0 ) {
1092 if ( !is_array( reset( $rows ) ) ) {
1093 $rows = array( $rows );
1096 foreach( $rows as $row ) {
1097 # Delete rows which collide
1098 if ( $uniqueIndexes ) {
1099 $sql = "DELETE FROM $table WHERE ";
1101 foreach ( $uniqueIndexes as $index ) {
1108 if ( is_array( $index ) ) {
1110 foreach ( $index as $col ) {
1116 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1119 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1123 $this->query( $sql, $fname );
1126 # Now insert the row
1127 $sql = "INSERT INTO $table ( "
1128 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1129 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1130 $this->query( $sql, $fname );
1135 * Returns the number of rows in the result set
1136 * Has to be called right after the corresponding select query
1137 * @param $res Object result set
1138 * @return Integer: number of rows
1140 public function numRows( $res ) {
1141 if ( $res instanceof ResultWrapper
) {
1142 $res = $res->result
;
1144 if ( $this->mNumRows
) {
1145 return $this->mNumRows
;
1152 * Moves the row pointer of the result set
1153 * @param $res Object: result set
1154 * @param $row Integer: row number
1155 * @return success or failure
1157 public function dataSeek( $res, $row ) {
1158 if ( $res instanceof ResultWrapper
) {
1159 $res = $res->result
;
1161 return db2_fetch_row( $res, $row );
1165 # Fix notices in Block.php
1169 * Frees memory associated with a statement resource
1170 * @param $res Object: statement resource to free
1171 * @return Boolean success or failure
1173 public function freeResult( $res ) {
1174 if ( $res instanceof ResultWrapper
) {
1175 $res = $res->result
;
1177 if ( !@db2_free_result
( $res ) ) {
1178 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1183 * Returns the number of columns in a resource
1184 * @param $res Object: statement resource
1185 * @return Number of fields/columns in resource
1187 public function numFields( $res ) {
1188 if ( $res instanceof ResultWrapper
) {
1189 $res = $res->result
;
1191 return db2_num_fields( $res );
1195 * Returns the nth column name
1196 * @param $res Object: statement resource
1197 * @param $n Integer: Index of field or column
1198 * @return String name of nth column
1200 public function fieldName( $res, $n ) {
1201 if ( $res instanceof ResultWrapper
) {
1202 $res = $res->result
;
1204 return db2_field_name( $res, $n );
1210 * @param $table Array or string, table name(s) (prefix auto-added)
1211 * @param $vars Array or string, field name(s) to be retrieved
1212 * @param $conds Array or string, condition(s) for WHERE
1213 * @param $fname String: calling function name (use __METHOD__)
1214 * for logs/profiling
1215 * @param $options Associative array of options
1216 * (e.g. array('GROUP BY' => 'page_title')),
1217 * see Database::makeSelectOptions code for list of
1219 * @param $join_conds Associative array of table join conditions (optional)
1220 * (e.g. array( 'page' => array('LEFT JOIN',
1221 * 'page_latest=rev_id') )
1222 * @return Mixed: database result resource for fetch functions or false
1225 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1227 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1230 // We must adjust for offset
1231 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1232 $limit = $options['LIMIT'];
1233 $offset = $options['OFFSET'];
1236 // DB2 does not have a proper num_rows() function yet, so we must emulate
1237 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1241 // we want the count
1242 $vars2 = array( 'count( * ) as num_rows' );
1243 // respecting just the limit option
1244 $options2 = array();
1245 if ( isset( $options['LIMIT'] ) ) {
1246 $options2['LIMIT'] = $options['LIMIT'];
1248 // but don't try to emulate for GROUP BY
1249 if ( isset( $options['GROUP BY'] ) ) {
1253 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1255 $obj = $this->fetchObject( $res2 );
1256 $this->mNumRows
= $obj->num_rows
;
1262 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1263 * Has limited support for per-column options (colnum => 'DISTINCT')
1267 * @param $options Associative array of options to be turned into
1268 * an SQL query, valid keys are listed in the function.
1271 function makeSelectOptions( $options ) {
1272 $preLimitTail = $postLimitTail = '';
1275 $noKeyOptions = array();
1276 foreach ( $options as $key => $option ) {
1277 if ( is_numeric( $key ) ) {
1278 $noKeyOptions[$option] = true;
1282 if ( isset( $options['GROUP BY'] ) ) {
1283 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1285 if ( isset( $options['HAVING'] ) ) {
1286 $preLimitTail .= " HAVING {$options['HAVING']}";
1288 if ( isset( $options['ORDER BY'] ) ) {
1289 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1292 if ( isset( $noKeyOptions['DISTINCT'] )
1293 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1295 $startOpts .= 'DISTINCT';
1298 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1302 * Returns link to IBM DB2 free download
1303 * @return String: wikitext of a link to the server software's web site
1305 public static function getSoftwareLink() {
1306 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1310 * Get search engine class. All subclasses of this
1311 * need to implement this if they wish to use searching.
1315 public function getSearchEngine() {
1316 return 'SearchIBM_DB2';
1320 * Did the last database access fail because of deadlock?
1323 public function wasDeadlock() {
1325 $err = $this->lastErrno();
1327 // This is literal port of the MySQL logic and may be wrong for DB2
1328 case '40001': // sql0911n, Deadlock or timeout, rollback
1329 case '57011': // sql0904n, Resource unavailable, no rollback
1330 case '57033': // sql0913n, Deadlock or timeout, no rollback
1331 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1338 * Ping the server and try to reconnect if it there is no connection
1339 * The connection may be closed and reopened while this happens
1340 * @return Boolean: whether the connection exists
1342 public function ping() {
1343 // db2_ping() doesn't exist
1346 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1347 $this->mPassword
, $this->mServer
, $this->mPort
);
1351 ######################################
1352 # Unimplemented and not applicable
1353 ######################################
1358 public function getStatus( $which = '%' ) {
1359 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1364 * @return string $sql
1366 public function limitResultForUpdate( $sql, $num ) {
1367 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1372 * Only useful with fake prepare like in base Database class
1375 public function fillPreparedArg( $matches ) {
1376 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1380 ######################################
1382 ######################################
1385 * Returns information about an index
1386 * If errors are explicitly ignored, returns NULL on failure
1387 * @param $table String: table name
1388 * @param $index String: index name
1389 * @param $fname String: function name for logging and profiling
1390 * @return Object query row in object form
1392 public function indexInfo( $table, $index,
1393 $fname = 'DatabaseIbm_db2::indexExists' )
1395 $table = $this->tableName( $table );
1397 SELECT name as indexname
1398 FROM sysibm.sysindexes si
1399 WHERE si.name='$index' AND si.tbname='$table'
1400 AND sc.tbcreator='$this->mSchema'
1402 $res = $this->query( $sql, $fname );
1406 $row = $this->fetchObject( $res );
1407 if ( $row != null ) {
1415 * Returns an information object on a table column
1416 * @param $table String: table name
1417 * @param $field String: column name
1418 * @return IBM_DB2Field
1420 public function fieldInfo( $table, $field ) {
1421 return IBM_DB2Field
::fromText( $this, $table, $field );
1425 * db2_field_type() wrapper
1426 * @param $res Object: result of executed statement
1427 * @param $index Mixed: number or name of the column
1428 * @return String column type
1430 public function fieldType( $res, $index ) {
1431 if ( $res instanceof ResultWrapper
) {
1432 $res = $res->result
;
1434 return db2_field_type( $res, $index );
1438 * Verifies that an index was created as unique
1439 * @param $table String: table name
1440 * @param $index String: index name
1441 * @param $fname function name for profiling
1444 public function indexUnique ( $table, $index,
1445 $fname = 'DatabaseIbm_db2::indexUnique' )
1447 $table = $this->tableName( $table );
1449 SELECT si.name as indexname
1450 FROM sysibm.sysindexes si
1451 WHERE si.name='$index' AND si.tbname='$table'
1452 AND sc.tbcreator='$this->mSchema'
1453 AND si.uniquerule IN ( 'U', 'P' )
1455 $res = $this->query( $sql, $fname );
1459 if ( $this->fetchObject( $res ) ) {
1467 * Returns the size of a text field, or -1 for "unlimited"
1468 * @param $table String: table name
1469 * @param $field String: column name
1470 * @return Integer: length or -1 for unlimited
1472 public function textFieldSize( $table, $field ) {
1473 $table = $this->tableName( $table );
1475 SELECT length as size
1476 FROM sysibm.syscolumns sc
1477 WHERE sc.name='$field' AND sc.tbname='$table'
1478 AND sc.tbcreator='$this->mSchema'
1480 $res = $this->query( $sql );
1481 $row = $this->fetchObject( $res );
1487 * DELETE where the condition is a join
1488 * @param $delTable String: deleting from this table
1489 * @param $joinTable String: using data from this table
1490 * @param $delVar String: variable in deleteable table
1491 * @param $joinVar String: variable in data table
1492 * @param $conds Array: conditionals for join table
1493 * @param $fname String: function name for profiling
1495 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1496 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1499 throw new DBUnexpectedError( $this,
1500 'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
1503 $delTable = $this->tableName( $delTable );
1504 $joinTable = $this->tableName( $joinTable );
1506 DELETE FROM $delTable
1508 SELECT $joinVar FROM $joinTable
1511 if ( $conds != '*' ) {
1512 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1516 $this->query( $sql, $fname );
1520 * Description is left as an exercise for the reader
1521 * @param $b Mixed: data to be encoded
1522 * @return IBM_DB2Blob
1524 public function encodeBlob( $b ) {
1525 return new IBM_DB2Blob( $b );
1529 * Description is left as an exercise for the reader
1530 * @param $b IBM_DB2Blob: data to be decoded
1533 public function decodeBlob( $b ) {
1538 * Convert into a list of string being concatenated
1539 * @param $stringList Array: strings that need to be joined together
1541 * @return String: joined by the concatenation operator
1543 public function buildConcat( $stringList ) {
1544 // || is equivalent to CONCAT
1545 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1546 return implode( ' || ', $stringList );
1550 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1551 * @param $column String: name of timestamp column
1552 * @return String: SQL code
1554 public function extractUnixEpoch( $column ) {
1556 // see SpecialAncientpages
1559 ######################################
1560 # Prepared statements
1561 ######################################
1564 * Intended to be compatible with the PEAR::DB wrapper functions.
1565 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1567 * ? = scalar value, quoted as necessary
1568 * ! = raw SQL bit (a function for instance)
1569 * & = filename; reads the file and inserts as a blob
1570 * (we don't use this though...)
1571 * @param $sql String: SQL statement with appropriate markers
1572 * @param $func String: Name of the function, for profiling
1573 * @return resource a prepared DB2 SQL statement
1575 public function prepare( $sql, $func = 'DB2::prepare' ) {
1576 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1581 * Frees resources associated with a prepared statement
1582 * @return Boolean success or failure
1584 public function freePrepared( $prepared ) {
1585 return db2_free_stmt( $prepared );
1589 * Execute a prepared query with the various arguments
1590 * @param $prepared String: the prepared sql
1591 * @param $args Mixed: either an array here, or put scalars as varargs
1592 * @return Resource: results object
1594 public function execute( $prepared, $args = null ) {
1595 if( !is_array( $args ) ) {
1597 $args = func_get_args();
1598 array_shift( $args );
1600 $res = db2_execute( $prepared, $args );
1602 $this->installPrint( db2_stmt_errormsg() );
1608 * Prepare & execute an SQL statement, quoting and inserting arguments
1609 * in the appropriate places.
1610 * @param $query String
1613 public function safeQuery( $query, $args = null ) {
1614 // copied verbatim from Database.php
1615 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1616 if( !is_array( $args ) ) {
1618 $args = func_get_args();
1619 array_shift( $args );
1621 $retval = $this->execute( $prepared, $args );
1622 $this->freePrepared( $prepared );
1627 * For faking prepared SQL statements on DBs that don't support
1629 * @param $preparedQuery String: a 'preparable' SQL statement
1630 * @param $args Array of arguments to fill it with
1631 * @return String: executable statement
1633 public function fillPrepared( $preparedQuery, $args ) {
1635 $this->preparedArgs
=& $args;
1637 foreach ( $args as $i => $arg ) {
1638 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1641 return $preparedQuery;
1645 * Switches module between regular and install modes
1647 public function setMode( $mode ) {
1648 $old = $this->mMode
;
1649 $this->mMode
= $mode;
1654 * Bitwise negation of a column or value in SQL
1655 * Same as (~field) in C
1656 * @param $field String
1659 function bitNot( $field ) {
1660 // expecting bit-fields smaller than 4bytes
1661 return "BITNOT( $field )";
1665 * Bitwise AND of two columns or values in SQL
1666 * Same as (fieldLeft & fieldRight) in C
1667 * @param $fieldLeft String
1668 * @param $fieldRight String
1671 function bitAnd( $fieldLeft, $fieldRight ) {
1672 return "BITAND( $fieldLeft, $fieldRight )";
1676 * Bitwise OR of two columns or values in SQL
1677 * Same as (fieldLeft | fieldRight) in C
1678 * @param $fieldLeft String
1679 * @param $fieldRight String
1682 function bitOr( $fieldLeft, $fieldRight ) {
1683 return "BITOR( $fieldLeft, $fieldRight )";
1687 class IBM_DB2Helper
{
1688 public static function makeArray( $maybeArray ) {
1689 if ( !is_array( $maybeArray ) ) {
1690 return array( $maybeArray );