3 * This is the IBM DB2 database abstraction layer.
4 * See maintenance/ibm_db2/README for development notes
5 * and other specific information
9 * @author leo.petr+mediawiki@gmail.com
13 * This represents a column in a DB2 database
16 class IBM_DB2Field
implements Field
{
18 private $tablename = '';
20 private $nullable = false;
21 private $max_length = 0;
24 * Builder method for the class
25 * @param $db DatabaseIbm_db2: Database interface
26 * @param $table String: table name
27 * @param $field String: column name
28 * @return IBM_DB2Field
30 static function fromText( $db, $table, $field ) {
35 lcase( coltype ) AS typname,
36 nulls AS attnotnull, length AS attlen
37 FROM sysibm.syscolumns
38 WHERE tbcreator=%s AND tbname=%s AND name=%s;
42 $db->addQuotes( $wgDBmwschema ),
43 $db->addQuotes( $table ),
44 $db->addQuotes( $field )
47 $row = $db->fetchObject( $res );
51 $n = new IBM_DB2Field
;
52 $n->type
= $row->typname
;
53 $n->nullable
= ( $row->attnotnull
== 'N' );
55 $n->tablename
= $table;
56 $n->max_length
= $row->attlen
;
61 * @return string column name
63 function name() { return $this->name
; }
66 * @return string table name
68 function tableName() { return $this->tablename
; }
71 * @return string column type
73 function type() { return $this->type
; }
76 * @return bool true or false
78 function isNullable() { return $this->nullable
; }
80 * How much can you fit in the column per row?
83 function maxLength() { return $this->max_length
; }
87 * Wrapper around binary large objects
93 public function __construct( $data ) {
97 public function getData() {
101 public function __toString() {
107 * Primary database interface
110 class DatabaseIbm_db2
extends DatabaseBase
{
113 protected $mLastQuery = '';
114 protected $mPHPError = false;
116 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
117 protected $mOpened = false;
119 protected $mTablePrefix;
121 protected $mTrxLevel = 0;
122 protected $mErrorCount = 0;
123 protected $mLBInfo = array();
124 protected $mFakeSlaveLag = null, $mFakeMaster = false;
128 /** Database server port */
129 protected $mPort = null;
130 /** Schema for tables, stored procedures, triggers */
131 protected $mSchema = null;
132 /** Whether the schema has been applied in this session */
133 protected $mSchemaSet = false;
134 /** Result of last query */
135 protected $mLastResult = null;
136 /** Number of rows affected by last INSERT/UPDATE/DELETE */
137 protected $mAffectedRows = null;
138 /** Number of rows returned by last SELECT */
139 protected $mNumRows = null;
141 /** Connection config options - see constructor */
142 public $mConnOptions = array();
143 /** Statement config options -- see constructor */
144 public $mStmtOptions = array();
146 /** Default schema */
147 const USE_GLOBAL
= 'get from global';
149 /** Option that applies to nothing */
150 const NONE_OPTION
= 0x00;
151 /** Option that applies to connection objects */
152 const CONN_OPTION
= 0x01;
153 /** Option that applies to statement objects */
154 const STMT_OPTION
= 0x02;
156 /** Regular operation mode -- minimal debug messages */
157 const REGULAR_MODE
= 'regular';
158 /** Installation mode -- lots of debug messages */
159 const INSTALL_MODE
= 'install';
161 /** Controls the level of debug message output */
162 protected $mMode = self
::REGULAR_MODE
;
164 /** Last sequence value used for a primary key */
165 protected $mInsertId = null;
167 ######################################
168 # Getters and Setters
169 ######################################
172 * Returns true if this database supports (and uses) cascading deletes
174 function cascadingDeletes() {
179 * Returns true if this database supports (and uses) triggers (e.g. on the
182 function cleanupTriggers() {
187 * Returns true if this database is strict about what can be put into an
189 * Specifically, it uses a NULL value instead of an empty string.
191 function strictIPs() {
196 * Returns true if this database uses timestamps rather than integers
198 function realTimestamps() {
203 * Returns true if this database does an implicit sort when doing GROUP BY
205 function implicitGroupby() {
210 * Returns true if this database does an implicit order by when the column
212 * For example: SELECT page_title FROM page LIMIT 1
214 function implicitOrderby() {
219 * Returns true if this database can do a native search on IP columns
220 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
222 function searchableIPs() {
227 * Returns true if this database can use functional indexes
229 function functionalIndexes() {
234 * Returns a unique string representing the wiki on the server
236 function getWikiID() {
237 if( $this->mSchema
) {
238 return "{$this->mDBname}-{$this->mSchema}";
240 return $this->mDBname
;
250 * @param $server String: hostname of database server
251 * @param $user String: username
252 * @param $password String: password
253 * @param $dbName String: database name on the server
254 * @param $flags Integer: database behaviour flags (optional, unused)
255 * @param $schema String
257 public function __construct( $server = false, $user = false,
259 $dbName = false, $flags = 0,
260 $schema = self
::USE_GLOBAL
)
262 global $wgDBmwschema;
264 if ( $schema == self
::USE_GLOBAL
) {
265 $this->mSchema
= $wgDBmwschema;
267 $this->mSchema
= $schema;
270 // configure the connection and statement objects
272 $this->setDB2Option( 'cursor', 'DB2_SCROLLABLE',
273 self::CONN_OPTION | self::STMT_OPTION );
275 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
276 self
::CONN_OPTION | self
::STMT_OPTION
);
277 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
279 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
282 parent
::__construct( $server, $user, $password, $dbName, DBO_TRX |
$flags );
286 * Enables options only if the ibm_db2 extension version supports them
287 * @param $name String: name of the option in the options array
288 * @param $const String: name of the constant holding the right option value
289 * @param $type Integer: whether this is a Connection or Statement otion
291 private function setDB2Option( $name, $const, $type ) {
292 if ( defined( $const ) ) {
293 if ( $type & self
::CONN_OPTION
) {
294 $this->mConnOptions
[$name] = constant( $const );
296 if ( $type & self
::STMT_OPTION
) {
297 $this->mStmtOptions
[$name] = constant( $const );
301 "$const is not defined. ibm_db2 version is likely too low." );
306 * Outputs debug information in the appropriate place
307 * @param $string String: the relevant debug message
309 private function installPrint( $string ) {
310 wfDebug( "$string\n" );
311 if ( $this->mMode
== self
::INSTALL_MODE
) {
312 print "<li><pre>$string</pre></li>";
318 * Opens a database connection and returns it
319 * Closes any existing connection
321 * @param $server String: hostname
322 * @param $user String
323 * @param $password String
324 * @param $dbName String: database name
325 * @return a fresh connection
327 public function open( $server, $user, $password, $dbName ) {
328 wfProfileIn( __METHOD__
);
330 # Load IBM DB2 driver if missing
333 # Test for IBM DB2 support, to avoid suppressed fatal error
334 if ( !function_exists( 'db2_connect' ) ) {
335 throw new DBConnectionError( $this, "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?" );
340 // Close existing connection
343 $this->mServer
= $server;
344 $this->mPort
= $port = $wgDBport;
345 $this->mUser
= $user;
346 $this->mPassword
= $password;
347 $this->mDBname
= $dbName;
349 $this->openUncataloged( $dbName, $user, $password, $server, $port );
351 if ( !$this->mConn
) {
352 $this->installPrint( "DB connection error\n" );
354 "Server: $server, Database: $dbName, User: $user, Password: "
355 . substr( $password, 0, 3 ) . "...\n" );
356 $this->installPrint( $this->lastError() . "\n" );
357 wfProfileOut( __METHOD__
);
358 wfDebug( "DB connection error\n" );
359 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
360 wfDebug( $this->lastError() . "\n" );
361 throw new DBConnectionError( $this, $this->lastError() );
364 // Apply connection config
365 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
366 // Some MediaWiki code is still transaction-less (?).
367 // The strategy is to keep AutoCommit on for that code
368 // but switch it off whenever a transaction is begun.
369 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
371 $this->mOpened
= true;
372 $this->applySchema();
374 wfProfileOut( __METHOD__
);
379 * Opens a cataloged database connection, sets mConn
381 protected function openCataloged( $dbName, $user, $password ) {
382 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
386 * Opens an uncataloged database connection, sets mConn
388 protected function openUncataloged( $dbName, $user, $password, $server, $port )
390 $dsn = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$dbName;CHARSET=UTF-8;HOSTNAME=$server;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
391 @$this->mConn
= db2_pconnect($dsn, "", "", array());
395 * Closes a database connection, if it is open
396 * Returns success, true if already closed
398 public function close() {
399 $this->mOpened
= false;
400 if ( $this->mConn
) {
401 if ( $this->trxLevel() > 0 ) {
404 return db2_close( $this->mConn
);
411 * Retrieves the most current database error
412 * Forces a database rollback
414 public function lastError() {
415 $connerr = db2_conn_errormsg();
420 $stmterr = db2_stmt_errormsg();
430 * Get the last error number
431 * Return 0 if no error
434 public function lastErrno() {
435 $connerr = db2_conn_error();
439 $stmterr = db2_stmt_error();
447 * Is a database connection open?
450 public function isOpen() { return $this->mOpened
; }
453 * The DBMS-dependent part of query()
454 * @param $sql String: SQL query.
455 * @return object Result object for fetch functions or false on failure
457 protected function doQuery( $sql ) {
458 $this->applySchema();
460 // Needed to handle any UTF-8 encoding issues in the raw sql
461 // Note that we fully support prepared statements for DB2
462 // prepare() and execute() should be used instead of doQuery() whenever possible
463 $sql = utf8_decode($sql);
465 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
466 if( $ret == false ) {
467 $error = db2_stmt_errormsg();
469 $this->installPrint( "<pre>$sql</pre>" );
470 $this->installPrint( $error );
471 throw new DBUnexpectedError( $this, 'SQL error: '
472 . htmlspecialchars( $error ) );
474 $this->mLastResult
= $ret;
475 $this->mAffectedRows
= null; // Not calculated until asked for
480 * @return string Version information from the database
482 public function getServerVersion() {
483 $info = db2_server_info( $this->mConn
);
484 return $info->DBMS_VER
;
488 * Queries whether a given table exists
491 public function tableExists( $table ) {
492 $schema = $this->mSchema
;
494 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
495 strtoupper( $table ) .
496 "' AND ST.CREATOR = '" .
497 strtoupper( $schema ) . "'";
498 $res = $this->query( $sql );
503 // If the table exists, there should be one of it
504 @$row = $this->fetchRow( $res );
506 if ( $count == '1' ||
$count == 1 ) {
514 * Fetch the next row from the given result object, in object form.
515 * Fields can be retrieved with $row->fieldname, with fields acting like
518 * @param $res SQL result object as returned from Database::query(), etc.
519 * @return DB2 row object
520 * @throws DBUnexpectedError Thrown if the database returns an error
522 public function fetchObject( $res ) {
523 if ( $res instanceof ResultWrapper
) {
526 @$row = db2_fetch_object( $res );
527 if( $this->lastErrno() ) {
528 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
529 . htmlspecialchars( $this->lastError() ) );
535 * Fetch the next row from the given result object, in associative array
536 * form. Fields are retrieved with $row['fieldname'].
538 * @param $res SQL result object as returned from Database::query(), etc.
539 * @return DB2 row object
540 * @throws DBUnexpectedError Thrown if the database returns an error
542 public function fetchRow( $res ) {
543 if ( $res instanceof ResultWrapper
) {
546 if ( db2_num_rows( $res ) > 0) {
547 @$row = db2_fetch_array( $res );
548 if ( $this->lastErrno() ) {
549 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
550 . htmlspecialchars( $this->lastError() ) );
558 * Create tables, stored procedures, and so on
560 public function setup_database() {
562 // TODO: switch to root login if available
564 // Switch into the correct namespace
565 $this->applySchema();
568 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
569 if ( $res !== true ) {
570 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
574 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
575 if ( $res !== true ) {
576 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
578 print '<li>Foreign keys done</li>';
581 // TODO: populate interwiki links
583 if ( $this->lastError() ) {
585 'Errors encountered during table creation -- rolled back' );
586 $this->installPrint( 'Please install again' );
591 } catch ( MWException
$mwe ) {
592 print "<br><pre>$mwe</pre><br>";
598 * Doesn't escape numbers
600 * @param $s String: string to escape
601 * @return escaped string
603 public function addQuotes( $s ) {
604 //$this->installPrint( "DB2::addQuotes( $s )\n" );
605 if ( is_null( $s ) ) {
607 } elseif ( $s instanceof Blob
) {
608 return "'" . $s->fetch( $s ) . "'";
609 } elseif ( $s instanceof IBM_DB2Blob
) {
610 return "'" . $this->decodeBlob( $s ) . "'";
612 $s = $this->strencode( $s );
613 if ( is_numeric( $s ) ) {
621 * Verifies that a DB2 column/field type is numeric
623 * @param $type String: DB2 column type
624 * @return Boolean: true if numeric
626 public function is_numeric_type( $type ) {
627 switch ( strtoupper( $type ) ) {
642 * Alias for addQuotes()
643 * @param $s String: string to escape
644 * @return escaped string
646 public function strencode( $s ) {
647 // Bloody useless function
648 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
649 // But also necessary
650 $s = db2_escape_string( $s );
651 // Wide characters are evil -- some of them look like '
652 $s = utf8_encode( $s );
654 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
655 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
656 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
661 * Switch into the database schema
663 protected function applySchema() {
664 if ( !( $this->mSchemaSet
) ) {
665 $this->mSchemaSet
= true;
667 $this->doQuery( "SET SCHEMA = $this->mSchema" );
673 * Start a transaction (mandatory)
675 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
676 // BEGIN is implicit for DB2
677 // However, it requires that AutoCommit be off.
679 // Some MediaWiki code is still transaction-less (?).
680 // The strategy is to keep AutoCommit on for that code
681 // but switch it off whenever a transaction is begun.
682 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
684 $this->mTrxLevel
= 1;
689 * Must have a preceding begin()
691 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
692 db2_commit( $this->mConn
);
694 // Some MediaWiki code is still transaction-less (?).
695 // The strategy is to keep AutoCommit on for that code
696 // but switch it off whenever a transaction is begun.
697 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
699 $this->mTrxLevel
= 0;
703 * Cancel a transaction
705 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
706 db2_rollback( $this->mConn
);
707 // turn auto-commit back on
708 // not sure if this is appropriate
709 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
710 $this->mTrxLevel
= 0;
714 * Makes an encoded list of strings from an array
716 * LIST_COMMA - comma separated, no field names
717 * LIST_AND - ANDed WHERE clause (without the WHERE)
718 * LIST_OR - ORed WHERE clause (without the WHERE)
719 * LIST_SET - comma separated with field names, like a SET clause
720 * LIST_NAMES - comma separated field names
721 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
723 function makeList( $a, $mode = LIST_COMMA
) {
724 if ( !is_array( $a ) ) {
725 throw new DBUnexpectedError( $this,
726 'DatabaseIbm_db2::makeList called with incorrect parameters' );
729 // if this is for a prepared UPDATE statement
730 // (this should be promoted to the parent class
731 // once other databases use prepared statements)
732 if ( $mode == LIST_SET_PREPARED
) {
735 foreach ( $a as $field => $value ) {
737 $list .= ", $field = ?";
739 $list .= "$field = ?";
748 // otherwise, call the usual function
749 return parent
::makeList( $a, $mode );
753 * Construct a LIMIT query with optional offset
754 * This is used for query pages
756 * @param $sql string SQL query we will append the limit too
757 * @param $limit integer the SQL limit
758 * @param $offset integer the SQL offset (default false)
760 public function limitResult( $sql, $limit, $offset=false ) {
761 if( !is_numeric( $limit ) ) {
762 throw new DBUnexpectedError( $this,
763 "Invalid non-numeric limit passed to limitResult()\n" );
766 if ( stripos( $sql, 'where' ) === false ) {
767 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
769 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
772 return "$sql FETCH FIRST $limit ROWS ONLY ";
776 * Handle reserved keyword replacement in table names
778 * @param $name Object
779 * @param $name Boolean
782 public function tableName( $name, $quoted = true ) {
783 // we want maximum compatibility with MySQL schema
788 * Generates a timestamp in an insertable format
790 * @param $ts timestamp
791 * @return String: timestamp value
793 public function timestamp( $ts = 0 ) {
794 // TS_MW cannot be easily distinguished from an integer
795 return wfTimestamp( TS_DB2
, $ts );
799 * Return the next in a sequence, save the value for retrieval via insertId()
800 * @param $seqName String: name of a defined sequence in the database
801 * @return next value in that sequence
803 public function nextSequenceValue( $seqName ) {
804 // Not using sequences in the primary schema to allow for easier migration
806 // Emulating MySQL behaviour of using NULL to signal that sequences
809 $safeseq = preg_replace( "/'/", "''", $seqName );
810 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
811 $row = $this->fetchRow( $res );
812 $this->mInsertId = $row[0];
813 return $this->mInsertId;
819 * This must be called after nextSequenceVal
820 * @return Last sequence value used as a primary key
822 public function insertId() {
823 return $this->mInsertId
;
827 * Updates the mInsertId property with the value of the last insert
828 * into a generated column
830 * @param $table String: sanitized table name
831 * @param $primaryKey Mixed: string name of the primary key
832 * @param $stmt Resource: prepared statement resource
833 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
835 private function calcInsertId( $table, $primaryKey, $stmt ) {
837 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
842 * INSERT wrapper, inserts an array into a table
844 * $args may be a single associative array, or an array of arrays
845 * with numeric keys, for multi-row insert
847 * @param $table String: Name of the table to insert to.
848 * @param $args Array: Items to insert into the table.
849 * @param $fname String: Name of the function, for profiling
850 * @param $options String or Array. Valid options: IGNORE
852 * @return bool Success of insert operation. IGNORE always returns true.
854 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
857 if ( !count( $args ) ) {
860 // get database-specific table name (not used)
861 $table = $this->tableName( $table );
862 // format options as an array
863 $options = IBM_DB2Helper
::makeArray( $options );
864 // format args as an array of arrays
865 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
866 $args = array( $args );
869 // prevent insertion of NULL into primary key columns
870 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
871 // if there's only one primary key
872 // we'll be able to read its value after insertion
874 if ( count( $primaryKeys ) == 1 ) {
875 $primaryKey = $primaryKeys[0];
879 $keys = array_keys( $args[0] );
880 $key_count = count( $keys );
882 // If IGNORE is set, we use savepoints to emulate mysql's behavior
883 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
887 // If we are not in a transaction, we need to be for savepoint trickery
888 if ( !$this->mTrxLevel
) {
892 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
893 if ( $key_count == 1 ) {
896 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
898 $this->installPrint( "Preparing the following SQL:" );
899 $this->installPrint( "$sql" );
900 $this->installPrint( print_r( $args, true ));
901 $stmt = $this->prepare( $sql );
903 // start a transaction/enter transaction mode
908 foreach ( $args as $row ) {
909 //$this->installPrint( "Inserting " . print_r( $row, true ));
910 // insert each row into the database
911 $res = $res & $this->execute( $stmt, $row );
913 $this->installPrint( 'Last error:' );
914 $this->installPrint( $this->lastError() );
916 // get the last inserted value into a generated column
917 $this->calcInsertId( $table, $primaryKey, $stmt );
920 $olde = error_reporting( 0 );
921 // For future use, we may want to track the number of actual inserts
922 // Right now, insert (all writes) simply return true/false
923 $numrowsinserted = 0;
925 // always return true
928 foreach ( $args as $row ) {
929 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
930 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
932 $res2 = $this->execute( $stmt, $row );
935 $this->installPrint( 'Last error:' );
936 $this->installPrint( $this->lastError() );
938 // get the last inserted value into a generated column
939 $this->calcInsertId( $table, $primaryKey, $stmt );
941 $errNum = $this->lastErrno();
943 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
944 $this->mStmtOptions
);
946 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
947 $this->mStmtOptions
);
952 $olde = error_reporting( $olde );
953 // Set the affected row count for the whole operation
954 $this->mAffectedRows
= $numrowsinserted;
958 $this->freePrepared( $stmt );
964 * Given a table name and a hash of columns with values
965 * Removes primary key columns from the hash where the value is NULL
967 * @param $table String: name of the table
968 * @param $args Array of hashes of column names with values
969 * @return Array: tuple( filtered array of columns, array of primary keys )
971 private function removeNullPrimaryKeys( $table, $args ) {
972 $schema = $this->mSchema
;
974 // find out the primary keys
975 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
976 . strtoupper( $table )
977 . "' AND TBCREATOR = '"
978 . strtoupper( $schema )
979 . "' AND KEYSEQ > 0" );
983 $row = $this->fetchRow( $keyres );
985 $row = $this->fetchRow( $keyres )
988 $keys[] = strtolower( $row[0] );
990 // remove primary keys
991 foreach ( $args as $ai => $row ) {
992 foreach ( $keys as $key ) {
993 if ( $row[$key] == null ) {
999 // return modified hash
1000 return array( $args, $keys );
1004 * UPDATE wrapper, takes a condition array and a SET array
1006 * @param $table String: The table to UPDATE
1007 * @param $values An array of values to SET
1008 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1009 * @param $fname String: The Class::Function calling this function
1011 * @param $options An array of UPDATE options, can be one or
1012 * more of IGNORE, LOW_PRIORITY
1015 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1016 $options = array() )
1018 $table = $this->tableName( $table );
1019 $opts = $this->makeUpdateOptions( $options );
1020 $sql = "UPDATE $opts $table SET "
1021 . $this->makeList( $values, LIST_SET_PREPARED
);
1022 if ( $conds != '*' ) {
1023 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1025 $stmt = $this->prepare( $sql );
1026 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1027 // assuming for now that an array with string keys will work
1028 // if not, convert to simple array first
1029 $result = $this->execute( $stmt, $values );
1030 $this->freePrepared( $stmt );
1036 * DELETE query wrapper
1038 * Use $conds == "*" to delete all rows
1040 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1042 throw new DBUnexpectedError( $this,
1043 'DatabaseIbm_db2::delete() called with no conditions' );
1045 $table = $this->tableName( $table );
1046 $sql = "DELETE FROM $table";
1047 if ( $conds != '*' ) {
1048 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1050 $result = $this->query( $sql, $fname );
1056 * Returns the number of rows affected by the last query or 0
1057 * @return Integer: the number of rows affected by the last query
1059 public function affectedRows() {
1060 if ( !is_null( $this->mAffectedRows
) ) {
1061 // Forced result for simulated queries
1062 return $this->mAffectedRows
;
1064 if( empty( $this->mLastResult
) ) {
1067 return db2_num_rows( $this->mLastResult
);
1071 * Simulates REPLACE with a DELETE followed by INSERT
1072 * @param $table Object
1073 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1074 * @param $rows Array: rows to insert
1075 * @param $fname String: name of the function for profiling
1078 function replace( $table, $uniqueIndexes, $rows,
1079 $fname = 'DatabaseIbm_db2::replace' )
1081 $table = $this->tableName( $table );
1083 if ( count( $rows )==0 ) {
1088 if ( !is_array( reset( $rows ) ) ) {
1089 $rows = array( $rows );
1092 foreach( $rows as $row ) {
1093 # Delete rows which collide
1094 if ( $uniqueIndexes ) {
1095 $sql = "DELETE FROM $table WHERE ";
1097 foreach ( $uniqueIndexes as $index ) {
1104 if ( is_array( $index ) ) {
1106 foreach ( $index as $col ) {
1112 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1115 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1119 $this->query( $sql, $fname );
1122 # Now insert the row
1123 $this->insert($table, $row);
1128 * Returns the number of rows in the result set
1129 * Has to be called right after the corresponding select query
1130 * @param $res Object result set
1131 * @return Integer: number of rows
1133 public function numRows( $res ) {
1134 if ( $res instanceof ResultWrapper
) {
1135 $res = $res->result
;
1138 if ( $this->mNumRows
) {
1139 return $this->mNumRows
;
1146 * Moves the row pointer of the result set
1147 * @param $res Object: result set
1148 * @param $row Integer: row number
1149 * @return success or failure
1151 public function dataSeek( $res, $row ) {
1152 if ( $res instanceof ResultWrapper
) {
1153 $res = $res->result
;
1155 return db2_fetch_row( $res, $row );
1159 # Fix notices in Block.php
1163 * Frees memory associated with a statement resource
1164 * @param $res Object: statement resource to free
1165 * @return Boolean success or failure
1167 public function freeResult( $res ) {
1168 if ( $res instanceof ResultWrapper
) {
1169 $res = $res->result
;
1171 if ( !@db2_free_result
( $res ) ) {
1172 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1177 * Returns the number of columns in a resource
1178 * @param $res Object: statement resource
1179 * @return Number of fields/columns in resource
1181 public function numFields( $res ) {
1182 if ( $res instanceof ResultWrapper
) {
1183 $res = $res->result
;
1185 return db2_num_fields( $res );
1189 * Returns the nth column name
1190 * @param $res Object: statement resource
1191 * @param $n Integer: Index of field or column
1192 * @return String name of nth column
1194 public function fieldName( $res, $n ) {
1195 if ( $res instanceof ResultWrapper
) {
1196 $res = $res->result
;
1198 return db2_field_name( $res, $n );
1204 * @param $table Array or string, table name(s) (prefix auto-added)
1205 * @param $vars Array or string, field name(s) to be retrieved
1206 * @param $conds Array or string, condition(s) for WHERE
1207 * @param $fname String: calling function name (use __METHOD__)
1208 * for logs/profiling
1209 * @param $options Associative array of options
1210 * (e.g. array('GROUP BY' => 'page_title')),
1211 * see Database::makeSelectOptions code for list of
1213 * @param $join_conds Associative array of table join conditions (optional)
1214 * (e.g. array( 'page' => array('LEFT JOIN',
1215 * 'page_latest=rev_id') )
1216 * @return Mixed: database result resource for fetch functions or false
1219 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1221 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1224 // We must adjust for offset
1225 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1226 $limit = $options['LIMIT'];
1227 $offset = $options['OFFSET'];
1230 // DB2 does not have a proper num_rows() function yet, so we must emulate
1231 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1235 // we want the count
1236 $vars2 = array( 'count( * ) as num_rows' );
1237 // respecting just the limit option
1238 $options2 = array();
1239 if ( isset( $options['LIMIT'] ) ) {
1240 $options2['LIMIT'] = $options['LIMIT'];
1242 // but don't try to emulate for GROUP BY
1243 if ( isset( $options['GROUP BY'] ) ) {
1247 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1249 $obj = $this->fetchObject( $res2 );
1250 $this->mNumRows
= $obj->num_rows
;
1256 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1257 * Has limited support for per-column options (colnum => 'DISTINCT')
1261 * @param $options Associative array of options to be turned into
1262 * an SQL query, valid keys are listed in the function.
1265 function makeSelectOptions( $options ) {
1266 $preLimitTail = $postLimitTail = '';
1269 $noKeyOptions = array();
1270 foreach ( $options as $key => $option ) {
1271 if ( is_numeric( $key ) ) {
1272 $noKeyOptions[$option] = true;
1276 if ( isset( $options['GROUP BY'] ) ) {
1277 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1279 if ( isset( $options['HAVING'] ) ) {
1280 $preLimitTail .= " HAVING {$options['HAVING']}";
1282 if ( isset( $options['ORDER BY'] ) ) {
1283 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1286 if ( isset( $noKeyOptions['DISTINCT'] )
1287 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1289 $startOpts .= 'DISTINCT';
1292 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1296 * Returns link to IBM DB2 free download
1297 * @return String: wikitext of a link to the server software's web site
1299 public static function getSoftwareLink() {
1300 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1304 * Get search engine class. All subclasses of this
1305 * need to implement this if they wish to use searching.
1309 public function getSearchEngine() {
1310 return 'SearchIBM_DB2';
1314 * Did the last database access fail because of deadlock?
1317 public function wasDeadlock() {
1319 $err = $this->lastErrno();
1321 // This is literal port of the MySQL logic and may be wrong for DB2
1322 case '40001': // sql0911n, Deadlock or timeout, rollback
1323 case '57011': // sql0904n, Resource unavailable, no rollback
1324 case '57033': // sql0913n, Deadlock or timeout, no rollback
1325 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1332 * Ping the server and try to reconnect if it there is no connection
1333 * The connection may be closed and reopened while this happens
1334 * @return Boolean: whether the connection exists
1336 public function ping() {
1337 // db2_ping() doesn't exist
1340 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1341 $this->mPassword
, $this->mServer
, $this->mPort
);
1345 ######################################
1346 # Unimplemented and not applicable
1347 ######################################
1352 public function getStatus( $which = '%' ) {
1353 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1358 * @return string $sql
1360 public function limitResultForUpdate( $sql, $num ) {
1361 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1366 * Only useful with fake prepare like in base Database class
1369 public function fillPreparedArg( $matches ) {
1370 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1374 ######################################
1376 ######################################
1379 * Returns information about an index
1380 * If errors are explicitly ignored, returns NULL on failure
1381 * @param $table String: table name
1382 * @param $index String: index name
1383 * @param $fname String: function name for logging and profiling
1384 * @return Object query row in object form
1386 public function indexInfo( $table, $index,
1387 $fname = 'DatabaseIbm_db2::indexExists' )
1389 $table = $this->tableName( $table );
1391 SELECT name as indexname
1392 FROM sysibm.sysindexes si
1393 WHERE si.name='$index' AND si.tbname='$table'
1394 AND sc.tbcreator='$this->mSchema'
1396 $res = $this->query( $sql, $fname );
1400 $row = $this->fetchObject( $res );
1401 if ( $row != null ) {
1409 * Returns an information object on a table column
1410 * @param $table String: table name
1411 * @param $field String: column name
1412 * @return IBM_DB2Field
1414 public function fieldInfo( $table, $field ) {
1415 return IBM_DB2Field
::fromText( $this, $table, $field );
1419 * db2_field_type() wrapper
1420 * @param $res Object: result of executed statement
1421 * @param $index Mixed: number or name of the column
1422 * @return String column type
1424 public function fieldType( $res, $index ) {
1425 if ( $res instanceof ResultWrapper
) {
1426 $res = $res->result
;
1428 return db2_field_type( $res, $index );
1432 * Verifies that an index was created as unique
1433 * @param $table String: table name
1434 * @param $index String: index name
1435 * @param $fname function name for profiling
1438 public function indexUnique ( $table, $index,
1439 $fname = 'DatabaseIbm_db2::indexUnique' )
1441 $table = $this->tableName( $table );
1443 SELECT si.name as indexname
1444 FROM sysibm.sysindexes si
1445 WHERE si.name='$index' AND si.tbname='$table'
1446 AND sc.tbcreator='$this->mSchema'
1447 AND si.uniquerule IN ( 'U', 'P' )
1449 $res = $this->query( $sql, $fname );
1453 if ( $this->fetchObject( $res ) ) {
1461 * Returns the size of a text field, or -1 for "unlimited"
1462 * @param $table String: table name
1463 * @param $field String: column name
1464 * @return Integer: length or -1 for unlimited
1466 public function textFieldSize( $table, $field ) {
1467 $table = $this->tableName( $table );
1469 SELECT length as size
1470 FROM sysibm.syscolumns sc
1471 WHERE sc.name='$field' AND sc.tbname='$table'
1472 AND sc.tbcreator='$this->mSchema'
1474 $res = $this->query( $sql );
1475 $row = $this->fetchObject( $res );
1481 * Description is left as an exercise for the reader
1482 * @param $b Mixed: data to be encoded
1483 * @return IBM_DB2Blob
1485 public function encodeBlob( $b ) {
1486 return new IBM_DB2Blob( $b );
1490 * Description is left as an exercise for the reader
1491 * @param $b IBM_DB2Blob: data to be decoded
1494 public function decodeBlob( $b ) {
1499 * Convert into a list of string being concatenated
1500 * @param $stringList Array: strings that need to be joined together
1502 * @return String: joined by the concatenation operator
1504 public function buildConcat( $stringList ) {
1505 // || is equivalent to CONCAT
1506 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1507 return implode( ' || ', $stringList );
1511 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1512 * @param $column String: name of timestamp column
1513 * @return String: SQL code
1515 public function extractUnixEpoch( $column ) {
1517 // see SpecialAncientpages
1520 ######################################
1521 # Prepared statements
1522 ######################################
1525 * Intended to be compatible with the PEAR::DB wrapper functions.
1526 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1528 * ? = scalar value, quoted as necessary
1529 * ! = raw SQL bit (a function for instance)
1530 * & = filename; reads the file and inserts as a blob
1531 * (we don't use this though...)
1532 * @param $sql String: SQL statement with appropriate markers
1533 * @param $func String: Name of the function, for profiling
1534 * @return resource a prepared DB2 SQL statement
1536 public function prepare( $sql, $func = 'DB2::prepare' ) {
1537 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1542 * Frees resources associated with a prepared statement
1543 * @return Boolean success or failure
1545 public function freePrepared( $prepared ) {
1546 return db2_free_stmt( $prepared );
1550 * Execute a prepared query with the various arguments
1551 * @param $prepared String: the prepared sql
1552 * @param $args Mixed: either an array here, or put scalars as varargs
1553 * @return Resource: results object
1555 public function execute( $prepared, $args = null ) {
1556 if( !is_array( $args ) ) {
1558 $args = func_get_args();
1559 array_shift( $args );
1561 $res = db2_execute( $prepared, $args );
1563 $this->installPrint( db2_stmt_errormsg() );
1569 * Prepare & execute an SQL statement, quoting and inserting arguments
1570 * in the appropriate places.
1571 * @param $query String
1574 public function safeQuery( $query, $args = null ) {
1575 // copied verbatim from Database.php
1576 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1577 if( !is_array( $args ) ) {
1579 $args = func_get_args();
1580 array_shift( $args );
1582 $retval = $this->execute( $prepared, $args );
1583 $this->freePrepared( $prepared );
1588 * For faking prepared SQL statements on DBs that don't support
1590 * @param $preparedQuery String: a 'preparable' SQL statement
1591 * @param $args Array of arguments to fill it with
1592 * @return String: executable statement
1594 public function fillPrepared( $preparedQuery, $args ) {
1596 $this->preparedArgs
=& $args;
1598 foreach ( $args as $i => $arg ) {
1599 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1602 return $preparedQuery;
1606 * Switches module between regular and install modes
1608 public function setMode( $mode ) {
1609 $old = $this->mMode
;
1610 $this->mMode
= $mode;
1615 * Bitwise negation of a column or value in SQL
1616 * Same as (~field) in C
1617 * @param $field String
1620 function bitNot( $field ) {
1621 // expecting bit-fields smaller than 4bytes
1622 return "BITNOT( $field )";
1626 * Bitwise AND of two columns or values in SQL
1627 * Same as (fieldLeft & fieldRight) in C
1628 * @param $fieldLeft String
1629 * @param $fieldRight String
1632 function bitAnd( $fieldLeft, $fieldRight ) {
1633 return "BITAND( $fieldLeft, $fieldRight )";
1637 * Bitwise OR of two columns or values in SQL
1638 * Same as (fieldLeft | fieldRight) in C
1639 * @param $fieldLeft String
1640 * @param $fieldRight String
1643 function bitOr( $fieldLeft, $fieldRight ) {
1644 return "BITOR( $fieldLeft, $fieldRight )";
1648 class IBM_DB2Helper
{
1649 public static function makeArray( $maybeArray ) {
1650 if ( !is_array( $maybeArray ) ) {
1651 return array( $maybeArray );