3 * This is the IBM DB2 database abstraction layer.
4 * See maintenance/ibm_db2/README for development notes
5 * and other specific information.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
24 * @author leo.petr+mediawiki@gmail.com
28 * This represents a column in a DB2 database
31 class IBM_DB2Field
implements Field
{
33 private $tablename = '';
35 private $nullable = false;
36 private $max_length = 0;
39 * Builder method for the class
40 * @param $db DatabaseIbm_db2: Database interface
41 * @param $table String: table name
42 * @param $field String: column name
43 * @return IBM_DB2Field
45 static function fromText( $db, $table, $field ) {
50 lcase( coltype ) AS typname,
51 nulls AS attnotnull, length AS attlen
52 FROM sysibm.syscolumns
53 WHERE tbcreator=%s AND tbname=%s AND name=%s;
57 $db->addQuotes( $wgDBmwschema ),
58 $db->addQuotes( $table ),
59 $db->addQuotes( $field )
62 $row = $db->fetchObject( $res );
66 $n = new IBM_DB2Field
;
67 $n->type
= $row->typname
;
68 $n->nullable
= ( $row->attnotnull
== 'N' );
70 $n->tablename
= $table;
71 $n->max_length
= $row->attlen
;
76 * @return string column name
78 function name() { return $this->name
; }
81 * @return string table name
83 function tableName() { return $this->tablename
; }
86 * @return string column type
88 function type() { return $this->type
; }
91 * @return bool true or false
93 function isNullable() { return $this->nullable
; }
95 * How much can you fit in the column per row?
98 function maxLength() { return $this->max_length
; }
102 * Wrapper around binary large objects
108 public function __construct( $data ) {
109 $this->mData
= $data;
112 public function getData() {
116 public function __toString() {
122 * Wrapper to address lack of certain operations in the DB2 driver
131 private $current_pos;
132 private $columns = array();
135 private $resultSet = array();
136 private $loadedLines = 0;
139 * Construct and initialize a wrapper for DB2 query results
140 * @param $db DatabaseBase
141 * @param $result Object
142 * @param $num_rows Integer
144 * @param $columns Array
146 public function __construct( $db, $result, $num_rows, $sql, $columns ) {
149 if( $result instanceof ResultWrapper
) {
150 $this->result
= $result->result
;
152 $this->result
= $result;
155 $this->num_rows
= $num_rows;
156 $this->current_pos
= 0;
157 if ( $this->num_rows
> 0 ) {
158 // Make a lower-case list of the column names
159 // By default, DB2 column names are capitalized
160 // while MySQL column names are lowercase
162 // Is there a reasonable maximum value for $i?
163 // Setting to 2048 to prevent an infinite loop
164 for( $i = 0; $i < 2048; $i++
) {
165 $name = db2_field_name( $this->result
, $i );
166 if ( $name != false ) {
173 $this->columns
[$i] = strtolower( $name );
181 * Unwrap the DB2 query results
182 * @return mixed Object on success, false on failure
184 public function getResult() {
185 if ( $this->result
) {
186 return $this->result
;
192 * Get the number of rows in the result set
195 public function getNum_rows() {
196 return $this->num_rows
;
200 * Return a row from the result set in object format
201 * @return mixed Object on success, false on failure.
203 public function fetchObject() {
205 && $this->num_rows
> 0
206 && $this->current_pos
>= 0
207 && $this->current_pos
< $this->num_rows
)
209 $row = $this->fetchRow();
210 $ret = new stdClass();
212 foreach ( $row as $k => $v ) {
213 $lc = $this->columns
[$k];
222 * Return a row form the result set in array format
223 * @return mixed Array on success, false on failure
224 * @throws DBUnexpectedError
226 public function fetchRow() {
228 && $this->num_rows
> 0
229 && $this->current_pos
>= 0
230 && $this->current_pos
< $this->num_rows
)
232 if ( $this->loadedLines
<= $this->current_pos
) {
233 $row = db2_fetch_array( $this->result
);
234 $this->resultSet
[$this->loadedLines++
] = $row;
235 if ( $this->db
->lastErrno() ) {
236 throw new DBUnexpectedError( $this->db
, 'Error in fetchRow(): '
237 . htmlspecialchars( $this->db
->lastError() ) );
241 if ( $this->loadedLines
> $this->current_pos
) {
242 return $this->resultSet
[$this->current_pos++
];
250 * Free a DB2 result object
251 * @throws DBUnexpectedError
253 public function freeResult() {
254 unset( $this->resultSet
);
255 if ( !@db2_free_result
( $this->result
) ) {
256 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
262 * Primary database interface
265 class DatabaseIbm_db2
extends DatabaseBase
{
268 protected $mLastQuery = '';
269 protected $mPHPError = false;
271 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
272 protected $mOpened = false;
274 protected $mTablePrefix;
276 protected $mTrxLevel = 0;
277 protected $mErrorCount = 0;
278 protected $mLBInfo = array();
279 protected $mFakeSlaveLag = null, $mFakeMaster = false;
283 /** Database server port */
284 protected $mPort = null;
285 /** Schema for tables, stored procedures, triggers */
286 protected $mSchema = null;
287 /** Whether the schema has been applied in this session */
288 protected $mSchemaSet = false;
289 /** Result of last query */
290 protected $mLastResult = null;
291 /** Number of rows affected by last INSERT/UPDATE/DELETE */
292 protected $mAffectedRows = null;
293 /** Number of rows returned by last SELECT */
294 protected $mNumRows = null;
295 /** Current row number on the cursor of the last SELECT */
296 protected $currentRow = 0;
298 /** Connection config options - see constructor */
299 public $mConnOptions = array();
300 /** Statement config options -- see constructor */
301 public $mStmtOptions = array();
303 /** Default schema */
304 const USE_GLOBAL
= 'get from global';
306 /** Option that applies to nothing */
307 const NONE_OPTION
= 0x00;
308 /** Option that applies to connection objects */
309 const CONN_OPTION
= 0x01;
310 /** Option that applies to statement objects */
311 const STMT_OPTION
= 0x02;
313 /** Regular operation mode -- minimal debug messages */
314 const REGULAR_MODE
= 'regular';
315 /** Installation mode -- lots of debug messages */
316 const INSTALL_MODE
= 'install';
318 /** Controls the level of debug message output */
319 protected $mMode = self
::REGULAR_MODE
;
321 /** Last sequence value used for a primary key */
322 protected $mInsertId = null;
324 ######################################
325 # Getters and Setters
326 ######################################
329 * Returns true if this database supports (and uses) cascading deletes
332 function cascadingDeletes() {
337 * Returns true if this database supports (and uses) triggers (e.g. on the
341 function cleanupTriggers() {
346 * Returns true if this database is strict about what can be put into an
348 * Specifically, it uses a NULL value instead of an empty string.
351 function strictIPs() {
356 * Returns true if this database uses timestamps rather than integers
359 function realTimestamps() {
364 * Returns true if this database does an implicit sort when doing GROUP BY
367 function implicitGroupby() {
372 * Returns true if this database does an implicit order by when the column
374 * For example: SELECT page_title FROM page LIMIT 1
377 function implicitOrderby() {
382 * Returns true if this database can do a native search on IP columns
383 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
386 function searchableIPs() {
391 * Returns true if this database can use functional indexes
394 function functionalIndexes() {
399 * Returns a unique string representing the wiki on the server
402 public function getWikiID() {
403 if( $this->mSchema
) {
404 return "{$this->mDBname}-{$this->mSchema}";
406 return $this->mDBname
;
411 * Returns the database software identifieir
414 public function getType() {
419 * Returns the database connection object
422 public function getDb() {
428 * @param $server String: hostname of database server
429 * @param $user String: username
430 * @param $password String: password
431 * @param $dbName String: database name on the server
432 * @param $flags Integer: database behaviour flags (optional, unused)
433 * @param $schema String
435 public function __construct( $server = false, $user = false,
437 $dbName = false, $flags = 0,
438 $schema = self
::USE_GLOBAL
)
440 global $wgDBmwschema;
442 if ( $schema == self
::USE_GLOBAL
) {
443 $this->mSchema
= $wgDBmwschema;
445 $this->mSchema
= $schema;
448 // configure the connection and statement objects
449 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
450 self
::CONN_OPTION | self
::STMT_OPTION
);
451 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
453 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
455 parent
::__construct( $server, $user, $password, $dbName, DBO_TRX |
$flags );
459 * Enables options only if the ibm_db2 extension version supports them
460 * @param $name String: name of the option in the options array
461 * @param $const String: name of the constant holding the right option value
462 * @param $type Integer: whether this is a Connection or Statement otion
464 private function setDB2Option( $name, $const, $type ) {
465 if ( defined( $const ) ) {
466 if ( $type & self
::CONN_OPTION
) {
467 $this->mConnOptions
[$name] = constant( $const );
469 if ( $type & self
::STMT_OPTION
) {
470 $this->mStmtOptions
[$name] = constant( $const );
474 "$const is not defined. ibm_db2 version is likely too low." );
479 * Outputs debug information in the appropriate place
480 * @param $string String: the relevant debug message
482 private function installPrint( $string ) {
483 wfDebug( "$string\n" );
484 if ( $this->mMode
== self
::INSTALL_MODE
) {
485 print "<li><pre>$string</pre></li>";
491 * Opens a database connection and returns it
492 * Closes any existing connection
494 * @param $server String: hostname
495 * @param $user String
496 * @param $password String
497 * @param $dbName String: database name
498 * @throws DBConnectionError
499 * @return DatabaseBase a fresh connection
501 public function open( $server, $user, $password, $dbName ) {
502 wfProfileIn( __METHOD__
);
504 # Load IBM DB2 driver if missing
507 # Test for IBM DB2 support, to avoid suppressed fatal error
508 if ( !function_exists( 'db2_connect' ) ) {
509 throw new DBConnectionError( $this, "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?" );
514 // Close existing connection
517 $this->mServer
= $server;
518 $this->mPort
= $port = $wgDBport;
519 $this->mUser
= $user;
520 $this->mPassword
= $password;
521 $this->mDBname
= $dbName;
523 $this->openUncataloged( $dbName, $user, $password, $server, $port );
525 if ( !$this->mConn
) {
526 $this->installPrint( "DB connection error\n" );
528 "Server: $server, Database: $dbName, User: $user, Password: "
529 . substr( $password, 0, 3 ) . "...\n" );
530 $this->installPrint( $this->lastError() . "\n" );
531 wfProfileOut( __METHOD__
);
532 wfDebug( "DB connection error\n" );
533 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
534 wfDebug( $this->lastError() . "\n" );
535 throw new DBConnectionError( $this, $this->lastError() );
538 // Some MediaWiki code is still transaction-less (?).
539 // The strategy is to keep AutoCommit on for that code
540 // but switch it off whenever a transaction is begun.
541 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
543 $this->mOpened
= true;
544 $this->applySchema();
546 wfProfileOut( __METHOD__
);
551 * Opens a cataloged database connection, sets mConn
553 protected function openCataloged( $dbName, $user, $password ) {
554 wfSuppressWarnings();
555 $this->mConn
= db2_pconnect( $dbName, $user, $password );
560 * Opens an uncataloged database connection, sets mConn
562 protected function openUncataloged( $dbName, $user, $password, $server, $port )
564 $dsn = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$dbName;CHARSET=UTF-8;HOSTNAME=$server;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
565 wfSuppressWarnings();
566 $this->mConn
= db2_pconnect( $dsn, "", "", array() );
571 * Closes a database connection, if it is open
572 * Returns success, true if already closed
575 protected function closeConnection() {
576 return db2_close( $this->mConn
);
580 * Retrieves the most current database error
581 * Forces a database rollback
582 * @return bool|string
584 public function lastError() {
585 $connerr = db2_conn_errormsg();
587 //$this->rollback( __METHOD__ );
590 $stmterr = db2_stmt_errormsg();
592 //$this->rollback( __METHOD__ );
600 * Get the last error number
601 * Return 0 if no error
604 public function lastErrno() {
605 $connerr = db2_conn_error();
609 $stmterr = db2_stmt_error();
617 * Is a database connection open?
620 public function isOpen() { return $this->mOpened
; }
623 * The DBMS-dependent part of query()
624 * @param $sql String: SQL query.
625 * @throws DBUnexpectedError
626 * @return object Result object for fetch functions or false on failure
628 protected function doQuery( $sql ) {
629 $this->applySchema();
631 // Needed to handle any UTF-8 encoding issues in the raw sql
632 // Note that we fully support prepared statements for DB2
633 // prepare() and execute() should be used instead of doQuery() whenever possible
634 $sql = utf8_decode( $sql );
636 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
637 if( $ret == false ) {
638 $error = db2_stmt_errormsg();
640 $this->installPrint( "<pre>$sql</pre>" );
641 $this->installPrint( $error );
642 throw new DBUnexpectedError( $this, 'SQL error: '
643 . htmlspecialchars( $error ) );
645 $this->mLastResult
= $ret;
646 $this->mAffectedRows
= null; // Not calculated until asked for
651 * @return string Version information from the database
653 public function getServerVersion() {
654 $info = db2_server_info( $this->mConn
);
655 return $info->DBMS_VER
;
659 * Queries whether a given table exists
662 public function tableExists( $table, $fname = __METHOD__
) {
663 $schema = $this->mSchema
;
665 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
666 strtoupper( $table ) .
667 "' AND ST.CREATOR = '" .
668 strtoupper( $schema ) . "'";
669 $res = $this->query( $sql );
674 // If the table exists, there should be one of it
675 $row = $this->fetchRow( $res );
677 if ( $count == '1' ||
$count == 1 ) {
685 * Fetch the next row from the given result object, in object form.
686 * Fields can be retrieved with $row->fieldname, with fields acting like
689 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
690 * @return DB2 row object
691 * @throws DBUnexpectedError Thrown if the database returns an error
693 public function fetchObject( $res ) {
694 if ( $res instanceof ResultWrapper
) {
697 wfSuppressWarnings();
698 $row = db2_fetch_object( $res );
700 if( $this->lastErrno() ) {
701 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
702 . htmlspecialchars( $this->lastError() ) );
708 * Fetch the next row from the given result object, in associative array
709 * form. Fields are retrieved with $row['fieldname'].
711 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
712 * @return ResultWrapper row object
713 * @throws DBUnexpectedError Thrown if the database returns an error
715 public function fetchRow( $res ) {
716 if ( $res instanceof ResultWrapper
) {
719 if ( db2_num_rows( $res ) > 0) {
720 wfSuppressWarnings();
721 $row = db2_fetch_array( $res );
723 if ( $this->lastErrno() ) {
724 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
725 . htmlspecialchars( $this->lastError() ) );
734 * Doesn't escape numbers
736 * @param $s String: string to escape
737 * @return string escaped string
739 public function addQuotes( $s ) {
740 //$this->installPrint( "DB2::addQuotes( $s )\n" );
741 if ( is_null( $s ) ) {
743 } elseif ( $s instanceof Blob
) {
744 return "'" . $s->fetch( $s ) . "'";
745 } elseif ( $s instanceof IBM_DB2Blob
) {
746 return "'" . $this->decodeBlob( $s ) . "'";
748 $s = $this->strencode( $s );
749 if ( is_numeric( $s ) ) {
757 * Verifies that a DB2 column/field type is numeric
759 * @param $type String: DB2 column type
760 * @return Boolean: true if numeric
762 public function is_numeric_type( $type ) {
763 switch ( strtoupper( $type ) ) {
778 * Alias for addQuotes()
779 * @param $s String: string to escape
780 * @return string escaped string
782 public function strencode( $s ) {
783 // Bloody useless function
784 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
785 // But also necessary
786 $s = db2_escape_string( $s );
787 // Wide characters are evil -- some of them look like '
788 $s = utf8_encode( $s );
790 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
791 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
792 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
797 * Switch into the database schema
799 protected function applySchema() {
800 if ( !( $this->mSchemaSet
) ) {
801 $this->mSchemaSet
= true;
802 $this->begin( __METHOD__
);
803 $this->doQuery( "SET SCHEMA = $this->mSchema" );
804 $this->commit( __METHOD__
);
809 * Start a transaction (mandatory)
811 protected function doBegin( $fname = 'DatabaseIbm_db2::begin' ) {
812 // BEGIN is implicit for DB2
813 // However, it requires that AutoCommit be off.
815 // Some MediaWiki code is still transaction-less (?).
816 // The strategy is to keep AutoCommit on for that code
817 // but switch it off whenever a transaction is begun.
818 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
820 $this->mTrxLevel
= 1;
825 * Must have a preceding begin()
827 protected function doCommit( $fname = 'DatabaseIbm_db2::commit' ) {
828 db2_commit( $this->mConn
);
830 // Some MediaWiki code is still transaction-less (?).
831 // The strategy is to keep AutoCommit on for that code
832 // but switch it off whenever a transaction is begun.
833 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
835 $this->mTrxLevel
= 0;
839 * Cancel a transaction
841 protected function doRollback( $fname = 'DatabaseIbm_db2::rollback' ) {
842 db2_rollback( $this->mConn
);
843 // turn auto-commit back on
844 // not sure if this is appropriate
845 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
846 $this->mTrxLevel
= 0;
850 * Makes an encoded list of strings from an array
852 * LIST_COMMA - comma separated, no field names
853 * LIST_AND - ANDed WHERE clause (without the WHERE)
854 * LIST_OR - ORed WHERE clause (without the WHERE)
855 * LIST_SET - comma separated with field names, like a SET clause
856 * LIST_NAMES - comma separated field names
857 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
860 * @throws DBUnexpectedError
863 function makeList( $a, $mode = LIST_COMMA
) {
864 if ( !is_array( $a ) ) {
865 throw new DBUnexpectedError( $this,
866 'DatabaseIbm_db2::makeList called with incorrect parameters' );
869 // if this is for a prepared UPDATE statement
870 // (this should be promoted to the parent class
871 // once other databases use prepared statements)
872 if ( $mode == LIST_SET_PREPARED
) {
875 foreach ( $a as $field => $value ) {
877 $list .= ", $field = ?";
879 $list .= "$field = ?";
888 // otherwise, call the usual function
889 return parent
::makeList( $a, $mode );
893 * Construct a LIMIT query with optional offset
894 * This is used for query pages
896 * @param $sql string SQL query we will append the limit too
897 * @param $limit integer the SQL limit
898 * @param bool|int $offset SQL offset (default false)
899 * @throws DBUnexpectedError
902 public function limitResult( $sql, $limit, $offset=false ) {
903 if( !is_numeric( $limit ) ) {
904 throw new DBUnexpectedError( $this,
905 "Invalid non-numeric limit passed to limitResult()\n" );
908 if ( stripos( $sql, 'where' ) === false ) {
909 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
911 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
914 return "$sql FETCH FIRST $limit ROWS ONLY ";
918 * Handle reserved keyword replacement in table names
920 * @param $name Object
921 * @param $format String Ignored parameter Default 'quoted'Boolean
924 public function tableName( $name, $format = 'quoted' ) {
925 // we want maximum compatibility with MySQL schema
930 * Generates a timestamp in an insertable format
932 * @param $ts string timestamp
933 * @return String: timestamp value
935 public function timestamp( $ts = 0 ) {
936 // TS_MW cannot be easily distinguished from an integer
937 return wfTimestamp( TS_DB2
, $ts );
941 * Return the next in a sequence, save the value for retrieval via insertId()
942 * @param $seqName String: name of a defined sequence in the database
943 * @return int next value in that sequence
945 public function nextSequenceValue( $seqName ) {
946 // Not using sequences in the primary schema to allow for easier migration
948 // Emulating MySQL behaviour of using NULL to signal that sequences
951 $safeseq = preg_replace( "/'/", "''", $seqName );
952 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
953 $row = $this->fetchRow( $res );
954 $this->mInsertId = $row[0];
955 return $this->mInsertId;
961 * This must be called after nextSequenceVal
962 * @return int Last sequence value used as a primary key
964 public function insertId() {
965 return $this->mInsertId
;
969 * Updates the mInsertId property with the value of the last insert
970 * into a generated column
972 * @param $table String: sanitized table name
973 * @param $primaryKey Mixed: string name of the primary key
974 * @param $stmt Resource: prepared statement resource
975 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
977 private function calcInsertId( $table, $primaryKey, $stmt ) {
979 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
984 * INSERT wrapper, inserts an array into a table
986 * $args may be a single associative array, or an array of arrays
987 * with numeric keys, for multi-row insert
989 * @param $table String: Name of the table to insert to.
990 * @param $args Array: Items to insert into the table.
991 * @param $fname String: Name of the function, for profiling
992 * @param $options String or Array. Valid options: IGNORE
994 * @return bool Success of insert operation. IGNORE always returns true.
996 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
999 if ( !count( $args ) ) {
1002 // get database-specific table name (not used)
1003 $table = $this->tableName( $table );
1004 // format options as an array
1005 $options = IBM_DB2Helper
::makeArray( $options );
1006 // format args as an array of arrays
1007 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1008 $args = array( $args );
1011 // prevent insertion of NULL into primary key columns
1012 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
1013 // if there's only one primary key
1014 // we'll be able to read its value after insertion
1015 $primaryKey = false;
1016 if ( count( $primaryKeys ) == 1 ) {
1017 $primaryKey = $primaryKeys[0];
1021 $keys = array_keys( $args[0] );
1022 $key_count = count( $keys );
1024 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1025 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1029 // If we are not in a transaction, we need to be for savepoint trickery
1030 if ( !$this->mTrxLevel
) {
1031 $this->begin( __METHOD__
);
1034 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
1035 if ( $key_count == 1 ) {
1038 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1040 $this->installPrint( "Preparing the following SQL:" );
1041 $this->installPrint( "$sql" );
1042 $this->installPrint( print_r( $args, true ));
1043 $stmt = $this->prepare( $sql );
1045 // start a transaction/enter transaction mode
1046 $this->begin( __METHOD__
);
1050 foreach ( $args as $row ) {
1051 //$this->installPrint( "Inserting " . print_r( $row, true ));
1052 // insert each row into the database
1053 $res = $res & $this->execute( $stmt, $row );
1055 $this->installPrint( 'Last error:' );
1056 $this->installPrint( $this->lastError() );
1058 // get the last inserted value into a generated column
1059 $this->calcInsertId( $table, $primaryKey, $stmt );
1062 $olde = error_reporting( 0 );
1063 // For future use, we may want to track the number of actual inserts
1064 // Right now, insert (all writes) simply return true/false
1065 $numrowsinserted = 0;
1067 // always return true
1070 foreach ( $args as $row ) {
1071 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1072 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
1074 $res2 = $this->execute( $stmt, $row );
1077 $this->installPrint( 'Last error:' );
1078 $this->installPrint( $this->lastError() );
1080 // get the last inserted value into a generated column
1081 $this->calcInsertId( $table, $primaryKey, $stmt );
1083 $errNum = $this->lastErrno();
1085 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
1086 $this->mStmtOptions
);
1088 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
1089 $this->mStmtOptions
);
1094 $olde = error_reporting( $olde );
1095 // Set the affected row count for the whole operation
1096 $this->mAffectedRows
= $numrowsinserted;
1098 // commit either way
1099 $this->commit( __METHOD__
);
1100 $this->freePrepared( $stmt );
1106 * Given a table name and a hash of columns with values
1107 * Removes primary key columns from the hash where the value is NULL
1109 * @param $table String: name of the table
1110 * @param $args Array of hashes of column names with values
1111 * @return Array: tuple( filtered array of columns, array of primary keys )
1113 private function removeNullPrimaryKeys( $table, $args ) {
1114 $schema = $this->mSchema
;
1116 // find out the primary keys
1117 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
1118 . strtoupper( $table )
1119 . "' AND TBCREATOR = '"
1120 . strtoupper( $schema )
1121 . "' AND KEYSEQ > 0" );
1125 $row = $this->fetchRow( $keyres );
1127 $row = $this->fetchRow( $keyres )
1130 $keys[] = strtolower( $row[0] );
1132 // remove primary keys
1133 foreach ( $args as $ai => $row ) {
1134 foreach ( $keys as $key ) {
1135 if ( $row[$key] == null ) {
1136 unset( $row[$key] );
1141 // return modified hash
1142 return array( $args, $keys );
1146 * UPDATE wrapper, takes a condition array and a SET array
1148 * @param $table String: The table to UPDATE
1149 * @param $values array An array of values to SET
1150 * @param $conds array An array of conditions ( WHERE ). Use '*' to update all rows.
1151 * @param $fname String: The Class::Function calling this function
1153 * @param $options array An array of UPDATE options, can be one or
1154 * more of IGNORE, LOW_PRIORITY
1157 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1158 $options = array() )
1160 $table = $this->tableName( $table );
1161 $opts = $this->makeUpdateOptions( $options );
1162 $sql = "UPDATE $opts $table SET "
1163 . $this->makeList( $values, LIST_SET_PREPARED
);
1164 if ( $conds != '*' ) {
1165 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1167 $stmt = $this->prepare( $sql );
1168 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1169 // assuming for now that an array with string keys will work
1170 // if not, convert to simple array first
1171 $result = $this->execute( $stmt, $values );
1172 $this->freePrepared( $stmt );
1178 * DELETE query wrapper
1180 * Use $conds == "*" to delete all rows
1181 * @param array $table
1182 * @param array|string $conds
1183 * @param string $fname
1184 * @throws DBUnexpectedError
1185 * @return bool|ResultWrapper
1187 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1189 throw new DBUnexpectedError( $this,
1190 'DatabaseIbm_db2::delete() called with no conditions' );
1192 $table = $this->tableName( $table );
1193 $sql = "DELETE FROM $table";
1194 if ( $conds != '*' ) {
1195 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1197 $result = $this->query( $sql, $fname );
1203 * Returns the number of rows affected by the last query or 0
1204 * @return Integer: the number of rows affected by the last query
1206 public function affectedRows() {
1207 if ( !is_null( $this->mAffectedRows
) ) {
1208 // Forced result for simulated queries
1209 return $this->mAffectedRows
;
1211 if( empty( $this->mLastResult
) ) {
1214 return db2_num_rows( $this->mLastResult
);
1218 * Returns the number of rows in the result set
1219 * Has to be called right after the corresponding select query
1220 * @param $res Object result set
1221 * @return Integer: number of rows
1223 public function numRows( $res ) {
1224 if ( $res instanceof ResultWrapper
) {
1225 $res = $res->result
;
1228 if ( $this->mNumRows
) {
1229 return $this->mNumRows
;
1236 * Moves the row pointer of the result set
1237 * @param $res Object: result set
1238 * @param $row Integer: row number
1239 * @return bool success or failure
1241 public function dataSeek( $res, $row ) {
1242 if ( $res instanceof ResultWrapper
) {
1243 return $res = $res->result
;
1245 if ( $res instanceof IBM_DB2Result
) {
1246 return $res->dataSeek( $row );
1248 wfDebug( "dataSeek operation in DB2 database\n" );
1253 # Fix notices in Block.php
1257 * Frees memory associated with a statement resource
1258 * @param $res Object: statement resource to free
1259 * @throws DBUnexpectedError
1260 * @return Boolean success or failure
1262 public function freeResult( $res ) {
1263 if ( $res instanceof ResultWrapper
) {
1264 $res = $res->result
;
1266 wfSuppressWarnings();
1267 $ok = db2_free_result( $res );
1268 wfRestoreWarnings();
1270 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1275 * Returns the number of columns in a resource
1276 * @param $res Object: statement resource
1277 * @return Number of fields/columns in resource
1279 public function numFields( $res ) {
1280 if ( $res instanceof ResultWrapper
) {
1281 $res = $res->result
;
1283 if ( $res instanceof IBM_DB2Result
) {
1284 $res = $res->getResult();
1286 return db2_num_fields( $res );
1290 * Returns the nth column name
1291 * @param $res Object: statement resource
1292 * @param $n Integer: Index of field or column
1293 * @return String name of nth column
1295 public function fieldName( $res, $n ) {
1296 if ( $res instanceof ResultWrapper
) {
1297 $res = $res->result
;
1299 if ( $res instanceof IBM_DB2Result
) {
1300 $res = $res->getResult();
1302 return db2_field_name( $res, $n );
1308 * @param $table Array or string, table name(s) (prefix auto-added)
1309 * @param $vars Array or string, field name(s) to be retrieved
1310 * @param $conds Array or string, condition(s) for WHERE
1311 * @param $fname String: calling function name (use __METHOD__)
1312 * for logs/profiling
1313 * @param $options array Associative array of options
1314 * (e.g. array( 'GROUP BY' => 'page_title' )),
1315 * see Database::makeSelectOptions code for list of
1317 * @param $join_conds array Associative array of table join conditions (optional)
1318 * (e.g. array( 'page' => array('LEFT JOIN',
1319 * 'page_latest=rev_id') )
1320 * @return Mixed: database result resource for fetch functions or false
1323 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1325 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1327 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1329 // We must adjust for offset
1330 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1331 $limit = $options['LIMIT'];
1332 $offset = $options['OFFSET'];
1335 // DB2 does not have a proper num_rows() function yet, so we must emulate
1336 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1340 // we want the count
1341 $vars2 = array( 'count( * ) as num_rows' );
1342 // respecting just the limit option
1343 $options2 = array();
1344 if ( isset( $options['LIMIT'] ) ) {
1345 $options2['LIMIT'] = $options['LIMIT'];
1347 // but don't try to emulate for GROUP BY
1348 if ( isset( $options['GROUP BY'] ) ) {
1352 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1355 $obj = $this->fetchObject( $res2 );
1356 $this->mNumRows
= $obj->num_rows
;
1358 return new ResultWrapper( $this, new IBM_DB2Result( $this, $res, $obj->num_rows
, $vars, $sql ) );
1362 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1363 * Has limited support for per-column options (colnum => 'DISTINCT')
1367 * @param $options array Associative array of options to be turned into
1368 * an SQL query, valid keys are listed in the function.
1371 function makeSelectOptions( $options ) {
1372 $preLimitTail = $postLimitTail = '';
1375 $noKeyOptions = array();
1376 foreach ( $options as $key => $option ) {
1377 if ( is_numeric( $key ) ) {
1378 $noKeyOptions[$option] = true;
1382 if ( isset( $options['GROUP BY'] ) ) {
1383 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1385 if ( isset( $options['HAVING'] ) ) {
1386 $preLimitTail .= " HAVING {$options['HAVING']}";
1388 if ( isset( $options['ORDER BY'] ) ) {
1389 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1392 if ( isset( $noKeyOptions['DISTINCT'] )
1393 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1395 $startOpts .= 'DISTINCT';
1398 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1402 * Returns link to IBM DB2 free download
1403 * @return String: wikitext of a link to the server software's web site
1405 public static function getSoftwareLink() {
1406 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1410 * Get search engine class. All subclasses of this
1411 * need to implement this if they wish to use searching.
1415 public function getSearchEngine() {
1416 return 'SearchIBM_DB2';
1420 * Did the last database access fail because of deadlock?
1423 public function wasDeadlock() {
1425 $err = $this->lastErrno();
1427 // This is literal port of the MySQL logic and may be wrong for DB2
1428 case '40001': // sql0911n, Deadlock or timeout, rollback
1429 case '57011': // sql0904n, Resource unavailable, no rollback
1430 case '57033': // sql0913n, Deadlock or timeout, no rollback
1431 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1438 * Ping the server and try to reconnect if it there is no connection
1439 * The connection may be closed and reopened while this happens
1440 * @return Boolean: whether the connection exists
1442 public function ping() {
1443 // db2_ping() doesn't exist
1446 $this->openUncataloged( $this->mDBName
, $this->mUser
,
1447 $this->mPassword
, $this->mServer
, $this->mPort
);
1451 ######################################
1452 # Unimplemented and not applicable
1453 ######################################
1456 * Only useful with fake prepare like in base Database class
1459 public function fillPreparedArg( $matches ) {
1460 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1464 ######################################
1466 ######################################
1469 * Returns information about an index
1470 * If errors are explicitly ignored, returns NULL on failure
1471 * @param $table String: table name
1472 * @param $index String: index name
1473 * @param $fname String: function name for logging and profiling
1474 * @return Object query row in object form
1476 public function indexInfo( $table, $index,
1477 $fname = 'DatabaseIbm_db2::indexExists' )
1479 $table = $this->tableName( $table );
1481 SELECT name as indexname
1482 FROM sysibm.sysindexes si
1483 WHERE si.name='$index' AND si.tbname='$table'
1484 AND sc.tbcreator='$this->mSchema'
1486 $res = $this->query( $sql, $fname );
1490 $row = $this->fetchObject( $res );
1491 if ( $row != null ) {
1499 * Returns an information object on a table column
1500 * @param $table String: table name
1501 * @param $field String: column name
1502 * @return IBM_DB2Field
1504 public function fieldInfo( $table, $field ) {
1505 return IBM_DB2Field
::fromText( $this, $table, $field );
1509 * db2_field_type() wrapper
1510 * @param $res Object: result of executed statement
1511 * @param $index Mixed: number or name of the column
1512 * @return String column type
1514 public function fieldType( $res, $index ) {
1515 if ( $res instanceof ResultWrapper
) {
1516 $res = $res->result
;
1518 if ( $res instanceof IBM_DB2Result
) {
1519 $res = $res->getResult();
1521 return db2_field_type( $res, $index );
1525 * Verifies that an index was created as unique
1526 * @param $table String: table name
1527 * @param $index String: index name
1528 * @param $fname string function name for profiling
1531 public function indexUnique ( $table, $index,
1532 $fname = 'DatabaseIbm_db2::indexUnique' )
1534 $table = $this->tableName( $table );
1536 SELECT si.name as indexname
1537 FROM sysibm.sysindexes si
1538 WHERE si.name='$index' AND si.tbname='$table'
1539 AND sc.tbcreator='$this->mSchema'
1540 AND si.uniquerule IN ( 'U', 'P' )
1542 $res = $this->query( $sql, $fname );
1546 if ( $this->fetchObject( $res ) ) {
1554 * Returns the size of a text field, or -1 for "unlimited"
1555 * @param $table String: table name
1556 * @param $field String: column name
1557 * @return Integer: length or -1 for unlimited
1559 public function textFieldSize( $table, $field ) {
1560 $table = $this->tableName( $table );
1562 SELECT length as size
1563 FROM sysibm.syscolumns sc
1564 WHERE sc.name='$field' AND sc.tbname='$table'
1565 AND sc.tbcreator='$this->mSchema'
1567 $res = $this->query( $sql );
1568 $row = $this->fetchObject( $res );
1574 * Description is left as an exercise for the reader
1575 * @param $b Mixed: data to be encoded
1576 * @return IBM_DB2Blob
1578 public function encodeBlob( $b ) {
1579 return new IBM_DB2Blob( $b );
1583 * Description is left as an exercise for the reader
1584 * @param $b IBM_DB2Blob: data to be decoded
1587 public function decodeBlob( $b ) {
1592 * Convert into a list of string being concatenated
1593 * @param $stringList Array: strings that need to be joined together
1595 * @return String: joined by the concatenation operator
1597 public function buildConcat( $stringList ) {
1598 // || is equivalent to CONCAT
1599 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1600 return implode( ' || ', $stringList );
1604 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1605 * @param $column String: name of timestamp column
1606 * @return String: SQL code
1608 public function extractUnixEpoch( $column ) {
1610 // see SpecialAncientpages
1613 ######################################
1614 # Prepared statements
1615 ######################################
1618 * Intended to be compatible with the PEAR::DB wrapper functions.
1619 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1621 * ? = scalar value, quoted as necessary
1622 * ! = raw SQL bit (a function for instance)
1623 * & = filename; reads the file and inserts as a blob
1624 * (we don't use this though...)
1625 * @param $sql String: SQL statement with appropriate markers
1626 * @param $func String: Name of the function, for profiling
1627 * @return resource a prepared DB2 SQL statement
1629 public function prepare( $sql, $func = 'DB2::prepare' ) {
1630 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1635 * Frees resources associated with a prepared statement
1636 * @return Boolean success or failure
1638 public function freePrepared( $prepared ) {
1639 return db2_free_stmt( $prepared );
1643 * Execute a prepared query with the various arguments
1644 * @param $prepared String: the prepared sql
1645 * @param $args Mixed: either an array here, or put scalars as varargs
1646 * @return Resource: results object
1648 public function execute( $prepared, $args = null ) {
1649 if( !is_array( $args ) ) {
1651 $args = func_get_args();
1652 array_shift( $args );
1654 $res = db2_execute( $prepared, $args );
1656 $this->installPrint( db2_stmt_errormsg() );
1662 * For faking prepared SQL statements on DBs that don't support
1664 * @param $preparedQuery String: a 'preparable' SQL statement
1665 * @param $args Array of arguments to fill it with
1666 * @return String: executable statement
1668 public function fillPrepared( $preparedQuery, $args ) {
1670 $this->preparedArgs
=& $args;
1672 foreach ( $args as $i => $arg ) {
1673 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1676 return $preparedQuery;
1680 * Switches module between regular and install modes
1683 public function setMode( $mode ) {
1684 $old = $this->mMode
;
1685 $this->mMode
= $mode;
1690 * Bitwise negation of a column or value in SQL
1691 * Same as (~field) in C
1692 * @param $field String
1695 function bitNot( $field ) {
1696 // expecting bit-fields smaller than 4bytes
1697 return "BITNOT( $field )";
1701 * Bitwise AND of two columns or values in SQL
1702 * Same as (fieldLeft & fieldRight) in C
1703 * @param $fieldLeft String
1704 * @param $fieldRight String
1707 function bitAnd( $fieldLeft, $fieldRight ) {
1708 return "BITAND( $fieldLeft, $fieldRight )";
1712 * Bitwise OR of two columns or values in SQL
1713 * Same as (fieldLeft | fieldRight) in C
1714 * @param $fieldLeft String
1715 * @param $fieldRight String
1718 function bitOr( $fieldLeft, $fieldRight ) {
1719 return "BITOR( $fieldLeft, $fieldRight )";
1723 class IBM_DB2Helper
{
1724 public static function makeArray( $maybeArray ) {
1725 if ( !is_array( $maybeArray ) ) {
1726 return array( $maybeArray );