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
688 * If no more rows are available, false is returned.
690 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
691 * @return object|bool
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'].
711 * If no more rows are available, false is returned.
713 * @param $res array|ResultWrapper SQL result object as returned from Database::query(), etc.
715 * @throws DBUnexpectedError Thrown if the database returns an error
717 public function fetchRow( $res ) {
718 if ( $res instanceof ResultWrapper
) {
721 if ( db2_num_rows( $res ) > 0) {
722 wfSuppressWarnings();
723 $row = db2_fetch_array( $res );
725 if ( $this->lastErrno() ) {
726 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
727 . htmlspecialchars( $this->lastError() ) );
736 * Doesn't escape numbers
738 * @param $s String: string to escape
739 * @return string escaped string
741 public function addQuotes( $s ) {
742 //$this->installPrint( "DB2::addQuotes( $s )\n" );
743 if ( is_null( $s ) ) {
745 } elseif ( $s instanceof Blob
) {
746 return "'" . $s->fetch( $s ) . "'";
747 } elseif ( $s instanceof IBM_DB2Blob
) {
748 return "'" . $this->decodeBlob( $s ) . "'";
750 $s = $this->strencode( $s );
751 if ( is_numeric( $s ) ) {
759 * Verifies that a DB2 column/field type is numeric
761 * @param $type String: DB2 column type
762 * @return Boolean: true if numeric
764 public function is_numeric_type( $type ) {
765 switch ( strtoupper( $type ) ) {
780 * Alias for addQuotes()
781 * @param $s String: string to escape
782 * @return string escaped string
784 public function strencode( $s ) {
785 // Bloody useless function
786 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
787 // But also necessary
788 $s = db2_escape_string( $s );
789 // Wide characters are evil -- some of them look like '
790 $s = utf8_encode( $s );
792 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
793 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
794 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
799 * Switch into the database schema
801 protected function applySchema() {
802 if ( !( $this->mSchemaSet
) ) {
803 $this->mSchemaSet
= true;
804 $this->begin( __METHOD__
);
805 $this->doQuery( "SET SCHEMA = $this->mSchema" );
806 $this->commit( __METHOD__
);
811 * Start a transaction (mandatory)
813 protected function doBegin( $fname = 'DatabaseIbm_db2::begin' ) {
814 // BEGIN is implicit for DB2
815 // However, it requires that AutoCommit be off.
817 // Some MediaWiki code is still transaction-less (?).
818 // The strategy is to keep AutoCommit on for that code
819 // but switch it off whenever a transaction is begun.
820 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
822 $this->mTrxLevel
= 1;
827 * Must have a preceding begin()
829 protected function doCommit( $fname = 'DatabaseIbm_db2::commit' ) {
830 db2_commit( $this->mConn
);
832 // Some MediaWiki code is still transaction-less (?).
833 // The strategy is to keep AutoCommit on for that code
834 // but switch it off whenever a transaction is begun.
835 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
837 $this->mTrxLevel
= 0;
841 * Cancel a transaction
843 protected function doRollback( $fname = 'DatabaseIbm_db2::rollback' ) {
844 db2_rollback( $this->mConn
);
845 // turn auto-commit back on
846 // not sure if this is appropriate
847 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
848 $this->mTrxLevel
= 0;
852 * Makes an encoded list of strings from an array
854 * LIST_COMMA - comma separated, no field names
855 * LIST_AND - ANDed WHERE clause (without the WHERE)
856 * LIST_OR - ORed WHERE clause (without the WHERE)
857 * LIST_SET - comma separated with field names, like a SET clause
858 * LIST_NAMES - comma separated field names
859 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
862 * @throws DBUnexpectedError
865 function makeList( $a, $mode = LIST_COMMA
) {
866 if ( !is_array( $a ) ) {
867 throw new DBUnexpectedError( $this,
868 'DatabaseIbm_db2::makeList called with incorrect parameters' );
871 // if this is for a prepared UPDATE statement
872 // (this should be promoted to the parent class
873 // once other databases use prepared statements)
874 if ( $mode == LIST_SET_PREPARED
) {
877 foreach ( $a as $field => $value ) {
879 $list .= ", $field = ?";
881 $list .= "$field = ?";
890 // otherwise, call the usual function
891 return parent
::makeList( $a, $mode );
895 * Construct a LIMIT query with optional offset
896 * This is used for query pages
898 * @param $sql string SQL query we will append the limit too
899 * @param $limit integer the SQL limit
900 * @param bool|int $offset SQL offset (default false)
901 * @throws DBUnexpectedError
904 public function limitResult( $sql, $limit, $offset=false ) {
905 if( !is_numeric( $limit ) ) {
906 throw new DBUnexpectedError( $this,
907 "Invalid non-numeric limit passed to limitResult()\n" );
910 if ( stripos( $sql, 'where' ) === false ) {
911 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
913 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
916 return "$sql FETCH FIRST $limit ROWS ONLY ";
920 * Handle reserved keyword replacement in table names
922 * @param $name Object
923 * @param $format String Ignored parameter Default 'quoted'Boolean
926 public function tableName( $name, $format = 'quoted' ) {
927 // we want maximum compatibility with MySQL schema
932 * Generates a timestamp in an insertable format
934 * @param $ts string timestamp
935 * @return String: timestamp value
937 public function timestamp( $ts = 0 ) {
938 // TS_MW cannot be easily distinguished from an integer
939 return wfTimestamp( TS_DB2
, $ts );
943 * Return the next in a sequence, save the value for retrieval via insertId()
944 * @param $seqName String: name of a defined sequence in the database
945 * @return int next value in that sequence
947 public function nextSequenceValue( $seqName ) {
948 // Not using sequences in the primary schema to allow for easier migration
950 // Emulating MySQL behaviour of using NULL to signal that sequences
953 $safeseq = preg_replace( "/'/", "''", $seqName );
954 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
955 $row = $this->fetchRow( $res );
956 $this->mInsertId = $row[0];
957 return $this->mInsertId;
963 * This must be called after nextSequenceVal
964 * @return int Last sequence value used as a primary key
966 public function insertId() {
967 return $this->mInsertId
;
971 * Updates the mInsertId property with the value of the last insert
972 * into a generated column
974 * @param $table String: sanitized table name
975 * @param $primaryKey Mixed: string name of the primary key
976 * @param $stmt Resource: prepared statement resource
977 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
979 private function calcInsertId( $table, $primaryKey, $stmt ) {
981 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
986 * INSERT wrapper, inserts an array into a table
988 * $args may be a single associative array, or an array of arrays
989 * with numeric keys, for multi-row insert
991 * @param $table String: Name of the table to insert to.
992 * @param $args Array: Items to insert into the table.
993 * @param $fname String: Name of the function, for profiling
994 * @param $options String or Array. Valid options: IGNORE
996 * @return bool Success of insert operation. IGNORE always returns true.
998 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
1001 if ( !count( $args ) ) {
1004 // get database-specific table name (not used)
1005 $table = $this->tableName( $table );
1006 // format options as an array
1007 $options = IBM_DB2Helper
::makeArray( $options );
1008 // format args as an array of arrays
1009 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1010 $args = array( $args );
1013 // prevent insertion of NULL into primary key columns
1014 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
1015 // if there's only one primary key
1016 // we'll be able to read its value after insertion
1017 $primaryKey = false;
1018 if ( count( $primaryKeys ) == 1 ) {
1019 $primaryKey = $primaryKeys[0];
1023 $keys = array_keys( $args[0] );
1024 $key_count = count( $keys );
1026 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1027 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1031 // If we are not in a transaction, we need to be for savepoint trickery
1032 if ( !$this->mTrxLevel
) {
1033 $this->begin( __METHOD__
);
1036 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
1037 if ( $key_count == 1 ) {
1040 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
1042 $this->installPrint( "Preparing the following SQL:" );
1043 $this->installPrint( "$sql" );
1044 $this->installPrint( print_r( $args, true ));
1045 $stmt = $this->prepare( $sql );
1047 // start a transaction/enter transaction mode
1048 $this->begin( __METHOD__
);
1052 foreach ( $args as $row ) {
1053 //$this->installPrint( "Inserting " . print_r( $row, true ));
1054 // insert each row into the database
1055 $res = $res & $this->execute( $stmt, $row );
1057 $this->installPrint( 'Last error:' );
1058 $this->installPrint( $this->lastError() );
1060 // get the last inserted value into a generated column
1061 $this->calcInsertId( $table, $primaryKey, $stmt );
1064 $olde = error_reporting( 0 );
1065 // For future use, we may want to track the number of actual inserts
1066 // Right now, insert (all writes) simply return true/false
1067 $numrowsinserted = 0;
1069 // always return true
1072 foreach ( $args as $row ) {
1073 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1074 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
1076 $res2 = $this->execute( $stmt, $row );
1079 $this->installPrint( 'Last error:' );
1080 $this->installPrint( $this->lastError() );
1082 // get the last inserted value into a generated column
1083 $this->calcInsertId( $table, $primaryKey, $stmt );
1085 $errNum = $this->lastErrno();
1087 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
1088 $this->mStmtOptions
);
1090 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
1091 $this->mStmtOptions
);
1096 $olde = error_reporting( $olde );
1097 // Set the affected row count for the whole operation
1098 $this->mAffectedRows
= $numrowsinserted;
1100 // commit either way
1101 $this->commit( __METHOD__
);
1102 $this->freePrepared( $stmt );
1108 * Given a table name and a hash of columns with values
1109 * Removes primary key columns from the hash where the value is NULL
1111 * @param $table String: name of the table
1112 * @param $args Array of hashes of column names with values
1113 * @return Array: tuple( filtered array of columns, array of primary keys )
1115 private function removeNullPrimaryKeys( $table, $args ) {
1116 $schema = $this->mSchema
;
1118 // find out the primary keys
1119 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
1120 . strtoupper( $table )
1121 . "' AND TBCREATOR = '"
1122 . strtoupper( $schema )
1123 . "' AND KEYSEQ > 0" );
1127 $row = $this->fetchRow( $keyres );
1129 $row = $this->fetchRow( $keyres )
1132 $keys[] = strtolower( $row[0] );
1134 // remove primary keys
1135 foreach ( $args as $ai => $row ) {
1136 foreach ( $keys as $key ) {
1137 if ( $row[$key] == null ) {
1138 unset( $row[$key] );
1143 // return modified hash
1144 return array( $args, $keys );
1148 * UPDATE wrapper, takes a condition array and a SET array
1150 * @param $table String: The table to UPDATE
1151 * @param $values array An array of values to SET
1152 * @param $conds array An array of conditions ( WHERE ). Use '*' to update all rows.
1153 * @param $fname String: The Class::Function calling this function
1155 * @param $options array An array of UPDATE options, can be one or
1156 * more of IGNORE, LOW_PRIORITY
1159 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1160 $options = array() )
1162 $table = $this->tableName( $table );
1163 $opts = $this->makeUpdateOptions( $options );
1164 $sql = "UPDATE $opts $table SET "
1165 . $this->makeList( $values, LIST_SET_PREPARED
);
1166 if ( $conds != '*' ) {
1167 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1169 $stmt = $this->prepare( $sql );
1170 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1171 // assuming for now that an array with string keys will work
1172 // if not, convert to simple array first
1173 $result = $this->execute( $stmt, $values );
1174 $this->freePrepared( $stmt );
1180 * DELETE query wrapper
1182 * Use $conds == "*" to delete all rows
1183 * @param array $table
1184 * @param array|string $conds
1185 * @param string $fname
1186 * @throws DBUnexpectedError
1187 * @return bool|ResultWrapper
1189 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1191 throw new DBUnexpectedError( $this,
1192 'DatabaseIbm_db2::delete() called with no conditions' );
1194 $table = $this->tableName( $table );
1195 $sql = "DELETE FROM $table";
1196 if ( $conds != '*' ) {
1197 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1199 $result = $this->query( $sql, $fname );
1205 * Returns the number of rows affected by the last query or 0
1206 * @return Integer: the number of rows affected by the last query
1208 public function affectedRows() {
1209 if ( !is_null( $this->mAffectedRows
) ) {
1210 // Forced result for simulated queries
1211 return $this->mAffectedRows
;
1213 if( empty( $this->mLastResult
) ) {
1216 return db2_num_rows( $this->mLastResult
);
1220 * Returns the number of rows in the result set
1221 * Has to be called right after the corresponding select query
1222 * @param $res Object result set
1223 * @return Integer: number of rows
1225 public function numRows( $res ) {
1226 if ( $res instanceof ResultWrapper
) {
1227 $res = $res->result
;
1230 if ( $this->mNumRows
) {
1231 return $this->mNumRows
;
1238 * Moves the row pointer of the result set
1239 * @param $res Object: result set
1240 * @param $row Integer: row number
1241 * @return bool success or failure
1243 public function dataSeek( $res, $row ) {
1244 if ( $res instanceof ResultWrapper
) {
1245 return $res = $res->result
;
1247 if ( $res instanceof IBM_DB2Result
) {
1248 return $res->dataSeek( $row );
1250 wfDebug( "dataSeek operation in DB2 database\n" );
1255 # Fix notices in Block.php
1259 * Frees memory associated with a statement resource
1260 * @param $res Object: statement resource to free
1261 * @throws DBUnexpectedError
1262 * @return Boolean success or failure
1264 public function freeResult( $res ) {
1265 if ( $res instanceof ResultWrapper
) {
1266 $res = $res->result
;
1268 wfSuppressWarnings();
1269 $ok = db2_free_result( $res );
1270 wfRestoreWarnings();
1272 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1277 * Returns the number of columns in a resource
1278 * @param $res Object: statement resource
1279 * @return Number of fields/columns in resource
1281 public function numFields( $res ) {
1282 if ( $res instanceof ResultWrapper
) {
1283 $res = $res->result
;
1285 if ( $res instanceof IBM_DB2Result
) {
1286 $res = $res->getResult();
1288 return db2_num_fields( $res );
1292 * Returns the nth column name
1293 * @param $res Object: statement resource
1294 * @param $n Integer: Index of field or column
1295 * @return String name of nth column
1297 public function fieldName( $res, $n ) {
1298 if ( $res instanceof ResultWrapper
) {
1299 $res = $res->result
;
1301 if ( $res instanceof IBM_DB2Result
) {
1302 $res = $res->getResult();
1304 return db2_field_name( $res, $n );
1310 * @param $table Array or string, table name(s) (prefix auto-added)
1311 * @param $vars Array or string, field name(s) to be retrieved
1312 * @param $conds Array or string, condition(s) for WHERE
1313 * @param $fname String: calling function name (use __METHOD__)
1314 * for logs/profiling
1315 * @param $options array Associative array of options
1316 * (e.g. array( 'GROUP BY' => 'page_title' )),
1317 * see Database::makeSelectOptions code for list of
1319 * @param $join_conds array Associative array of table join conditions (optional)
1320 * (e.g. array( 'page' => array('LEFT JOIN',
1321 * 'page_latest=rev_id') )
1322 * @return Mixed: database result resource for fetch functions or false
1325 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1327 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1329 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1331 // We must adjust for offset
1332 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1333 $limit = $options['LIMIT'];
1334 $offset = $options['OFFSET'];
1337 // DB2 does not have a proper num_rows() function yet, so we must emulate
1338 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1342 // we want the count
1343 $vars2 = array( 'count( * ) as num_rows' );
1344 // respecting just the limit option
1345 $options2 = array();
1346 if ( isset( $options['LIMIT'] ) ) {
1347 $options2['LIMIT'] = $options['LIMIT'];
1349 // but don't try to emulate for GROUP BY
1350 if ( isset( $options['GROUP BY'] ) ) {
1354 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1357 $obj = $this->fetchObject( $res2 );
1358 $this->mNumRows
= $obj->num_rows
;
1360 return new ResultWrapper( $this, new IBM_DB2Result( $this, $res, $obj->num_rows
, $vars, $sql ) );
1364 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1365 * Has limited support for per-column options (colnum => 'DISTINCT')
1369 * @param $options array Associative array of options to be turned into
1370 * an SQL query, valid keys are listed in the function.
1373 function makeSelectOptions( $options ) {
1374 $preLimitTail = $postLimitTail = '';
1377 $noKeyOptions = array();
1378 foreach ( $options as $key => $option ) {
1379 if ( is_numeric( $key ) ) {
1380 $noKeyOptions[$option] = true;
1384 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1386 $preLimitTail .= $this->makeOrderBy( $options );
1388 if ( isset( $noKeyOptions['DISTINCT'] )
1389 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1391 $startOpts .= 'DISTINCT';
1394 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1398 * Returns link to IBM DB2 free download
1399 * @return String: wikitext of a link to the server software's web site
1401 public static function getSoftwareLink() {
1402 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1406 * Get search engine class. All subclasses of this
1407 * need to implement this if they wish to use searching.
1411 public function getSearchEngine() {
1412 return 'SearchIBM_DB2';
1416 * Did the last database access fail because of deadlock?
1419 public function wasDeadlock() {
1421 $err = $this->lastErrno();
1423 // This is literal port of the MySQL logic and may be wrong for DB2
1424 case '40001': // sql0911n, Deadlock or timeout, rollback
1425 case '57011': // sql0904n, Resource unavailable, no rollback
1426 case '57033': // sql0913n, Deadlock or timeout, no rollback
1427 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1434 * Ping the server and try to reconnect if it there is no connection
1435 * The connection may be closed and reopened while this happens
1436 * @return Boolean: whether the connection exists
1438 public function ping() {
1439 // db2_ping() doesn't exist
1442 $this->openUncataloged( $this->mDBName
, $this->mUser
,
1443 $this->mPassword
, $this->mServer
, $this->mPort
);
1447 ######################################
1448 # Unimplemented and not applicable
1449 ######################################
1452 * Only useful with fake prepare like in base Database class
1455 public function fillPreparedArg( $matches ) {
1456 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1460 ######################################
1462 ######################################
1465 * Returns information about an index
1466 * If errors are explicitly ignored, returns NULL on failure
1467 * @param $table String: table name
1468 * @param $index String: index name
1469 * @param $fname String: function name for logging and profiling
1470 * @return Object query row in object form
1472 public function indexInfo( $table, $index,
1473 $fname = 'DatabaseIbm_db2::indexExists' )
1475 $table = $this->tableName( $table );
1477 SELECT name as indexname
1478 FROM sysibm.sysindexes si
1479 WHERE si.name='$index' AND si.tbname='$table'
1480 AND sc.tbcreator='$this->mSchema'
1482 $res = $this->query( $sql, $fname );
1486 $row = $this->fetchObject( $res );
1487 if ( $row != null ) {
1495 * Returns an information object on a table column
1496 * @param $table String: table name
1497 * @param $field String: column name
1498 * @return IBM_DB2Field
1500 public function fieldInfo( $table, $field ) {
1501 return IBM_DB2Field
::fromText( $this, $table, $field );
1505 * db2_field_type() wrapper
1506 * @param $res Object: result of executed statement
1507 * @param $index Mixed: number or name of the column
1508 * @return String column type
1510 public function fieldType( $res, $index ) {
1511 if ( $res instanceof ResultWrapper
) {
1512 $res = $res->result
;
1514 if ( $res instanceof IBM_DB2Result
) {
1515 $res = $res->getResult();
1517 return db2_field_type( $res, $index );
1521 * Verifies that an index was created as unique
1522 * @param $table String: table name
1523 * @param $index String: index name
1524 * @param $fname string function name for profiling
1527 public function indexUnique ( $table, $index,
1528 $fname = 'DatabaseIbm_db2::indexUnique' )
1530 $table = $this->tableName( $table );
1532 SELECT si.name as indexname
1533 FROM sysibm.sysindexes si
1534 WHERE si.name='$index' AND si.tbname='$table'
1535 AND sc.tbcreator='$this->mSchema'
1536 AND si.uniquerule IN ( 'U', 'P' )
1538 $res = $this->query( $sql, $fname );
1542 if ( $this->fetchObject( $res ) ) {
1550 * Returns the size of a text field, or -1 for "unlimited"
1551 * @param $table String: table name
1552 * @param $field String: column name
1553 * @return Integer: length or -1 for unlimited
1555 public function textFieldSize( $table, $field ) {
1556 $table = $this->tableName( $table );
1558 SELECT length as size
1559 FROM sysibm.syscolumns sc
1560 WHERE sc.name='$field' AND sc.tbname='$table'
1561 AND sc.tbcreator='$this->mSchema'
1563 $res = $this->query( $sql );
1564 $row = $this->fetchObject( $res );
1570 * Description is left as an exercise for the reader
1571 * @param $b Mixed: data to be encoded
1572 * @return IBM_DB2Blob
1574 public function encodeBlob( $b ) {
1575 return new IBM_DB2Blob( $b );
1579 * Description is left as an exercise for the reader
1580 * @param $b IBM_DB2Blob: data to be decoded
1583 public function decodeBlob( $b ) {
1588 * Convert into a list of string being concatenated
1589 * @param $stringList Array: strings that need to be joined together
1591 * @return String: joined by the concatenation operator
1593 public function buildConcat( $stringList ) {
1594 // || is equivalent to CONCAT
1595 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1596 return implode( ' || ', $stringList );
1600 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1601 * @param $column String: name of timestamp column
1602 * @return String: SQL code
1604 public function extractUnixEpoch( $column ) {
1606 // see SpecialAncientpages
1609 ######################################
1610 # Prepared statements
1611 ######################################
1614 * Intended to be compatible with the PEAR::DB wrapper functions.
1615 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1617 * ? = scalar value, quoted as necessary
1618 * ! = raw SQL bit (a function for instance)
1619 * & = filename; reads the file and inserts as a blob
1620 * (we don't use this though...)
1621 * @param $sql String: SQL statement with appropriate markers
1622 * @param $func String: Name of the function, for profiling
1623 * @return resource a prepared DB2 SQL statement
1625 public function prepare( $sql, $func = 'DB2::prepare' ) {
1626 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1631 * Frees resources associated with a prepared statement
1632 * @return Boolean success or failure
1634 public function freePrepared( $prepared ) {
1635 return db2_free_stmt( $prepared );
1639 * Execute a prepared query with the various arguments
1640 * @param $prepared String: the prepared sql
1641 * @param $args Mixed: either an array here, or put scalars as varargs
1642 * @return Resource: results object
1644 public function execute( $prepared, $args = null ) {
1645 if( !is_array( $args ) ) {
1647 $args = func_get_args();
1648 array_shift( $args );
1650 $res = db2_execute( $prepared, $args );
1652 $this->installPrint( db2_stmt_errormsg() );
1658 * For faking prepared SQL statements on DBs that don't support
1660 * @param $preparedQuery String: a 'preparable' SQL statement
1661 * @param $args Array of arguments to fill it with
1662 * @return String: executable statement
1664 public function fillPrepared( $preparedQuery, $args ) {
1666 $this->preparedArgs
=& $args;
1668 foreach ( $args as $i => $arg ) {
1669 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1672 return $preparedQuery;
1676 * Switches module between regular and install modes
1679 public function setMode( $mode ) {
1680 $old = $this->mMode
;
1681 $this->mMode
= $mode;
1686 * Bitwise negation of a column or value in SQL
1687 * Same as (~field) in C
1688 * @param $field String
1691 function bitNot( $field ) {
1692 // expecting bit-fields smaller than 4bytes
1693 return "BITNOT( $field )";
1697 * Bitwise AND of two columns or values in SQL
1698 * Same as (fieldLeft & fieldRight) in C
1699 * @param $fieldLeft String
1700 * @param $fieldRight String
1703 function bitAnd( $fieldLeft, $fieldRight ) {
1704 return "BITAND( $fieldLeft, $fieldRight )";
1708 * Bitwise OR of two columns or values in SQL
1709 * Same as (fieldLeft | fieldRight) in C
1710 * @param $fieldLeft String
1711 * @param $fieldRight String
1714 function bitOr( $fieldLeft, $fieldRight ) {
1715 return "BITOR( $fieldLeft, $fieldRight )";
1719 class IBM_DB2Helper
{
1720 public static function makeArray( $maybeArray ) {
1721 if ( !is_array( $maybeArray ) ) {
1722 return array( $maybeArray );