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 * Wrapper to address lack of certain operations in the DB2 driver
116 private $current_pos;
117 private $columns = array();
120 private $resultSet = array();
121 private $loadedLines = 0;
124 * Construct and initialize a wrapper for DB2 query results
125 * @param $db DatabaseBase
126 * @param $result Object
127 * @param $num_rows Integer
129 * @param $columns Array
131 public function __construct( $db, $result, $num_rows, $sql, $columns ){
134 if( $result instanceof ResultWrapper
){
135 $this->result
= $result->result
;
138 $this->result
= $result;
141 $this->num_rows
= $num_rows;
142 $this->current_pos
= 0;
143 if ( $this->num_rows
> 0 ) {
144 // Make a lower-case list of the column names
145 // By default, DB2 column names are capitalized
146 // while MySQL column names are lowercase
148 // Is there a reasonable maximum value for $i?
149 // Setting to 2048 to prevent an infinite loop
150 for( $i = 0; $i < 2048; $i++
) {
151 $name = db2_field_name( $this->result
, $i );
152 if ( $name != false ) {
159 $this->columns
[$i] = strtolower( $name );
167 * Unwrap the DB2 query results
168 * @return mixed Object on success, false on failure
170 public function getResult() {
171 if ( $this->result
) {
172 return $this->result
;
178 * Get the number of rows in the result set
181 public function getNum_rows() {
182 return $this->num_rows
;
186 * Return a row from the result set in object format
187 * @return mixed Object on success, false on failure.
189 public function fetchObject() {
191 && $this->num_rows
> 0
192 && $this->current_pos
>= 0
193 && $this->current_pos
< $this->num_rows
)
195 $row = $this->fetchRow();
196 $ret = new stdClass();
198 foreach ( $row as $k => $v ) {
199 $lc = $this->columns
[$k];
208 * Return a row form the result set in array format
209 * @return mixed Array on success, false on failure
210 * @throws DBUnexpectedError
212 public function fetchRow(){
214 && $this->num_rows
> 0
215 && $this->current_pos
>= 0
216 && $this->current_pos
< $this->num_rows
)
218 if ( $this->loadedLines
<= $this->current_pos
) {
219 $row = db2_fetch_array( $this->result
);
220 $this->resultSet
[$this->loadedLines++
] = $row;
221 if ( $this->db
->lastErrno() ) {
222 throw new DBUnexpectedError( $this->db
, 'Error in fetchRow(): '
223 . htmlspecialchars( $this->db
->lastError() ) );
227 if ( $this->loadedLines
> $this->current_pos
){
228 return $this->resultSet
[$this->current_pos++
];
236 * Free a DB2 result object
237 * @throws DBUnexpectedError
239 public function freeResult(){
240 unset( $this->resultSet
);
241 if ( !@db2_free_result
( $this->result
) ) {
242 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
248 * Primary database interface
251 class DatabaseIbm_db2
extends DatabaseBase
{
254 protected $mLastQuery = '';
255 protected $mPHPError = false;
257 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
258 protected $mOpened = false;
260 protected $mTablePrefix;
262 protected $mTrxLevel = 0;
263 protected $mErrorCount = 0;
264 protected $mLBInfo = array();
265 protected $mFakeSlaveLag = null, $mFakeMaster = false;
269 /** Database server port */
270 protected $mPort = null;
271 /** Schema for tables, stored procedures, triggers */
272 protected $mSchema = null;
273 /** Whether the schema has been applied in this session */
274 protected $mSchemaSet = false;
275 /** Result of last query */
276 protected $mLastResult = null;
277 /** Number of rows affected by last INSERT/UPDATE/DELETE */
278 protected $mAffectedRows = null;
279 /** Number of rows returned by last SELECT */
280 protected $mNumRows = null;
281 /** Current row number on the cursor of the last SELECT */
282 protected $currentRow = 0;
284 /** Connection config options - see constructor */
285 public $mConnOptions = array();
286 /** Statement config options -- see constructor */
287 public $mStmtOptions = array();
289 /** Default schema */
290 const USE_GLOBAL
= 'get from global';
292 /** Option that applies to nothing */
293 const NONE_OPTION
= 0x00;
294 /** Option that applies to connection objects */
295 const CONN_OPTION
= 0x01;
296 /** Option that applies to statement objects */
297 const STMT_OPTION
= 0x02;
299 /** Regular operation mode -- minimal debug messages */
300 const REGULAR_MODE
= 'regular';
301 /** Installation mode -- lots of debug messages */
302 const INSTALL_MODE
= 'install';
304 /** Controls the level of debug message output */
305 protected $mMode = self
::REGULAR_MODE
;
307 /** Last sequence value used for a primary key */
308 protected $mInsertId = null;
310 ######################################
311 # Getters and Setters
312 ######################################
315 * Returns true if this database supports (and uses) cascading deletes
317 function cascadingDeletes() {
322 * Returns true if this database supports (and uses) triggers (e.g. on the
325 function cleanupTriggers() {
330 * Returns true if this database is strict about what can be put into an
332 * Specifically, it uses a NULL value instead of an empty string.
334 function strictIPs() {
339 * Returns true if this database uses timestamps rather than integers
341 function realTimestamps() {
346 * Returns true if this database does an implicit sort when doing GROUP BY
348 function implicitGroupby() {
353 * Returns true if this database does an implicit order by when the column
355 * For example: SELECT page_title FROM page LIMIT 1
357 function implicitOrderby() {
362 * Returns true if this database can do a native search on IP columns
363 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
365 function searchableIPs() {
370 * Returns true if this database can use functional indexes
372 function functionalIndexes() {
377 * Returns a unique string representing the wiki on the server
379 public function getWikiID() {
380 if( $this->mSchema
) {
381 return "{$this->mDBname}-{$this->mSchema}";
383 return $this->mDBname
;
388 * Returns the database software identifieir
391 public function getType() {
396 * Returns the database connection object
399 public function getDb(){
405 * @param $server String: hostname of database server
406 * @param $user String: username
407 * @param $password String: password
408 * @param $dbName String: database name on the server
409 * @param $flags Integer: database behaviour flags (optional, unused)
410 * @param $schema String
412 public function __construct( $server = false, $user = false,
414 $dbName = false, $flags = 0,
415 $schema = self
::USE_GLOBAL
)
417 global $wgDBmwschema;
419 if ( $schema == self
::USE_GLOBAL
) {
420 $this->mSchema
= $wgDBmwschema;
422 $this->mSchema
= $schema;
425 // configure the connection and statement objects
426 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
427 self
::CONN_OPTION | self
::STMT_OPTION
);
428 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
430 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
432 parent
::__construct( $server, $user, $password, $dbName, DBO_TRX |
$flags );
436 * Enables options only if the ibm_db2 extension version supports them
437 * @param $name String: name of the option in the options array
438 * @param $const String: name of the constant holding the right option value
439 * @param $type Integer: whether this is a Connection or Statement otion
441 private function setDB2Option( $name, $const, $type ) {
442 if ( defined( $const ) ) {
443 if ( $type & self
::CONN_OPTION
) {
444 $this->mConnOptions
[$name] = constant( $const );
446 if ( $type & self
::STMT_OPTION
) {
447 $this->mStmtOptions
[$name] = constant( $const );
451 "$const is not defined. ibm_db2 version is likely too low." );
456 * Outputs debug information in the appropriate place
457 * @param $string String: the relevant debug message
459 private function installPrint( $string ) {
460 wfDebug( "$string\n" );
461 if ( $this->mMode
== self
::INSTALL_MODE
) {
462 print "<li><pre>$string</pre></li>";
468 * Opens a database connection and returns it
469 * Closes any existing connection
471 * @param $server String: hostname
472 * @param $user String
473 * @param $password String
474 * @param $dbName String: database name
475 * @return DatabaseBase a fresh connection
477 public function open( $server, $user, $password, $dbName ) {
478 wfProfileIn( __METHOD__
);
480 # Load IBM DB2 driver if missing
483 # Test for IBM DB2 support, to avoid suppressed fatal error
484 if ( !function_exists( 'db2_connect' ) ) {
485 throw new DBConnectionError( $this, "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?" );
490 // Close existing connection
493 $this->mServer
= $server;
494 $this->mPort
= $port = $wgDBport;
495 $this->mUser
= $user;
496 $this->mPassword
= $password;
497 $this->mDBname
= $dbName;
499 $this->openUncataloged( $dbName, $user, $password, $server, $port );
501 if ( !$this->mConn
) {
502 $this->installPrint( "DB connection error\n" );
504 "Server: $server, Database: $dbName, User: $user, Password: "
505 . substr( $password, 0, 3 ) . "...\n" );
506 $this->installPrint( $this->lastError() . "\n" );
507 wfProfileOut( __METHOD__
);
508 wfDebug( "DB connection error\n" );
509 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
510 wfDebug( $this->lastError() . "\n" );
511 throw new DBConnectionError( $this, $this->lastError() );
514 // Some MediaWiki code is still transaction-less (?).
515 // The strategy is to keep AutoCommit on for that code
516 // but switch it off whenever a transaction is begun.
517 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
519 $this->mOpened
= true;
520 $this->applySchema();
522 wfProfileOut( __METHOD__
);
527 * Opens a cataloged database connection, sets mConn
529 protected function openCataloged( $dbName, $user, $password ) {
530 wfSuppressWarnings();
531 $this->mConn
= db2_pconnect( $dbName, $user, $password );
536 * Opens an uncataloged database connection, sets mConn
538 protected function openUncataloged( $dbName, $user, $password, $server, $port )
540 $dsn = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$dbName;CHARSET=UTF-8;HOSTNAME=$server;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
541 wfSuppressWarnings();
542 $this->mConn
= db2_pconnect( $dsn, "", "", array() );
547 * Closes a database connection, if it is open
548 * Returns success, true if already closed
550 public function close() {
551 $this->mOpened
= false;
552 if ( $this->mConn
) {
553 if ( $this->trxLevel() > 0 ) {
556 return db2_close( $this->mConn
);
563 * Retrieves the most current database error
564 * Forces a database rollback
566 public function lastError() {
567 $connerr = db2_conn_errormsg();
572 $stmterr = db2_stmt_errormsg();
582 * Get the last error number
583 * Return 0 if no error
586 public function lastErrno() {
587 $connerr = db2_conn_error();
591 $stmterr = db2_stmt_error();
599 * Is a database connection open?
602 public function isOpen() { return $this->mOpened
; }
605 * The DBMS-dependent part of query()
606 * @param $sql String: SQL query.
607 * @return object Result object for fetch functions or false on failure
609 protected function doQuery( $sql ) {
610 $this->applySchema();
612 // Needed to handle any UTF-8 encoding issues in the raw sql
613 // Note that we fully support prepared statements for DB2
614 // prepare() and execute() should be used instead of doQuery() whenever possible
615 $sql = utf8_decode( $sql );
617 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
618 if( $ret == false ) {
619 $error = db2_stmt_errormsg();
621 $this->installPrint( "<pre>$sql</pre>" );
622 $this->installPrint( $error );
623 throw new DBUnexpectedError( $this, 'SQL error: '
624 . htmlspecialchars( $error ) );
626 $this->mLastResult
= $ret;
627 $this->mAffectedRows
= null; // Not calculated until asked for
632 * @return string Version information from the database
634 public function getServerVersion() {
635 $info = db2_server_info( $this->mConn
);
636 return $info->DBMS_VER
;
640 * Queries whether a given table exists
643 public function tableExists( $table, $fname = __METHOD__
) {
644 $schema = $this->mSchema
;
646 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
647 strtoupper( $table ) .
648 "' AND ST.CREATOR = '" .
649 strtoupper( $schema ) . "'";
650 $res = $this->query( $sql );
655 // If the table exists, there should be one of it
656 $row = $this->fetchRow( $res );
658 if ( $count == '1' ||
$count == 1 ) {
666 * Fetch the next row from the given result object, in object form.
667 * Fields can be retrieved with $row->fieldname, with fields acting like
670 * @param $res SQL result object as returned from Database::query(), etc.
671 * @return DB2 row object
672 * @throws DBUnexpectedError Thrown if the database returns an error
674 public function fetchObject( $res ) {
675 if ( $res instanceof ResultWrapper
) {
678 wfSuppressWarnings();
679 $row = db2_fetch_object( $res );
681 if( $this->lastErrno() ) {
682 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
683 . htmlspecialchars( $this->lastError() ) );
689 * Fetch the next row from the given result object, in associative array
690 * form. Fields are retrieved with $row['fieldname'].
692 * @param $res SQL result object as returned from Database::query(), etc.
693 * @return DB2 row object
694 * @throws DBUnexpectedError Thrown if the database returns an error
696 public function fetchRow( $res ) {
697 if ( $res instanceof ResultWrapper
) {
700 if ( db2_num_rows( $res ) > 0) {
701 wfSuppressWarnings();
702 $row = db2_fetch_array( $res );
704 if ( $this->lastErrno() ) {
705 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
706 . htmlspecialchars( $this->lastError() ) );
715 * Doesn't escape numbers
717 * @param $s String: string to escape
718 * @return escaped string
720 public function addQuotes( $s ) {
721 //$this->installPrint( "DB2::addQuotes( $s )\n" );
722 if ( is_null( $s ) ) {
724 } elseif ( $s instanceof Blob
) {
725 return "'" . $s->fetch( $s ) . "'";
726 } elseif ( $s instanceof IBM_DB2Blob
) {
727 return "'" . $this->decodeBlob( $s ) . "'";
729 $s = $this->strencode( $s );
730 if ( is_numeric( $s ) ) {
738 * Verifies that a DB2 column/field type is numeric
740 * @param $type String: DB2 column type
741 * @return Boolean: true if numeric
743 public function is_numeric_type( $type ) {
744 switch ( strtoupper( $type ) ) {
759 * Alias for addQuotes()
760 * @param $s String: string to escape
761 * @return escaped string
763 public function strencode( $s ) {
764 // Bloody useless function
765 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
766 // But also necessary
767 $s = db2_escape_string( $s );
768 // Wide characters are evil -- some of them look like '
769 $s = utf8_encode( $s );
771 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
772 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
773 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
778 * Switch into the database schema
780 protected function applySchema() {
781 if ( !( $this->mSchemaSet
) ) {
782 $this->mSchemaSet
= true;
784 $this->doQuery( "SET SCHEMA = $this->mSchema" );
790 * Start a transaction (mandatory)
792 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
793 // BEGIN is implicit for DB2
794 // However, it requires that AutoCommit be off.
796 // Some MediaWiki code is still transaction-less (?).
797 // The strategy is to keep AutoCommit on for that code
798 // but switch it off whenever a transaction is begun.
799 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
801 $this->mTrxLevel
= 1;
806 * Must have a preceding begin()
808 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
809 db2_commit( $this->mConn
);
811 // Some MediaWiki code is still transaction-less (?).
812 // The strategy is to keep AutoCommit on for that code
813 // but switch it off whenever a transaction is begun.
814 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
816 $this->mTrxLevel
= 0;
820 * Cancel a transaction
822 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
823 db2_rollback( $this->mConn
);
824 // turn auto-commit back on
825 // not sure if this is appropriate
826 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
827 $this->mTrxLevel
= 0;
831 * Makes an encoded list of strings from an array
833 * LIST_COMMA - comma separated, no field names
834 * LIST_AND - ANDed WHERE clause (without the WHERE)
835 * LIST_OR - ORed WHERE clause (without the WHERE)
836 * LIST_SET - comma separated with field names, like a SET clause
837 * LIST_NAMES - comma separated field names
838 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
840 function makeList( $a, $mode = LIST_COMMA
) {
841 if ( !is_array( $a ) ) {
842 throw new DBUnexpectedError( $this,
843 'DatabaseIbm_db2::makeList called with incorrect parameters' );
846 // if this is for a prepared UPDATE statement
847 // (this should be promoted to the parent class
848 // once other databases use prepared statements)
849 if ( $mode == LIST_SET_PREPARED
) {
852 foreach ( $a as $field => $value ) {
854 $list .= ", $field = ?";
856 $list .= "$field = ?";
865 // otherwise, call the usual function
866 return parent
::makeList( $a, $mode );
870 * Construct a LIMIT query with optional offset
871 * This is used for query pages
873 * @param $sql string SQL query we will append the limit too
874 * @param $limit integer the SQL limit
875 * @param $offset integer the SQL offset (default false)
877 public function limitResult( $sql, $limit, $offset=false ) {
878 if( !is_numeric( $limit ) ) {
879 throw new DBUnexpectedError( $this,
880 "Invalid non-numeric limit passed to limitResult()\n" );
883 if ( stripos( $sql, 'where' ) === false ) {
884 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
886 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
889 return "$sql FETCH FIRST $limit ROWS ONLY ";
893 * Handle reserved keyword replacement in table names
895 * @param $name Object
896 * @param $format String Ignored parameter Default 'quoted'Boolean
899 public function tableName( $name, $format = 'quoted' ) {
900 // we want maximum compatibility with MySQL schema
905 * Generates a timestamp in an insertable format
907 * @param $ts timestamp
908 * @return String: timestamp value
910 public function timestamp( $ts = 0 ) {
911 // TS_MW cannot be easily distinguished from an integer
912 return wfTimestamp( TS_DB2
, $ts );
916 * Return the next in a sequence, save the value for retrieval via insertId()
917 * @param $seqName String: name of a defined sequence in the database
918 * @return next value in that sequence
920 public function nextSequenceValue( $seqName ) {
921 // Not using sequences in the primary schema to allow for easier migration
923 // Emulating MySQL behaviour of using NULL to signal that sequences
926 $safeseq = preg_replace( "/'/", "''", $seqName );
927 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
928 $row = $this->fetchRow( $res );
929 $this->mInsertId = $row[0];
930 return $this->mInsertId;
936 * This must be called after nextSequenceVal
937 * @return Last sequence value used as a primary key
939 public function insertId() {
940 return $this->mInsertId
;
944 * Updates the mInsertId property with the value of the last insert
945 * into a generated column
947 * @param $table String: sanitized table name
948 * @param $primaryKey Mixed: string name of the primary key
949 * @param $stmt Resource: prepared statement resource
950 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
952 private function calcInsertId( $table, $primaryKey, $stmt ) {
954 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
959 * INSERT wrapper, inserts an array into a table
961 * $args may be a single associative array, or an array of arrays
962 * with numeric keys, for multi-row insert
964 * @param $table String: Name of the table to insert to.
965 * @param $args Array: Items to insert into the table.
966 * @param $fname String: Name of the function, for profiling
967 * @param $options String or Array. Valid options: IGNORE
969 * @return bool Success of insert operation. IGNORE always returns true.
971 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
974 if ( !count( $args ) ) {
977 // get database-specific table name (not used)
978 $table = $this->tableName( $table );
979 // format options as an array
980 $options = IBM_DB2Helper
::makeArray( $options );
981 // format args as an array of arrays
982 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
983 $args = array( $args );
986 // prevent insertion of NULL into primary key columns
987 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
988 // if there's only one primary key
989 // we'll be able to read its value after insertion
991 if ( count( $primaryKeys ) == 1 ) {
992 $primaryKey = $primaryKeys[0];
996 $keys = array_keys( $args[0] );
997 $key_count = count( $keys );
999 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1000 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1004 // If we are not in a transaction, we need to be for savepoint trickery
1005 if ( !$this->mTrxLevel
) {
1009 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
1010 if ( $key_count == 1 ) {
1013 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1015 $this->installPrint( "Preparing the following SQL:" );
1016 $this->installPrint( "$sql" );
1017 $this->installPrint( print_r( $args, true ));
1018 $stmt = $this->prepare( $sql );
1020 // start a transaction/enter transaction mode
1025 foreach ( $args as $row ) {
1026 //$this->installPrint( "Inserting " . print_r( $row, true ));
1027 // insert each row into the database
1028 $res = $res & $this->execute( $stmt, $row );
1030 $this->installPrint( 'Last error:' );
1031 $this->installPrint( $this->lastError() );
1033 // get the last inserted value into a generated column
1034 $this->calcInsertId( $table, $primaryKey, $stmt );
1037 $olde = error_reporting( 0 );
1038 // For future use, we may want to track the number of actual inserts
1039 // Right now, insert (all writes) simply return true/false
1040 $numrowsinserted = 0;
1042 // always return true
1045 foreach ( $args as $row ) {
1046 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1047 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
1049 $res2 = $this->execute( $stmt, $row );
1052 $this->installPrint( 'Last error:' );
1053 $this->installPrint( $this->lastError() );
1055 // get the last inserted value into a generated column
1056 $this->calcInsertId( $table, $primaryKey, $stmt );
1058 $errNum = $this->lastErrno();
1060 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
1061 $this->mStmtOptions
);
1063 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
1064 $this->mStmtOptions
);
1069 $olde = error_reporting( $olde );
1070 // Set the affected row count for the whole operation
1071 $this->mAffectedRows
= $numrowsinserted;
1073 // commit either way
1075 $this->freePrepared( $stmt );
1081 * Given a table name and a hash of columns with values
1082 * Removes primary key columns from the hash where the value is NULL
1084 * @param $table String: name of the table
1085 * @param $args Array of hashes of column names with values
1086 * @return Array: tuple( filtered array of columns, array of primary keys )
1088 private function removeNullPrimaryKeys( $table, $args ) {
1089 $schema = $this->mSchema
;
1091 // find out the primary keys
1092 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
1093 . strtoupper( $table )
1094 . "' AND TBCREATOR = '"
1095 . strtoupper( $schema )
1096 . "' AND KEYSEQ > 0" );
1100 $row = $this->fetchRow( $keyres );
1102 $row = $this->fetchRow( $keyres )
1105 $keys[] = strtolower( $row[0] );
1107 // remove primary keys
1108 foreach ( $args as $ai => $row ) {
1109 foreach ( $keys as $key ) {
1110 if ( $row[$key] == null ) {
1111 unset( $row[$key] );
1116 // return modified hash
1117 return array( $args, $keys );
1121 * UPDATE wrapper, takes a condition array and a SET array
1123 * @param $table String: The table to UPDATE
1124 * @param $values An array of values to SET
1125 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1126 * @param $fname String: The Class::Function calling this function
1128 * @param $options An array of UPDATE options, can be one or
1129 * more of IGNORE, LOW_PRIORITY
1132 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1133 $options = array() )
1135 $table = $this->tableName( $table );
1136 $opts = $this->makeUpdateOptions( $options );
1137 $sql = "UPDATE $opts $table SET "
1138 . $this->makeList( $values, LIST_SET_PREPARED
);
1139 if ( $conds != '*' ) {
1140 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1142 $stmt = $this->prepare( $sql );
1143 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1144 // assuming for now that an array with string keys will work
1145 // if not, convert to simple array first
1146 $result = $this->execute( $stmt, $values );
1147 $this->freePrepared( $stmt );
1153 * DELETE query wrapper
1155 * Use $conds == "*" to delete all rows
1157 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1159 throw new DBUnexpectedError( $this,
1160 'DatabaseIbm_db2::delete() called with no conditions' );
1162 $table = $this->tableName( $table );
1163 $sql = "DELETE FROM $table";
1164 if ( $conds != '*' ) {
1165 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1167 $result = $this->query( $sql, $fname );
1173 * Returns the number of rows affected by the last query or 0
1174 * @return Integer: the number of rows affected by the last query
1176 public function affectedRows() {
1177 if ( !is_null( $this->mAffectedRows
) ) {
1178 // Forced result for simulated queries
1179 return $this->mAffectedRows
;
1181 if( empty( $this->mLastResult
) ) {
1184 return db2_num_rows( $this->mLastResult
);
1188 * Returns the number of rows in the result set
1189 * Has to be called right after the corresponding select query
1190 * @param $res Object result set
1191 * @return Integer: number of rows
1193 public function numRows( $res ) {
1194 if ( $res instanceof ResultWrapper
) {
1195 $res = $res->result
;
1198 if ( $this->mNumRows
) {
1199 return $this->mNumRows
;
1206 * Moves the row pointer of the result set
1207 * @param $res Object: result set
1208 * @param $row Integer: row number
1209 * @return success or failure
1211 public function dataSeek( $res, $row ) {
1212 if ( $res instanceof ResultWrapper
) {
1213 return $res = $res->result
;
1215 if ( $res instanceof IBM_DB2Result
) {
1216 return $res->dataSeek( $row );
1218 wfDebug( "dataSeek operation in DB2 database\n" );
1223 # Fix notices in Block.php
1227 * Frees memory associated with a statement resource
1228 * @param $res Object: statement resource to free
1229 * @return Boolean success or failure
1231 public function freeResult( $res ) {
1232 if ( $res instanceof ResultWrapper
) {
1233 $res = $res->result
;
1235 wfSuppressWarnings();
1236 $ok = db2_free_result( $res );
1237 wfRestoreWarnings();
1239 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1244 * Returns the number of columns in a resource
1245 * @param $res Object: statement resource
1246 * @return Number of fields/columns in resource
1248 public function numFields( $res ) {
1249 if ( $res instanceof ResultWrapper
) {
1250 $res = $res->result
;
1252 if ( $res instanceof IBM_DB2Result
) {
1253 $res = $res->getResult();
1255 return db2_num_fields( $res );
1259 * Returns the nth column name
1260 * @param $res Object: statement resource
1261 * @param $n Integer: Index of field or column
1262 * @return String name of nth column
1264 public function fieldName( $res, $n ) {
1265 if ( $res instanceof ResultWrapper
) {
1266 $res = $res->result
;
1268 if ( $res instanceof IBM_DB2Result
) {
1269 $res = $res->getResult();
1271 return db2_field_name( $res, $n );
1277 * @param $table Array or string, table name(s) (prefix auto-added)
1278 * @param $vars Array or string, field name(s) to be retrieved
1279 * @param $conds Array or string, condition(s) for WHERE
1280 * @param $fname String: calling function name (use __METHOD__)
1281 * for logs/profiling
1282 * @param $options array Associative array of options
1283 * (e.g. array( 'GROUP BY' => 'page_title' )),
1284 * see Database::makeSelectOptions code for list of
1286 * @param $join_conds array Associative array of table join conditions (optional)
1287 * (e.g. array( 'page' => array('LEFT JOIN',
1288 * 'page_latest=rev_id') )
1289 * @return Mixed: database result resource for fetch functions or false
1292 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1294 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1296 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1298 // We must adjust for offset
1299 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1300 $limit = $options['LIMIT'];
1301 $offset = $options['OFFSET'];
1304 // DB2 does not have a proper num_rows() function yet, so we must emulate
1305 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1309 // we want the count
1310 $vars2 = array( 'count( * ) as num_rows' );
1311 // respecting just the limit option
1312 $options2 = array();
1313 if ( isset( $options['LIMIT'] ) ) {
1314 $options2['LIMIT'] = $options['LIMIT'];
1316 // but don't try to emulate for GROUP BY
1317 if ( isset( $options['GROUP BY'] ) ) {
1321 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1324 $obj = $this->fetchObject( $res2 );
1325 $this->mNumRows
= $obj->num_rows
;
1327 return new ResultWrapper( $this, new IBM_DB2Result( $this, $res, $obj->num_rows
, $vars, $sql ) );
1331 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1332 * Has limited support for per-column options (colnum => 'DISTINCT')
1336 * @param $options array Associative array of options to be turned into
1337 * an SQL query, valid keys are listed in the function.
1340 function makeSelectOptions( $options ) {
1341 $preLimitTail = $postLimitTail = '';
1344 $noKeyOptions = array();
1345 foreach ( $options as $key => $option ) {
1346 if ( is_numeric( $key ) ) {
1347 $noKeyOptions[$option] = true;
1351 if ( isset( $options['GROUP BY'] ) ) {
1352 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1354 if ( isset( $options['HAVING'] ) ) {
1355 $preLimitTail .= " HAVING {$options['HAVING']}";
1357 if ( isset( $options['ORDER BY'] ) ) {
1358 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1361 if ( isset( $noKeyOptions['DISTINCT'] )
1362 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1364 $startOpts .= 'DISTINCT';
1367 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1371 * Returns link to IBM DB2 free download
1372 * @return String: wikitext of a link to the server software's web site
1374 public static function getSoftwareLink() {
1375 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1379 * Get search engine class. All subclasses of this
1380 * need to implement this if they wish to use searching.
1384 public function getSearchEngine() {
1385 return 'SearchIBM_DB2';
1389 * Did the last database access fail because of deadlock?
1392 public function wasDeadlock() {
1394 $err = $this->lastErrno();
1396 // This is literal port of the MySQL logic and may be wrong for DB2
1397 case '40001': // sql0911n, Deadlock or timeout, rollback
1398 case '57011': // sql0904n, Resource unavailable, no rollback
1399 case '57033': // sql0913n, Deadlock or timeout, no rollback
1400 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1407 * Ping the server and try to reconnect if it there is no connection
1408 * The connection may be closed and reopened while this happens
1409 * @return Boolean: whether the connection exists
1411 public function ping() {
1412 // db2_ping() doesn't exist
1415 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1416 $this->mPassword
, $this->mServer
, $this->mPort
);
1420 ######################################
1421 # Unimplemented and not applicable
1422 ######################################
1425 * @return string $sql
1427 public function limitResultForUpdate( $sql, $num ) {
1428 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1433 * Only useful with fake prepare like in base Database class
1436 public function fillPreparedArg( $matches ) {
1437 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1441 ######################################
1443 ######################################
1446 * Returns information about an index
1447 * If errors are explicitly ignored, returns NULL on failure
1448 * @param $table String: table name
1449 * @param $index String: index name
1450 * @param $fname String: function name for logging and profiling
1451 * @return Object query row in object form
1453 public function indexInfo( $table, $index,
1454 $fname = 'DatabaseIbm_db2::indexExists' )
1456 $table = $this->tableName( $table );
1458 SELECT name as indexname
1459 FROM sysibm.sysindexes si
1460 WHERE si.name='$index' AND si.tbname='$table'
1461 AND sc.tbcreator='$this->mSchema'
1463 $res = $this->query( $sql, $fname );
1467 $row = $this->fetchObject( $res );
1468 if ( $row != null ) {
1476 * Returns an information object on a table column
1477 * @param $table String: table name
1478 * @param $field String: column name
1479 * @return IBM_DB2Field
1481 public function fieldInfo( $table, $field ) {
1482 return IBM_DB2Field
::fromText( $this, $table, $field );
1486 * db2_field_type() wrapper
1487 * @param $res Object: result of executed statement
1488 * @param $index Mixed: number or name of the column
1489 * @return String column type
1491 public function fieldType( $res, $index ) {
1492 if ( $res instanceof ResultWrapper
) {
1493 $res = $res->result
;
1495 if ( $res instanceof IBM_DB2Result
) {
1496 $res = $res->getResult();
1498 return db2_field_type( $res, $index );
1502 * Verifies that an index was created as unique
1503 * @param $table String: table name
1504 * @param $index String: index name
1505 * @param $fname function name for profiling
1508 public function indexUnique ( $table, $index,
1509 $fname = 'DatabaseIbm_db2::indexUnique' )
1511 $table = $this->tableName( $table );
1513 SELECT si.name as indexname
1514 FROM sysibm.sysindexes si
1515 WHERE si.name='$index' AND si.tbname='$table'
1516 AND sc.tbcreator='$this->mSchema'
1517 AND si.uniquerule IN ( 'U', 'P' )
1519 $res = $this->query( $sql, $fname );
1523 if ( $this->fetchObject( $res ) ) {
1531 * Returns the size of a text field, or -1 for "unlimited"
1532 * @param $table String: table name
1533 * @param $field String: column name
1534 * @return Integer: length or -1 for unlimited
1536 public function textFieldSize( $table, $field ) {
1537 $table = $this->tableName( $table );
1539 SELECT length as size
1540 FROM sysibm.syscolumns sc
1541 WHERE sc.name='$field' AND sc.tbname='$table'
1542 AND sc.tbcreator='$this->mSchema'
1544 $res = $this->query( $sql );
1545 $row = $this->fetchObject( $res );
1551 * Description is left as an exercise for the reader
1552 * @param $b Mixed: data to be encoded
1553 * @return IBM_DB2Blob
1555 public function encodeBlob( $b ) {
1556 return new IBM_DB2Blob( $b );
1560 * Description is left as an exercise for the reader
1561 * @param $b IBM_DB2Blob: data to be decoded
1564 public function decodeBlob( $b ) {
1569 * Convert into a list of string being concatenated
1570 * @param $stringList Array: strings that need to be joined together
1572 * @return String: joined by the concatenation operator
1574 public function buildConcat( $stringList ) {
1575 // || is equivalent to CONCAT
1576 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1577 return implode( ' || ', $stringList );
1581 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1582 * @param $column String: name of timestamp column
1583 * @return String: SQL code
1585 public function extractUnixEpoch( $column ) {
1587 // see SpecialAncientpages
1590 ######################################
1591 # Prepared statements
1592 ######################################
1595 * Intended to be compatible with the PEAR::DB wrapper functions.
1596 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1598 * ? = scalar value, quoted as necessary
1599 * ! = raw SQL bit (a function for instance)
1600 * & = filename; reads the file and inserts as a blob
1601 * (we don't use this though...)
1602 * @param $sql String: SQL statement with appropriate markers
1603 * @param $func String: Name of the function, for profiling
1604 * @return resource a prepared DB2 SQL statement
1606 public function prepare( $sql, $func = 'DB2::prepare' ) {
1607 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1612 * Frees resources associated with a prepared statement
1613 * @return Boolean success or failure
1615 public function freePrepared( $prepared ) {
1616 return db2_free_stmt( $prepared );
1620 * Execute a prepared query with the various arguments
1621 * @param $prepared String: the prepared sql
1622 * @param $args Mixed: either an array here, or put scalars as varargs
1623 * @return Resource: results object
1625 public function execute( $prepared, $args = null ) {
1626 if( !is_array( $args ) ) {
1628 $args = func_get_args();
1629 array_shift( $args );
1631 $res = db2_execute( $prepared, $args );
1633 $this->installPrint( db2_stmt_errormsg() );
1639 * Prepare & execute an SQL statement, quoting and inserting arguments
1640 * in the appropriate places.
1641 * @param $query String
1644 public function safeQuery( $query, $args = null ) {
1645 // copied verbatim from Database.php
1646 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1647 if( !is_array( $args ) ) {
1649 $args = func_get_args();
1650 array_shift( $args );
1652 $retval = $this->execute( $prepared, $args );
1653 $this->freePrepared( $prepared );
1658 * For faking prepared SQL statements on DBs that don't support
1660 * @param $preparedQuery String: a 'preparable' SQL statement
1661 * @param $args Array of arguments to fill it with
1662 * @return String: executable statement
1664 public function fillPrepared( $preparedQuery, $args ) {
1666 $this->preparedArgs
=& $args;
1668 foreach ( $args as $i => $arg ) {
1669 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1672 return $preparedQuery;
1676 * Switches module between regular and install modes
1678 public function setMode( $mode ) {
1679 $old = $this->mMode
;
1680 $this->mMode
= $mode;
1685 * Bitwise negation of a column or value in SQL
1686 * Same as (~field) in C
1687 * @param $field String
1690 function bitNot( $field ) {
1691 // expecting bit-fields smaller than 4bytes
1692 return "BITNOT( $field )";
1696 * Bitwise AND of two columns or values in SQL
1697 * Same as (fieldLeft & fieldRight) in C
1698 * @param $fieldLeft String
1699 * @param $fieldRight String
1702 function bitAnd( $fieldLeft, $fieldRight ) {
1703 return "BITAND( $fieldLeft, $fieldRight )";
1707 * Bitwise OR of two columns or values in SQL
1708 * Same as (fieldLeft | fieldRight) in C
1709 * @param $fieldLeft String
1710 * @param $fieldRight String
1713 function bitOr( $fieldLeft, $fieldRight ) {
1714 return "BITOR( $fieldLeft, $fieldRight )";
1718 class IBM_DB2Helper
{
1719 public static function makeArray( $maybeArray ) {
1720 if ( !is_array( $maybeArray ) ) {
1721 return array( $maybeArray );