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
;
153 $this->result
= $result;
156 $this->num_rows
= $num_rows;
157 $this->current_pos
= 0;
158 if ( $this->num_rows
> 0 ) {
159 // Make a lower-case list of the column names
160 // By default, DB2 column names are capitalized
161 // while MySQL column names are lowercase
163 // Is there a reasonable maximum value for $i?
164 // Setting to 2048 to prevent an infinite loop
165 for( $i = 0; $i < 2048; $i++
) {
166 $name = db2_field_name( $this->result
, $i );
167 if ( $name != false ) {
174 $this->columns
[$i] = strtolower( $name );
182 * Unwrap the DB2 query results
183 * @return mixed Object on success, false on failure
185 public function getResult() {
186 if ( $this->result
) {
187 return $this->result
;
193 * Get the number of rows in the result set
196 public function getNum_rows() {
197 return $this->num_rows
;
201 * Return a row from the result set in object format
202 * @return mixed Object on success, false on failure.
204 public function fetchObject() {
206 && $this->num_rows
> 0
207 && $this->current_pos
>= 0
208 && $this->current_pos
< $this->num_rows
)
210 $row = $this->fetchRow();
211 $ret = new stdClass();
213 foreach ( $row as $k => $v ) {
214 $lc = $this->columns
[$k];
223 * Return a row form the result set in array format
224 * @return mixed Array on success, false on failure
225 * @throws DBUnexpectedError
227 public function fetchRow(){
229 && $this->num_rows
> 0
230 && $this->current_pos
>= 0
231 && $this->current_pos
< $this->num_rows
)
233 if ( $this->loadedLines
<= $this->current_pos
) {
234 $row = db2_fetch_array( $this->result
);
235 $this->resultSet
[$this->loadedLines++
] = $row;
236 if ( $this->db
->lastErrno() ) {
237 throw new DBUnexpectedError( $this->db
, 'Error in fetchRow(): '
238 . htmlspecialchars( $this->db
->lastError() ) );
242 if ( $this->loadedLines
> $this->current_pos
){
243 return $this->resultSet
[$this->current_pos++
];
251 * Free a DB2 result object
252 * @throws DBUnexpectedError
254 public function freeResult(){
255 unset( $this->resultSet
);
256 if ( !@db2_free_result
( $this->result
) ) {
257 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
263 * Primary database interface
266 class DatabaseIbm_db2
extends DatabaseBase
{
269 protected $mLastQuery = '';
270 protected $mPHPError = false;
272 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
273 protected $mOpened = false;
275 protected $mTablePrefix;
277 protected $mTrxLevel = 0;
278 protected $mErrorCount = 0;
279 protected $mLBInfo = array();
280 protected $mFakeSlaveLag = null, $mFakeMaster = false;
284 /** Database server port */
285 protected $mPort = null;
286 /** Schema for tables, stored procedures, triggers */
287 protected $mSchema = null;
288 /** Whether the schema has been applied in this session */
289 protected $mSchemaSet = false;
290 /** Result of last query */
291 protected $mLastResult = null;
292 /** Number of rows affected by last INSERT/UPDATE/DELETE */
293 protected $mAffectedRows = null;
294 /** Number of rows returned by last SELECT */
295 protected $mNumRows = null;
296 /** Current row number on the cursor of the last SELECT */
297 protected $currentRow = 0;
299 /** Connection config options - see constructor */
300 public $mConnOptions = array();
301 /** Statement config options -- see constructor */
302 public $mStmtOptions = array();
304 /** Default schema */
305 const USE_GLOBAL
= 'get from global';
307 /** Option that applies to nothing */
308 const NONE_OPTION
= 0x00;
309 /** Option that applies to connection objects */
310 const CONN_OPTION
= 0x01;
311 /** Option that applies to statement objects */
312 const STMT_OPTION
= 0x02;
314 /** Regular operation mode -- minimal debug messages */
315 const REGULAR_MODE
= 'regular';
316 /** Installation mode -- lots of debug messages */
317 const INSTALL_MODE
= 'install';
319 /** Controls the level of debug message output */
320 protected $mMode = self
::REGULAR_MODE
;
322 /** Last sequence value used for a primary key */
323 protected $mInsertId = null;
325 ######################################
326 # Getters and Setters
327 ######################################
330 * Returns true if this database supports (and uses) cascading deletes
333 function cascadingDeletes() {
338 * Returns true if this database supports (and uses) triggers (e.g. on the
342 function cleanupTriggers() {
347 * Returns true if this database is strict about what can be put into an
349 * Specifically, it uses a NULL value instead of an empty string.
352 function strictIPs() {
357 * Returns true if this database uses timestamps rather than integers
360 function realTimestamps() {
365 * Returns true if this database does an implicit sort when doing GROUP BY
368 function implicitGroupby() {
373 * Returns true if this database does an implicit order by when the column
375 * For example: SELECT page_title FROM page LIMIT 1
378 function implicitOrderby() {
383 * Returns true if this database can do a native search on IP columns
384 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
387 function searchableIPs() {
392 * Returns true if this database can use functional indexes
395 function functionalIndexes() {
400 * Returns a unique string representing the wiki on the server
403 public function getWikiID() {
404 if( $this->mSchema
) {
405 return "{$this->mDBname}-{$this->mSchema}";
407 return $this->mDBname
;
412 * Returns the database software identifieir
415 public function getType() {
420 * Returns the database connection object
423 public function getDb(){
429 * @param $server String: hostname of database server
430 * @param $user String: username
431 * @param $password String: password
432 * @param $dbName String: database name on the server
433 * @param $flags Integer: database behaviour flags (optional, unused)
434 * @param $schema String
436 public function __construct( $server = false, $user = false,
438 $dbName = false, $flags = 0,
439 $schema = self
::USE_GLOBAL
)
441 global $wgDBmwschema;
443 if ( $schema == self
::USE_GLOBAL
) {
444 $this->mSchema
= $wgDBmwschema;
446 $this->mSchema
= $schema;
449 // configure the connection and statement objects
450 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
451 self
::CONN_OPTION | self
::STMT_OPTION
);
452 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
454 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
456 parent
::__construct( $server, $user, $password, $dbName, DBO_TRX |
$flags );
460 * Enables options only if the ibm_db2 extension version supports them
461 * @param $name String: name of the option in the options array
462 * @param $const String: name of the constant holding the right option value
463 * @param $type Integer: whether this is a Connection or Statement otion
465 private function setDB2Option( $name, $const, $type ) {
466 if ( defined( $const ) ) {
467 if ( $type & self
::CONN_OPTION
) {
468 $this->mConnOptions
[$name] = constant( $const );
470 if ( $type & self
::STMT_OPTION
) {
471 $this->mStmtOptions
[$name] = constant( $const );
475 "$const is not defined. ibm_db2 version is likely too low." );
480 * Outputs debug information in the appropriate place
481 * @param $string String: the relevant debug message
483 private function installPrint( $string ) {
484 wfDebug( "$string\n" );
485 if ( $this->mMode
== self
::INSTALL_MODE
) {
486 print "<li><pre>$string</pre></li>";
492 * Opens a database connection and returns it
493 * Closes any existing connection
495 * @param $server String: hostname
496 * @param $user String
497 * @param $password String
498 * @param $dbName String: database name
499 * @throws DBConnectionError
500 * @return DatabaseBase a fresh connection
502 public function open( $server, $user, $password, $dbName ) {
503 wfProfileIn( __METHOD__
);
505 # Load IBM DB2 driver if missing
508 # Test for IBM DB2 support, to avoid suppressed fatal error
509 if ( !function_exists( 'db2_connect' ) ) {
510 throw new DBConnectionError( $this, "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?" );
515 // Close existing connection
518 $this->mServer
= $server;
519 $this->mPort
= $port = $wgDBport;
520 $this->mUser
= $user;
521 $this->mPassword
= $password;
522 $this->mDBname
= $dbName;
524 $this->openUncataloged( $dbName, $user, $password, $server, $port );
526 if ( !$this->mConn
) {
527 $this->installPrint( "DB connection error\n" );
529 "Server: $server, Database: $dbName, User: $user, Password: "
530 . substr( $password, 0, 3 ) . "...\n" );
531 $this->installPrint( $this->lastError() . "\n" );
532 wfProfileOut( __METHOD__
);
533 wfDebug( "DB connection error\n" );
534 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
535 wfDebug( $this->lastError() . "\n" );
536 throw new DBConnectionError( $this, $this->lastError() );
539 // Some MediaWiki code is still transaction-less (?).
540 // The strategy is to keep AutoCommit on for that code
541 // but switch it off whenever a transaction is begun.
542 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
544 $this->mOpened
= true;
545 $this->applySchema();
547 wfProfileOut( __METHOD__
);
552 * Opens a cataloged database connection, sets mConn
554 protected function openCataloged( $dbName, $user, $password ) {
555 wfSuppressWarnings();
556 $this->mConn
= db2_pconnect( $dbName, $user, $password );
561 * Opens an uncataloged database connection, sets mConn
563 protected function openUncataloged( $dbName, $user, $password, $server, $port )
565 $dsn = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$dbName;CHARSET=UTF-8;HOSTNAME=$server;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
566 wfSuppressWarnings();
567 $this->mConn
= db2_pconnect( $dsn, "", "", array() );
572 * Closes a database connection, if it is open
573 * Returns success, true if already closed
576 protected function closeConnection() {
577 return db2_close( $this->mConn
);
581 * Retrieves the most current database error
582 * Forces a database rollback
583 * @return bool|string
585 public function lastError() {
586 $connerr = db2_conn_errormsg();
588 //$this->rollback( __METHOD__ );
591 $stmterr = db2_stmt_errormsg();
593 //$this->rollback( __METHOD__ );
601 * Get the last error number
602 * Return 0 if no error
605 public function lastErrno() {
606 $connerr = db2_conn_error();
610 $stmterr = db2_stmt_error();
618 * Is a database connection open?
621 public function isOpen() { return $this->mOpened
; }
624 * The DBMS-dependent part of query()
625 * @param $sql String: SQL query.
626 * @throws DBUnexpectedError
627 * @return object Result object for fetch functions or false on failure
629 protected function doQuery( $sql ) {
630 $this->applySchema();
632 // Needed to handle any UTF-8 encoding issues in the raw sql
633 // Note that we fully support prepared statements for DB2
634 // prepare() and execute() should be used instead of doQuery() whenever possible
635 $sql = utf8_decode( $sql );
637 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
638 if( $ret == false ) {
639 $error = db2_stmt_errormsg();
641 $this->installPrint( "<pre>$sql</pre>" );
642 $this->installPrint( $error );
643 throw new DBUnexpectedError( $this, 'SQL error: '
644 . htmlspecialchars( $error ) );
646 $this->mLastResult
= $ret;
647 $this->mAffectedRows
= null; // Not calculated until asked for
652 * @return string Version information from the database
654 public function getServerVersion() {
655 $info = db2_server_info( $this->mConn
);
656 return $info->DBMS_VER
;
660 * Queries whether a given table exists
663 public function tableExists( $table, $fname = __METHOD__
) {
664 $schema = $this->mSchema
;
666 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
667 strtoupper( $table ) .
668 "' AND ST.CREATOR = '" .
669 strtoupper( $schema ) . "'";
670 $res = $this->query( $sql );
675 // If the table exists, there should be one of it
676 $row = $this->fetchRow( $res );
678 if ( $count == '1' ||
$count == 1 ) {
686 * Fetch the next row from the given result object, in object form.
687 * Fields can be retrieved with $row->fieldname, with fields acting like
690 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
691 * @return DB2 row object
692 * @throws DBUnexpectedError Thrown if the database returns an error
694 public function fetchObject( $res ) {
695 if ( $res instanceof ResultWrapper
) {
698 wfSuppressWarnings();
699 $row = db2_fetch_object( $res );
701 if( $this->lastErrno() ) {
702 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
703 . htmlspecialchars( $this->lastError() ) );
709 * Fetch the next row from the given result object, in associative array
710 * form. Fields are retrieved with $row['fieldname'].
712 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
713 * @return ResultWrapper row object
714 * @throws DBUnexpectedError Thrown if the database returns an error
716 public function fetchRow( $res ) {
717 if ( $res instanceof ResultWrapper
) {
720 if ( db2_num_rows( $res ) > 0) {
721 wfSuppressWarnings();
722 $row = db2_fetch_array( $res );
724 if ( $this->lastErrno() ) {
725 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
726 . htmlspecialchars( $this->lastError() ) );
735 * Doesn't escape numbers
737 * @param $s String: string to escape
738 * @return string escaped string
740 public function addQuotes( $s ) {
741 //$this->installPrint( "DB2::addQuotes( $s )\n" );
742 if ( is_null( $s ) ) {
744 } elseif ( $s instanceof Blob
) {
745 return "'" . $s->fetch( $s ) . "'";
746 } elseif ( $s instanceof IBM_DB2Blob
) {
747 return "'" . $this->decodeBlob( $s ) . "'";
749 $s = $this->strencode( $s );
750 if ( is_numeric( $s ) ) {
758 * Verifies that a DB2 column/field type is numeric
760 * @param $type String: DB2 column type
761 * @return Boolean: true if numeric
763 public function is_numeric_type( $type ) {
764 switch ( strtoupper( $type ) ) {
779 * Alias for addQuotes()
780 * @param $s String: string to escape
781 * @return string escaped string
783 public function strencode( $s ) {
784 // Bloody useless function
785 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
786 // But also necessary
787 $s = db2_escape_string( $s );
788 // Wide characters are evil -- some of them look like '
789 $s = utf8_encode( $s );
791 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
792 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
793 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
798 * Switch into the database schema
800 protected function applySchema() {
801 if ( !( $this->mSchemaSet
) ) {
802 $this->mSchemaSet
= true;
803 $this->begin( __METHOD__
);
804 $this->doQuery( "SET SCHEMA = $this->mSchema" );
805 $this->commit( __METHOD__
);
810 * Start a transaction (mandatory)
812 protected function doBegin( $fname = 'DatabaseIbm_db2::begin' ) {
813 // BEGIN is implicit for DB2
814 // However, it requires that AutoCommit be off.
816 // Some MediaWiki code is still transaction-less (?).
817 // The strategy is to keep AutoCommit on for that code
818 // but switch it off whenever a transaction is begun.
819 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
821 $this->mTrxLevel
= 1;
826 * Must have a preceding begin()
828 protected function doCommit( $fname = 'DatabaseIbm_db2::commit' ) {
829 db2_commit( $this->mConn
);
831 // Some MediaWiki code is still transaction-less (?).
832 // The strategy is to keep AutoCommit on for that code
833 // but switch it off whenever a transaction is begun.
834 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
836 $this->mTrxLevel
= 0;
840 * Cancel a transaction
842 protected function doRollback( $fname = 'DatabaseIbm_db2::rollback' ) {
843 db2_rollback( $this->mConn
);
844 // turn auto-commit back on
845 // not sure if this is appropriate
846 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
847 $this->mTrxLevel
= 0;
851 * Makes an encoded list of strings from an array
853 * LIST_COMMA - comma separated, no field names
854 * LIST_AND - ANDed WHERE clause (without the WHERE)
855 * LIST_OR - ORed WHERE clause (without the WHERE)
856 * LIST_SET - comma separated with field names, like a SET clause
857 * LIST_NAMES - comma separated field names
858 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
861 * @throws DBUnexpectedError
864 function makeList( $a, $mode = LIST_COMMA
) {
865 if ( !is_array( $a ) ) {
866 throw new DBUnexpectedError( $this,
867 'DatabaseIbm_db2::makeList called with incorrect parameters' );
870 // if this is for a prepared UPDATE statement
871 // (this should be promoted to the parent class
872 // once other databases use prepared statements)
873 if ( $mode == LIST_SET_PREPARED
) {
876 foreach ( $a as $field => $value ) {
878 $list .= ", $field = ?";
880 $list .= "$field = ?";
889 // otherwise, call the usual function
890 return parent
::makeList( $a, $mode );
894 * Construct a LIMIT query with optional offset
895 * This is used for query pages
897 * @param $sql string SQL query we will append the limit too
898 * @param $limit integer the SQL limit
899 * @param bool|int $offset SQL offset (default false)
900 * @throws DBUnexpectedError
903 public function limitResult( $sql, $limit, $offset=false ) {
904 if( !is_numeric( $limit ) ) {
905 throw new DBUnexpectedError( $this,
906 "Invalid non-numeric limit passed to limitResult()\n" );
909 if ( stripos( $sql, 'where' ) === false ) {
910 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
912 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
915 return "$sql FETCH FIRST $limit ROWS ONLY ";
919 * Handle reserved keyword replacement in table names
921 * @param $name Object
922 * @param $format String Ignored parameter Default 'quoted'Boolean
925 public function tableName( $name, $format = 'quoted' ) {
926 // we want maximum compatibility with MySQL schema
931 * Generates a timestamp in an insertable format
933 * @param $ts string timestamp
934 * @return String: timestamp value
936 public function timestamp( $ts = 0 ) {
937 // TS_MW cannot be easily distinguished from an integer
938 return wfTimestamp( TS_DB2
, $ts );
942 * Return the next in a sequence, save the value for retrieval via insertId()
943 * @param $seqName String: name of a defined sequence in the database
944 * @return int next value in that sequence
946 public function nextSequenceValue( $seqName ) {
947 // Not using sequences in the primary schema to allow for easier migration
949 // Emulating MySQL behaviour of using NULL to signal that sequences
952 $safeseq = preg_replace( "/'/", "''", $seqName );
953 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
954 $row = $this->fetchRow( $res );
955 $this->mInsertId = $row[0];
956 return $this->mInsertId;
962 * This must be called after nextSequenceVal
963 * @return int Last sequence value used as a primary key
965 public function insertId() {
966 return $this->mInsertId
;
970 * Updates the mInsertId property with the value of the last insert
971 * into a generated column
973 * @param $table String: sanitized table name
974 * @param $primaryKey Mixed: string name of the primary key
975 * @param $stmt Resource: prepared statement resource
976 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
978 private function calcInsertId( $table, $primaryKey, $stmt ) {
980 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
985 * INSERT wrapper, inserts an array into a table
987 * $args may be a single associative array, or an array of arrays
988 * with numeric keys, for multi-row insert
990 * @param $table String: Name of the table to insert to.
991 * @param $args Array: Items to insert into the table.
992 * @param $fname String: Name of the function, for profiling
993 * @param $options String or Array. Valid options: IGNORE
995 * @return bool Success of insert operation. IGNORE always returns true.
997 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
1000 if ( !count( $args ) ) {
1003 // get database-specific table name (not used)
1004 $table = $this->tableName( $table );
1005 // format options as an array
1006 $options = IBM_DB2Helper
::makeArray( $options );
1007 // format args as an array of arrays
1008 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1009 $args = array( $args );
1012 // prevent insertion of NULL into primary key columns
1013 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
1014 // if there's only one primary key
1015 // we'll be able to read its value after insertion
1016 $primaryKey = false;
1017 if ( count( $primaryKeys ) == 1 ) {
1018 $primaryKey = $primaryKeys[0];
1022 $keys = array_keys( $args[0] );
1023 $key_count = count( $keys );
1025 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1026 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1030 // If we are not in a transaction, we need to be for savepoint trickery
1031 if ( !$this->mTrxLevel
) {
1032 $this->begin( __METHOD__
);
1035 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
1036 if ( $key_count == 1 ) {
1039 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1041 $this->installPrint( "Preparing the following SQL:" );
1042 $this->installPrint( "$sql" );
1043 $this->installPrint( print_r( $args, true ));
1044 $stmt = $this->prepare( $sql );
1046 // start a transaction/enter transaction mode
1047 $this->begin( __METHOD__
);
1051 foreach ( $args as $row ) {
1052 //$this->installPrint( "Inserting " . print_r( $row, true ));
1053 // insert each row into the database
1054 $res = $res & $this->execute( $stmt, $row );
1056 $this->installPrint( 'Last error:' );
1057 $this->installPrint( $this->lastError() );
1059 // get the last inserted value into a generated column
1060 $this->calcInsertId( $table, $primaryKey, $stmt );
1063 $olde = error_reporting( 0 );
1064 // For future use, we may want to track the number of actual inserts
1065 // Right now, insert (all writes) simply return true/false
1066 $numrowsinserted = 0;
1068 // always return true
1071 foreach ( $args as $row ) {
1072 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1073 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
1075 $res2 = $this->execute( $stmt, $row );
1078 $this->installPrint( 'Last error:' );
1079 $this->installPrint( $this->lastError() );
1081 // get the last inserted value into a generated column
1082 $this->calcInsertId( $table, $primaryKey, $stmt );
1084 $errNum = $this->lastErrno();
1086 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
1087 $this->mStmtOptions
);
1089 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
1090 $this->mStmtOptions
);
1095 $olde = error_reporting( $olde );
1096 // Set the affected row count for the whole operation
1097 $this->mAffectedRows
= $numrowsinserted;
1099 // commit either way
1100 $this->commit( __METHOD__
);
1101 $this->freePrepared( $stmt );
1107 * Given a table name and a hash of columns with values
1108 * Removes primary key columns from the hash where the value is NULL
1110 * @param $table String: name of the table
1111 * @param $args Array of hashes of column names with values
1112 * @return Array: tuple( filtered array of columns, array of primary keys )
1114 private function removeNullPrimaryKeys( $table, $args ) {
1115 $schema = $this->mSchema
;
1117 // find out the primary keys
1118 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
1119 . strtoupper( $table )
1120 . "' AND TBCREATOR = '"
1121 . strtoupper( $schema )
1122 . "' AND KEYSEQ > 0" );
1126 $row = $this->fetchRow( $keyres );
1128 $row = $this->fetchRow( $keyres )
1131 $keys[] = strtolower( $row[0] );
1133 // remove primary keys
1134 foreach ( $args as $ai => $row ) {
1135 foreach ( $keys as $key ) {
1136 if ( $row[$key] == null ) {
1137 unset( $row[$key] );
1142 // return modified hash
1143 return array( $args, $keys );
1147 * UPDATE wrapper, takes a condition array and a SET array
1149 * @param $table String: The table to UPDATE
1150 * @param $values array An array of values to SET
1151 * @param $conds array An array of conditions ( WHERE ). Use '*' to update all rows.
1152 * @param $fname String: The Class::Function calling this function
1154 * @param $options array An array of UPDATE options, can be one or
1155 * more of IGNORE, LOW_PRIORITY
1158 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1159 $options = array() )
1161 $table = $this->tableName( $table );
1162 $opts = $this->makeUpdateOptions( $options );
1163 $sql = "UPDATE $opts $table SET "
1164 . $this->makeList( $values, LIST_SET_PREPARED
);
1165 if ( $conds != '*' ) {
1166 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1168 $stmt = $this->prepare( $sql );
1169 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1170 // assuming for now that an array with string keys will work
1171 // if not, convert to simple array first
1172 $result = $this->execute( $stmt, $values );
1173 $this->freePrepared( $stmt );
1179 * DELETE query wrapper
1181 * Use $conds == "*" to delete all rows
1182 * @param array $table
1183 * @param array|string $conds
1184 * @param string $fname
1185 * @throws DBUnexpectedError
1186 * @return bool|ResultWrapper
1188 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1190 throw new DBUnexpectedError( $this,
1191 'DatabaseIbm_db2::delete() called with no conditions' );
1193 $table = $this->tableName( $table );
1194 $sql = "DELETE FROM $table";
1195 if ( $conds != '*' ) {
1196 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1198 $result = $this->query( $sql, $fname );
1204 * Returns the number of rows affected by the last query or 0
1205 * @return Integer: the number of rows affected by the last query
1207 public function affectedRows() {
1208 if ( !is_null( $this->mAffectedRows
) ) {
1209 // Forced result for simulated queries
1210 return $this->mAffectedRows
;
1212 if( empty( $this->mLastResult
) ) {
1215 return db2_num_rows( $this->mLastResult
);
1219 * Returns the number of rows in the result set
1220 * Has to be called right after the corresponding select query
1221 * @param $res Object result set
1222 * @return Integer: number of rows
1224 public function numRows( $res ) {
1225 if ( $res instanceof ResultWrapper
) {
1226 $res = $res->result
;
1229 if ( $this->mNumRows
) {
1230 return $this->mNumRows
;
1237 * Moves the row pointer of the result set
1238 * @param $res Object: result set
1239 * @param $row Integer: row number
1240 * @return bool success or failure
1242 public function dataSeek( $res, $row ) {
1243 if ( $res instanceof ResultWrapper
) {
1244 return $res = $res->result
;
1246 if ( $res instanceof IBM_DB2Result
) {
1247 return $res->dataSeek( $row );
1249 wfDebug( "dataSeek operation in DB2 database\n" );
1254 # Fix notices in Block.php
1258 * Frees memory associated with a statement resource
1259 * @param $res Object: statement resource to free
1260 * @throws DBUnexpectedError
1261 * @return Boolean success or failure
1263 public function freeResult( $res ) {
1264 if ( $res instanceof ResultWrapper
) {
1265 $res = $res->result
;
1267 wfSuppressWarnings();
1268 $ok = db2_free_result( $res );
1269 wfRestoreWarnings();
1271 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1276 * Returns the number of columns in a resource
1277 * @param $res Object: statement resource
1278 * @return Number of fields/columns in resource
1280 public function numFields( $res ) {
1281 if ( $res instanceof ResultWrapper
) {
1282 $res = $res->result
;
1284 if ( $res instanceof IBM_DB2Result
) {
1285 $res = $res->getResult();
1287 return db2_num_fields( $res );
1291 * Returns the nth column name
1292 * @param $res Object: statement resource
1293 * @param $n Integer: Index of field or column
1294 * @return String name of nth column
1296 public function fieldName( $res, $n ) {
1297 if ( $res instanceof ResultWrapper
) {
1298 $res = $res->result
;
1300 if ( $res instanceof IBM_DB2Result
) {
1301 $res = $res->getResult();
1303 return db2_field_name( $res, $n );
1309 * @param $table Array or string, table name(s) (prefix auto-added)
1310 * @param $vars Array or string, field name(s) to be retrieved
1311 * @param $conds Array or string, condition(s) for WHERE
1312 * @param $fname String: calling function name (use __METHOD__)
1313 * for logs/profiling
1314 * @param $options array Associative array of options
1315 * (e.g. array( 'GROUP BY' => 'page_title' )),
1316 * see Database::makeSelectOptions code for list of
1318 * @param $join_conds array Associative array of table join conditions (optional)
1319 * (e.g. array( 'page' => array('LEFT JOIN',
1320 * 'page_latest=rev_id') )
1321 * @return Mixed: database result resource for fetch functions or false
1324 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1326 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1328 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1330 // We must adjust for offset
1331 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1332 $limit = $options['LIMIT'];
1333 $offset = $options['OFFSET'];
1336 // DB2 does not have a proper num_rows() function yet, so we must emulate
1337 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1341 // we want the count
1342 $vars2 = array( 'count( * ) as num_rows' );
1343 // respecting just the limit option
1344 $options2 = array();
1345 if ( isset( $options['LIMIT'] ) ) {
1346 $options2['LIMIT'] = $options['LIMIT'];
1348 // but don't try to emulate for GROUP BY
1349 if ( isset( $options['GROUP BY'] ) ) {
1353 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1356 $obj = $this->fetchObject( $res2 );
1357 $this->mNumRows
= $obj->num_rows
;
1359 return new ResultWrapper( $this, new IBM_DB2Result( $this, $res, $obj->num_rows
, $vars, $sql ) );
1363 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1364 * Has limited support for per-column options (colnum => 'DISTINCT')
1368 * @param $options array Associative array of options to be turned into
1369 * an SQL query, valid keys are listed in the function.
1372 function makeSelectOptions( $options ) {
1373 $preLimitTail = $postLimitTail = '';
1376 $noKeyOptions = array();
1377 foreach ( $options as $key => $option ) {
1378 if ( is_numeric( $key ) ) {
1379 $noKeyOptions[$option] = true;
1383 if ( isset( $options['GROUP BY'] ) ) {
1384 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1386 if ( isset( $options['HAVING'] ) ) {
1387 $preLimitTail .= " HAVING {$options['HAVING']}";
1389 if ( isset( $options['ORDER BY'] ) ) {
1390 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1393 if ( isset( $noKeyOptions['DISTINCT'] )
1394 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1396 $startOpts .= 'DISTINCT';
1399 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1403 * Returns link to IBM DB2 free download
1404 * @return String: wikitext of a link to the server software's web site
1406 public static function getSoftwareLink() {
1407 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1411 * Get search engine class. All subclasses of this
1412 * need to implement this if they wish to use searching.
1416 public function getSearchEngine() {
1417 return 'SearchIBM_DB2';
1421 * Did the last database access fail because of deadlock?
1424 public function wasDeadlock() {
1426 $err = $this->lastErrno();
1428 // This is literal port of the MySQL logic and may be wrong for DB2
1429 case '40001': // sql0911n, Deadlock or timeout, rollback
1430 case '57011': // sql0904n, Resource unavailable, no rollback
1431 case '57033': // sql0913n, Deadlock or timeout, no rollback
1432 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1439 * Ping the server and try to reconnect if it there is no connection
1440 * The connection may be closed and reopened while this happens
1441 * @return Boolean: whether the connection exists
1443 public function ping() {
1444 // db2_ping() doesn't exist
1447 $this->openUncataloged( $this->mDBName
, $this->mUser
,
1448 $this->mPassword
, $this->mServer
, $this->mPort
);
1452 ######################################
1453 # Unimplemented and not applicable
1454 ######################################
1457 * Only useful with fake prepare like in base Database class
1460 public function fillPreparedArg( $matches ) {
1461 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1465 ######################################
1467 ######################################
1470 * Returns information about an index
1471 * If errors are explicitly ignored, returns NULL on failure
1472 * @param $table String: table name
1473 * @param $index String: index name
1474 * @param $fname String: function name for logging and profiling
1475 * @return Object query row in object form
1477 public function indexInfo( $table, $index,
1478 $fname = 'DatabaseIbm_db2::indexExists' )
1480 $table = $this->tableName( $table );
1482 SELECT name as indexname
1483 FROM sysibm.sysindexes si
1484 WHERE si.name='$index' AND si.tbname='$table'
1485 AND sc.tbcreator='$this->mSchema'
1487 $res = $this->query( $sql, $fname );
1491 $row = $this->fetchObject( $res );
1492 if ( $row != null ) {
1500 * Returns an information object on a table column
1501 * @param $table String: table name
1502 * @param $field String: column name
1503 * @return IBM_DB2Field
1505 public function fieldInfo( $table, $field ) {
1506 return IBM_DB2Field
::fromText( $this, $table, $field );
1510 * db2_field_type() wrapper
1511 * @param $res Object: result of executed statement
1512 * @param $index Mixed: number or name of the column
1513 * @return String column type
1515 public function fieldType( $res, $index ) {
1516 if ( $res instanceof ResultWrapper
) {
1517 $res = $res->result
;
1519 if ( $res instanceof IBM_DB2Result
) {
1520 $res = $res->getResult();
1522 return db2_field_type( $res, $index );
1526 * Verifies that an index was created as unique
1527 * @param $table String: table name
1528 * @param $index String: index name
1529 * @param $fname string function name for profiling
1532 public function indexUnique ( $table, $index,
1533 $fname = 'DatabaseIbm_db2::indexUnique' )
1535 $table = $this->tableName( $table );
1537 SELECT si.name as indexname
1538 FROM sysibm.sysindexes si
1539 WHERE si.name='$index' AND si.tbname='$table'
1540 AND sc.tbcreator='$this->mSchema'
1541 AND si.uniquerule IN ( 'U', 'P' )
1543 $res = $this->query( $sql, $fname );
1547 if ( $this->fetchObject( $res ) ) {
1555 * Returns the size of a text field, or -1 for "unlimited"
1556 * @param $table String: table name
1557 * @param $field String: column name
1558 * @return Integer: length or -1 for unlimited
1560 public function textFieldSize( $table, $field ) {
1561 $table = $this->tableName( $table );
1563 SELECT length as size
1564 FROM sysibm.syscolumns sc
1565 WHERE sc.name='$field' AND sc.tbname='$table'
1566 AND sc.tbcreator='$this->mSchema'
1568 $res = $this->query( $sql );
1569 $row = $this->fetchObject( $res );
1575 * Description is left as an exercise for the reader
1576 * @param $b Mixed: data to be encoded
1577 * @return IBM_DB2Blob
1579 public function encodeBlob( $b ) {
1580 return new IBM_DB2Blob( $b );
1584 * Description is left as an exercise for the reader
1585 * @param $b IBM_DB2Blob: data to be decoded
1588 public function decodeBlob( $b ) {
1593 * Convert into a list of string being concatenated
1594 * @param $stringList Array: strings that need to be joined together
1596 * @return String: joined by the concatenation operator
1598 public function buildConcat( $stringList ) {
1599 // || is equivalent to CONCAT
1600 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1601 return implode( ' || ', $stringList );
1605 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1606 * @param $column String: name of timestamp column
1607 * @return String: SQL code
1609 public function extractUnixEpoch( $column ) {
1611 // see SpecialAncientpages
1614 ######################################
1615 # Prepared statements
1616 ######################################
1619 * Intended to be compatible with the PEAR::DB wrapper functions.
1620 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1622 * ? = scalar value, quoted as necessary
1623 * ! = raw SQL bit (a function for instance)
1624 * & = filename; reads the file and inserts as a blob
1625 * (we don't use this though...)
1626 * @param $sql String: SQL statement with appropriate markers
1627 * @param $func String: Name of the function, for profiling
1628 * @return resource a prepared DB2 SQL statement
1630 public function prepare( $sql, $func = 'DB2::prepare' ) {
1631 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1636 * Frees resources associated with a prepared statement
1637 * @return Boolean success or failure
1639 public function freePrepared( $prepared ) {
1640 return db2_free_stmt( $prepared );
1644 * Execute a prepared query with the various arguments
1645 * @param $prepared String: the prepared sql
1646 * @param $args Mixed: either an array here, or put scalars as varargs
1647 * @return Resource: results object
1649 public function execute( $prepared, $args = null ) {
1650 if( !is_array( $args ) ) {
1652 $args = func_get_args();
1653 array_shift( $args );
1655 $res = db2_execute( $prepared, $args );
1657 $this->installPrint( db2_stmt_errormsg() );
1663 * For faking prepared SQL statements on DBs that don't support
1665 * @param $preparedQuery String: a 'preparable' SQL statement
1666 * @param $args Array of arguments to fill it with
1667 * @return String: executable statement
1669 public function fillPrepared( $preparedQuery, $args ) {
1671 $this->preparedArgs
=& $args;
1673 foreach ( $args as $i => $arg ) {
1674 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1677 return $preparedQuery;
1681 * Switches module between regular and install modes
1684 public function setMode( $mode ) {
1685 $old = $this->mMode
;
1686 $this->mMode
= $mode;
1691 * Bitwise negation of a column or value in SQL
1692 * Same as (~field) in C
1693 * @param $field String
1696 function bitNot( $field ) {
1697 // expecting bit-fields smaller than 4bytes
1698 return "BITNOT( $field )";
1702 * Bitwise AND of two columns or values in SQL
1703 * Same as (fieldLeft & fieldRight) in C
1704 * @param $fieldLeft String
1705 * @param $fieldRight String
1708 function bitAnd( $fieldLeft, $fieldRight ) {
1709 return "BITAND( $fieldLeft, $fieldRight )";
1713 * Bitwise OR of two columns or values in SQL
1714 * Same as (fieldLeft | fieldRight) in C
1715 * @param $fieldLeft String
1716 * @param $fieldRight String
1719 function bitOr( $fieldLeft, $fieldRight ) {
1720 return "BITOR( $fieldLeft, $fieldRight )";
1724 class IBM_DB2Helper
{
1725 public static function makeArray( $maybeArray ) {
1726 if ( !is_array( $maybeArray ) ) {
1727 return array( $maybeArray );