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 * @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 * @return object Result object for fetch functions or false on failure
627 protected function doQuery( $sql ) {
628 $this->applySchema();
630 // Needed to handle any UTF-8 encoding issues in the raw sql
631 // Note that we fully support prepared statements for DB2
632 // prepare() and execute() should be used instead of doQuery() whenever possible
633 $sql = utf8_decode( $sql );
635 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
636 if( $ret == false ) {
637 $error = db2_stmt_errormsg();
639 $this->installPrint( "<pre>$sql</pre>" );
640 $this->installPrint( $error );
641 throw new DBUnexpectedError( $this, 'SQL error: '
642 . htmlspecialchars( $error ) );
644 $this->mLastResult
= $ret;
645 $this->mAffectedRows
= null; // Not calculated until asked for
650 * @return string Version information from the database
652 public function getServerVersion() {
653 $info = db2_server_info( $this->mConn
);
654 return $info->DBMS_VER
;
658 * Queries whether a given table exists
661 public function tableExists( $table, $fname = __METHOD__
) {
662 $schema = $this->mSchema
;
664 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
665 strtoupper( $table ) .
666 "' AND ST.CREATOR = '" .
667 strtoupper( $schema ) . "'";
668 $res = $this->query( $sql );
673 // If the table exists, there should be one of it
674 $row = $this->fetchRow( $res );
676 if ( $count == '1' ||
$count == 1 ) {
684 * Fetch the next row from the given result object, in object form.
685 * Fields can be retrieved with $row->fieldname, with fields acting like
688 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
689 * @return DB2 row object
690 * @throws DBUnexpectedError Thrown if the database returns an error
692 public function fetchObject( $res ) {
693 if ( $res instanceof ResultWrapper
) {
696 wfSuppressWarnings();
697 $row = db2_fetch_object( $res );
699 if( $this->lastErrno() ) {
700 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
701 . htmlspecialchars( $this->lastError() ) );
707 * Fetch the next row from the given result object, in associative array
708 * form. Fields are retrieved with $row['fieldname'].
710 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
711 * @return ResultWrapper row object
712 * @throws DBUnexpectedError Thrown if the database returns an error
714 public function fetchRow( $res ) {
715 if ( $res instanceof ResultWrapper
) {
718 if ( db2_num_rows( $res ) > 0) {
719 wfSuppressWarnings();
720 $row = db2_fetch_array( $res );
722 if ( $this->lastErrno() ) {
723 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
724 . htmlspecialchars( $this->lastError() ) );
733 * Doesn't escape numbers
735 * @param $s String: string to escape
736 * @return string escaped string
738 public function addQuotes( $s ) {
739 //$this->installPrint( "DB2::addQuotes( $s )\n" );
740 if ( is_null( $s ) ) {
742 } elseif ( $s instanceof Blob
) {
743 return "'" . $s->fetch( $s ) . "'";
744 } elseif ( $s instanceof IBM_DB2Blob
) {
745 return "'" . $this->decodeBlob( $s ) . "'";
747 $s = $this->strencode( $s );
748 if ( is_numeric( $s ) ) {
756 * Verifies that a DB2 column/field type is numeric
758 * @param $type String: DB2 column type
759 * @return Boolean: true if numeric
761 public function is_numeric_type( $type ) {
762 switch ( strtoupper( $type ) ) {
777 * Alias for addQuotes()
778 * @param $s String: string to escape
779 * @return string escaped string
781 public function strencode( $s ) {
782 // Bloody useless function
783 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
784 // But also necessary
785 $s = db2_escape_string( $s );
786 // Wide characters are evil -- some of them look like '
787 $s = utf8_encode( $s );
789 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
790 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
791 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
796 * Switch into the database schema
798 protected function applySchema() {
799 if ( !( $this->mSchemaSet
) ) {
800 $this->mSchemaSet
= true;
801 $this->begin( __METHOD__
);
802 $this->doQuery( "SET SCHEMA = $this->mSchema" );
803 $this->commit( __METHOD__
);
808 * Start a transaction (mandatory)
810 protected function doBegin( $fname = 'DatabaseIbm_db2::begin' ) {
811 // BEGIN is implicit for DB2
812 // However, it requires that AutoCommit be off.
814 // Some MediaWiki code is still transaction-less (?).
815 // The strategy is to keep AutoCommit on for that code
816 // but switch it off whenever a transaction is begun.
817 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
819 $this->mTrxLevel
= 1;
824 * Must have a preceding begin()
826 protected function doCommit( $fname = 'DatabaseIbm_db2::commit' ) {
827 db2_commit( $this->mConn
);
829 // Some MediaWiki code is still transaction-less (?).
830 // The strategy is to keep AutoCommit on for that code
831 // but switch it off whenever a transaction is begun.
832 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
834 $this->mTrxLevel
= 0;
838 * Cancel a transaction
840 protected function doRollback( $fname = 'DatabaseIbm_db2::rollback' ) {
841 db2_rollback( $this->mConn
);
842 // turn auto-commit back on
843 // not sure if this is appropriate
844 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
845 $this->mTrxLevel
= 0;
849 * Makes an encoded list of strings from an array
851 * LIST_COMMA - comma separated, no field names
852 * LIST_AND - ANDed WHERE clause (without the WHERE)
853 * LIST_OR - ORed WHERE clause (without the WHERE)
854 * LIST_SET - comma separated with field names, like a SET clause
855 * LIST_NAMES - comma separated field names
856 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
859 function makeList( $a, $mode = LIST_COMMA
) {
860 if ( !is_array( $a ) ) {
861 throw new DBUnexpectedError( $this,
862 'DatabaseIbm_db2::makeList called with incorrect parameters' );
865 // if this is for a prepared UPDATE statement
866 // (this should be promoted to the parent class
867 // once other databases use prepared statements)
868 if ( $mode == LIST_SET_PREPARED
) {
871 foreach ( $a as $field => $value ) {
873 $list .= ", $field = ?";
875 $list .= "$field = ?";
884 // otherwise, call the usual function
885 return parent
::makeList( $a, $mode );
889 * Construct a LIMIT query with optional offset
890 * This is used for query pages
892 * @param $sql string SQL query we will append the limit too
893 * @param $limit integer the SQL limit
894 * @param $offset integer the SQL offset (default false)
897 public function limitResult( $sql, $limit, $offset=false ) {
898 if( !is_numeric( $limit ) ) {
899 throw new DBUnexpectedError( $this,
900 "Invalid non-numeric limit passed to limitResult()\n" );
903 if ( stripos( $sql, 'where' ) === false ) {
904 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
906 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
909 return "$sql FETCH FIRST $limit ROWS ONLY ";
913 * Handle reserved keyword replacement in table names
915 * @param $name Object
916 * @param $format String Ignored parameter Default 'quoted'Boolean
919 public function tableName( $name, $format = 'quoted' ) {
920 // we want maximum compatibility with MySQL schema
925 * Generates a timestamp in an insertable format
927 * @param $ts string timestamp
928 * @return String: timestamp value
930 public function timestamp( $ts = 0 ) {
931 // TS_MW cannot be easily distinguished from an integer
932 return wfTimestamp( TS_DB2
, $ts );
936 * Return the next in a sequence, save the value for retrieval via insertId()
937 * @param $seqName String: name of a defined sequence in the database
938 * @return int next value in that sequence
940 public function nextSequenceValue( $seqName ) {
941 // Not using sequences in the primary schema to allow for easier migration
943 // Emulating MySQL behaviour of using NULL to signal that sequences
946 $safeseq = preg_replace( "/'/", "''", $seqName );
947 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
948 $row = $this->fetchRow( $res );
949 $this->mInsertId = $row[0];
950 return $this->mInsertId;
956 * This must be called after nextSequenceVal
957 * @return int Last sequence value used as a primary key
959 public function insertId() {
960 return $this->mInsertId
;
964 * Updates the mInsertId property with the value of the last insert
965 * into a generated column
967 * @param $table String: sanitized table name
968 * @param $primaryKey Mixed: string name of the primary key
969 * @param $stmt Resource: prepared statement resource
970 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
972 private function calcInsertId( $table, $primaryKey, $stmt ) {
974 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
979 * INSERT wrapper, inserts an array into a table
981 * $args may be a single associative array, or an array of arrays
982 * with numeric keys, for multi-row insert
984 * @param $table String: Name of the table to insert to.
985 * @param $args Array: Items to insert into the table.
986 * @param $fname String: Name of the function, for profiling
987 * @param $options String or Array. Valid options: IGNORE
989 * @return bool Success of insert operation. IGNORE always returns true.
991 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
994 if ( !count( $args ) ) {
997 // get database-specific table name (not used)
998 $table = $this->tableName( $table );
999 // format options as an array
1000 $options = IBM_DB2Helper
::makeArray( $options );
1001 // format args as an array of arrays
1002 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1003 $args = array( $args );
1006 // prevent insertion of NULL into primary key columns
1007 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
1008 // if there's only one primary key
1009 // we'll be able to read its value after insertion
1010 $primaryKey = false;
1011 if ( count( $primaryKeys ) == 1 ) {
1012 $primaryKey = $primaryKeys[0];
1016 $keys = array_keys( $args[0] );
1017 $key_count = count( $keys );
1019 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1020 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1024 // If we are not in a transaction, we need to be for savepoint trickery
1025 if ( !$this->mTrxLevel
) {
1026 $this->begin( __METHOD__
);
1029 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
1030 if ( $key_count == 1 ) {
1033 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1035 $this->installPrint( "Preparing the following SQL:" );
1036 $this->installPrint( "$sql" );
1037 $this->installPrint( print_r( $args, true ));
1038 $stmt = $this->prepare( $sql );
1040 // start a transaction/enter transaction mode
1041 $this->begin( __METHOD__
);
1045 foreach ( $args as $row ) {
1046 //$this->installPrint( "Inserting " . print_r( $row, true ));
1047 // insert each row into the database
1048 $res = $res & $this->execute( $stmt, $row );
1050 $this->installPrint( 'Last error:' );
1051 $this->installPrint( $this->lastError() );
1053 // get the last inserted value into a generated column
1054 $this->calcInsertId( $table, $primaryKey, $stmt );
1057 $olde = error_reporting( 0 );
1058 // For future use, we may want to track the number of actual inserts
1059 // Right now, insert (all writes) simply return true/false
1060 $numrowsinserted = 0;
1062 // always return true
1065 foreach ( $args as $row ) {
1066 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1067 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
1069 $res2 = $this->execute( $stmt, $row );
1072 $this->installPrint( 'Last error:' );
1073 $this->installPrint( $this->lastError() );
1075 // get the last inserted value into a generated column
1076 $this->calcInsertId( $table, $primaryKey, $stmt );
1078 $errNum = $this->lastErrno();
1080 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
1081 $this->mStmtOptions
);
1083 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
1084 $this->mStmtOptions
);
1089 $olde = error_reporting( $olde );
1090 // Set the affected row count for the whole operation
1091 $this->mAffectedRows
= $numrowsinserted;
1093 // commit either way
1094 $this->commit( __METHOD__
);
1095 $this->freePrepared( $stmt );
1101 * Given a table name and a hash of columns with values
1102 * Removes primary key columns from the hash where the value is NULL
1104 * @param $table String: name of the table
1105 * @param $args Array of hashes of column names with values
1106 * @return Array: tuple( filtered array of columns, array of primary keys )
1108 private function removeNullPrimaryKeys( $table, $args ) {
1109 $schema = $this->mSchema
;
1111 // find out the primary keys
1112 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
1113 . strtoupper( $table )
1114 . "' AND TBCREATOR = '"
1115 . strtoupper( $schema )
1116 . "' AND KEYSEQ > 0" );
1120 $row = $this->fetchRow( $keyres );
1122 $row = $this->fetchRow( $keyres )
1125 $keys[] = strtolower( $row[0] );
1127 // remove primary keys
1128 foreach ( $args as $ai => $row ) {
1129 foreach ( $keys as $key ) {
1130 if ( $row[$key] == null ) {
1131 unset( $row[$key] );
1136 // return modified hash
1137 return array( $args, $keys );
1141 * UPDATE wrapper, takes a condition array and a SET array
1143 * @param $table String: The table to UPDATE
1144 * @param $values array An array of values to SET
1145 * @param $conds array An array of conditions ( WHERE ). Use '*' to update all rows.
1146 * @param $fname String: The Class::Function calling this function
1148 * @param $options array An array of UPDATE options, can be one or
1149 * more of IGNORE, LOW_PRIORITY
1152 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1153 $options = array() )
1155 $table = $this->tableName( $table );
1156 $opts = $this->makeUpdateOptions( $options );
1157 $sql = "UPDATE $opts $table SET "
1158 . $this->makeList( $values, LIST_SET_PREPARED
);
1159 if ( $conds != '*' ) {
1160 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1162 $stmt = $this->prepare( $sql );
1163 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1164 // assuming for now that an array with string keys will work
1165 // if not, convert to simple array first
1166 $result = $this->execute( $stmt, $values );
1167 $this->freePrepared( $stmt );
1173 * DELETE query wrapper
1175 * Use $conds == "*" to delete all rows
1176 * @return bool|\ResultWrapper
1178 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1180 throw new DBUnexpectedError( $this,
1181 'DatabaseIbm_db2::delete() called with no conditions' );
1183 $table = $this->tableName( $table );
1184 $sql = "DELETE FROM $table";
1185 if ( $conds != '*' ) {
1186 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1188 $result = $this->query( $sql, $fname );
1194 * Returns the number of rows affected by the last query or 0
1195 * @return Integer: the number of rows affected by the last query
1197 public function affectedRows() {
1198 if ( !is_null( $this->mAffectedRows
) ) {
1199 // Forced result for simulated queries
1200 return $this->mAffectedRows
;
1202 if( empty( $this->mLastResult
) ) {
1205 return db2_num_rows( $this->mLastResult
);
1209 * Returns the number of rows in the result set
1210 * Has to be called right after the corresponding select query
1211 * @param $res Object result set
1212 * @return Integer: number of rows
1214 public function numRows( $res ) {
1215 if ( $res instanceof ResultWrapper
) {
1216 $res = $res->result
;
1219 if ( $this->mNumRows
) {
1220 return $this->mNumRows
;
1227 * Moves the row pointer of the result set
1228 * @param $res Object: result set
1229 * @param $row Integer: row number
1230 * @return bool success or failure
1232 public function dataSeek( $res, $row ) {
1233 if ( $res instanceof ResultWrapper
) {
1234 return $res = $res->result
;
1236 if ( $res instanceof IBM_DB2Result
) {
1237 return $res->dataSeek( $row );
1239 wfDebug( "dataSeek operation in DB2 database\n" );
1244 # Fix notices in Block.php
1248 * Frees memory associated with a statement resource
1249 * @param $res Object: statement resource to free
1250 * @return Boolean success or failure
1252 public function freeResult( $res ) {
1253 if ( $res instanceof ResultWrapper
) {
1254 $res = $res->result
;
1256 wfSuppressWarnings();
1257 $ok = db2_free_result( $res );
1258 wfRestoreWarnings();
1260 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1265 * Returns the number of columns in a resource
1266 * @param $res Object: statement resource
1267 * @return Number of fields/columns in resource
1269 public function numFields( $res ) {
1270 if ( $res instanceof ResultWrapper
) {
1271 $res = $res->result
;
1273 if ( $res instanceof IBM_DB2Result
) {
1274 $res = $res->getResult();
1276 return db2_num_fields( $res );
1280 * Returns the nth column name
1281 * @param $res Object: statement resource
1282 * @param $n Integer: Index of field or column
1283 * @return String name of nth column
1285 public function fieldName( $res, $n ) {
1286 if ( $res instanceof ResultWrapper
) {
1287 $res = $res->result
;
1289 if ( $res instanceof IBM_DB2Result
) {
1290 $res = $res->getResult();
1292 return db2_field_name( $res, $n );
1298 * @param $table Array or string, table name(s) (prefix auto-added)
1299 * @param $vars Array or string, field name(s) to be retrieved
1300 * @param $conds Array or string, condition(s) for WHERE
1301 * @param $fname String: calling function name (use __METHOD__)
1302 * for logs/profiling
1303 * @param $options array Associative array of options
1304 * (e.g. array( 'GROUP BY' => 'page_title' )),
1305 * see Database::makeSelectOptions code for list of
1307 * @param $join_conds array Associative array of table join conditions (optional)
1308 * (e.g. array( 'page' => array('LEFT JOIN',
1309 * 'page_latest=rev_id') )
1310 * @return Mixed: database result resource for fetch functions or false
1313 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1315 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1317 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1319 // We must adjust for offset
1320 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1321 $limit = $options['LIMIT'];
1322 $offset = $options['OFFSET'];
1325 // DB2 does not have a proper num_rows() function yet, so we must emulate
1326 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1330 // we want the count
1331 $vars2 = array( 'count( * ) as num_rows' );
1332 // respecting just the limit option
1333 $options2 = array();
1334 if ( isset( $options['LIMIT'] ) ) {
1335 $options2['LIMIT'] = $options['LIMIT'];
1337 // but don't try to emulate for GROUP BY
1338 if ( isset( $options['GROUP BY'] ) ) {
1342 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1345 $obj = $this->fetchObject( $res2 );
1346 $this->mNumRows
= $obj->num_rows
;
1348 return new ResultWrapper( $this, new IBM_DB2Result( $this, $res, $obj->num_rows
, $vars, $sql ) );
1352 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1353 * Has limited support for per-column options (colnum => 'DISTINCT')
1357 * @param $options array Associative array of options to be turned into
1358 * an SQL query, valid keys are listed in the function.
1361 function makeSelectOptions( $options ) {
1362 $preLimitTail = $postLimitTail = '';
1365 $noKeyOptions = array();
1366 foreach ( $options as $key => $option ) {
1367 if ( is_numeric( $key ) ) {
1368 $noKeyOptions[$option] = true;
1372 if ( isset( $options['GROUP BY'] ) ) {
1373 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1375 if ( isset( $options['HAVING'] ) ) {
1376 $preLimitTail .= " HAVING {$options['HAVING']}";
1378 if ( isset( $options['ORDER BY'] ) ) {
1379 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1382 if ( isset( $noKeyOptions['DISTINCT'] )
1383 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1385 $startOpts .= 'DISTINCT';
1388 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1392 * Returns link to IBM DB2 free download
1393 * @return String: wikitext of a link to the server software's web site
1395 public static function getSoftwareLink() {
1396 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1400 * Get search engine class. All subclasses of this
1401 * need to implement this if they wish to use searching.
1405 public function getSearchEngine() {
1406 return 'SearchIBM_DB2';
1410 * Did the last database access fail because of deadlock?
1413 public function wasDeadlock() {
1415 $err = $this->lastErrno();
1417 // This is literal port of the MySQL logic and may be wrong for DB2
1418 case '40001': // sql0911n, Deadlock or timeout, rollback
1419 case '57011': // sql0904n, Resource unavailable, no rollback
1420 case '57033': // sql0913n, Deadlock or timeout, no rollback
1421 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1428 * Ping the server and try to reconnect if it there is no connection
1429 * The connection may be closed and reopened while this happens
1430 * @return Boolean: whether the connection exists
1432 public function ping() {
1433 // db2_ping() doesn't exist
1436 $this->openUncataloged( $this->mDBName
, $this->mUser
,
1437 $this->mPassword
, $this->mServer
, $this->mPort
);
1441 ######################################
1442 # Unimplemented and not applicable
1443 ######################################
1446 * Only useful with fake prepare like in base Database class
1449 public function fillPreparedArg( $matches ) {
1450 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1454 ######################################
1456 ######################################
1459 * Returns information about an index
1460 * If errors are explicitly ignored, returns NULL on failure
1461 * @param $table String: table name
1462 * @param $index String: index name
1463 * @param $fname String: function name for logging and profiling
1464 * @return Object query row in object form
1466 public function indexInfo( $table, $index,
1467 $fname = 'DatabaseIbm_db2::indexExists' )
1469 $table = $this->tableName( $table );
1471 SELECT name as indexname
1472 FROM sysibm.sysindexes si
1473 WHERE si.name='$index' AND si.tbname='$table'
1474 AND sc.tbcreator='$this->mSchema'
1476 $res = $this->query( $sql, $fname );
1480 $row = $this->fetchObject( $res );
1481 if ( $row != null ) {
1489 * Returns an information object on a table column
1490 * @param $table String: table name
1491 * @param $field String: column name
1492 * @return IBM_DB2Field
1494 public function fieldInfo( $table, $field ) {
1495 return IBM_DB2Field
::fromText( $this, $table, $field );
1499 * db2_field_type() wrapper
1500 * @param $res Object: result of executed statement
1501 * @param $index Mixed: number or name of the column
1502 * @return String column type
1504 public function fieldType( $res, $index ) {
1505 if ( $res instanceof ResultWrapper
) {
1506 $res = $res->result
;
1508 if ( $res instanceof IBM_DB2Result
) {
1509 $res = $res->getResult();
1511 return db2_field_type( $res, $index );
1515 * Verifies that an index was created as unique
1516 * @param $table String: table name
1517 * @param $index String: index name
1518 * @param $fname string function name for profiling
1521 public function indexUnique ( $table, $index,
1522 $fname = 'DatabaseIbm_db2::indexUnique' )
1524 $table = $this->tableName( $table );
1526 SELECT si.name as indexname
1527 FROM sysibm.sysindexes si
1528 WHERE si.name='$index' AND si.tbname='$table'
1529 AND sc.tbcreator='$this->mSchema'
1530 AND si.uniquerule IN ( 'U', 'P' )
1532 $res = $this->query( $sql, $fname );
1536 if ( $this->fetchObject( $res ) ) {
1544 * Returns the size of a text field, or -1 for "unlimited"
1545 * @param $table String: table name
1546 * @param $field String: column name
1547 * @return Integer: length or -1 for unlimited
1549 public function textFieldSize( $table, $field ) {
1550 $table = $this->tableName( $table );
1552 SELECT length as size
1553 FROM sysibm.syscolumns sc
1554 WHERE sc.name='$field' AND sc.tbname='$table'
1555 AND sc.tbcreator='$this->mSchema'
1557 $res = $this->query( $sql );
1558 $row = $this->fetchObject( $res );
1564 * Description is left as an exercise for the reader
1565 * @param $b Mixed: data to be encoded
1566 * @return IBM_DB2Blob
1568 public function encodeBlob( $b ) {
1569 return new IBM_DB2Blob( $b );
1573 * Description is left as an exercise for the reader
1574 * @param $b IBM_DB2Blob: data to be decoded
1577 public function decodeBlob( $b ) {
1582 * Convert into a list of string being concatenated
1583 * @param $stringList Array: strings that need to be joined together
1585 * @return String: joined by the concatenation operator
1587 public function buildConcat( $stringList ) {
1588 // || is equivalent to CONCAT
1589 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1590 return implode( ' || ', $stringList );
1594 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1595 * @param $column String: name of timestamp column
1596 * @return String: SQL code
1598 public function extractUnixEpoch( $column ) {
1600 // see SpecialAncientpages
1603 ######################################
1604 # Prepared statements
1605 ######################################
1608 * Intended to be compatible with the PEAR::DB wrapper functions.
1609 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1611 * ? = scalar value, quoted as necessary
1612 * ! = raw SQL bit (a function for instance)
1613 * & = filename; reads the file and inserts as a blob
1614 * (we don't use this though...)
1615 * @param $sql String: SQL statement with appropriate markers
1616 * @param $func String: Name of the function, for profiling
1617 * @return resource a prepared DB2 SQL statement
1619 public function prepare( $sql, $func = 'DB2::prepare' ) {
1620 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1625 * Frees resources associated with a prepared statement
1626 * @return Boolean success or failure
1628 public function freePrepared( $prepared ) {
1629 return db2_free_stmt( $prepared );
1633 * Execute a prepared query with the various arguments
1634 * @param $prepared String: the prepared sql
1635 * @param $args Mixed: either an array here, or put scalars as varargs
1636 * @return Resource: results object
1638 public function execute( $prepared, $args = null ) {
1639 if( !is_array( $args ) ) {
1641 $args = func_get_args();
1642 array_shift( $args );
1644 $res = db2_execute( $prepared, $args );
1646 $this->installPrint( db2_stmt_errormsg() );
1652 * For faking prepared SQL statements on DBs that don't support
1654 * @param $preparedQuery String: a 'preparable' SQL statement
1655 * @param $args Array of arguments to fill it with
1656 * @return String: executable statement
1658 public function fillPrepared( $preparedQuery, $args ) {
1660 $this->preparedArgs
=& $args;
1662 foreach ( $args as $i => $arg ) {
1663 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1666 return $preparedQuery;
1670 * Switches module between regular and install modes
1673 public function setMode( $mode ) {
1674 $old = $this->mMode
;
1675 $this->mMode
= $mode;
1680 * Bitwise negation of a column or value in SQL
1681 * Same as (~field) in C
1682 * @param $field String
1685 function bitNot( $field ) {
1686 // expecting bit-fields smaller than 4bytes
1687 return "BITNOT( $field )";
1691 * Bitwise AND of two columns or values in SQL
1692 * Same as (fieldLeft & fieldRight) in C
1693 * @param $fieldLeft String
1694 * @param $fieldRight String
1697 function bitAnd( $fieldLeft, $fieldRight ) {
1698 return "BITAND( $fieldLeft, $fieldRight )";
1702 * Bitwise OR of two columns or values in SQL
1703 * Same as (fieldLeft | fieldRight) in C
1704 * @param $fieldLeft String
1705 * @param $fieldRight String
1708 function bitOr( $fieldLeft, $fieldRight ) {
1709 return "BITOR( $fieldLeft, $fieldRight )";
1713 class IBM_DB2Helper
{
1714 public static function makeArray( $maybeArray ) {
1715 if ( !is_array( $maybeArray ) ) {
1716 return array( $maybeArray );