60a419055bef707b661e2534945d488ef0dbbe4f
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
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 nullable() { 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 $mOut, $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
= 'mediawiki';
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
;
248 ######################################
250 ######################################
255 * @param $server String: hostname of database server
256 * @param $user String: username
257 * @param $password String: password
258 * @param $dbName String: database name on the server
259 * @param $flags Integer: database behaviour flags (optional, unused)
260 * @param $schema String
262 public function DatabaseIbm_db2( $server = false, $user = false,
264 $dbName = false, $flags = 0,
265 $schema = self
::USE_GLOBAL
)
268 global $wgOut, $wgDBmwschema;
269 # Can't get a reference if it hasn't been set yet
270 if ( !isset( $wgOut ) ) {
273 $this->mOut
=& $wgOut;
274 $this->mFlags
= DBO_TRX |
$flags;
276 if ( $schema == self
::USE_GLOBAL
) {
277 $this->mSchema
= $wgDBmwschema;
279 $this->mSchema
= $schema;
282 // configure the connection and statement objects
283 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
284 self
::CONN_OPTION | self
::STMT_OPTION
);
285 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
287 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
290 $this->open( $server, $user, $password, $dbName );
294 * Enables options only if the ibm_db2 extension version supports them
295 * @param $name String: name of the option in the options array
296 * @param $const String: name of the constant holding the right option value
297 * @param $type Integer: whether this is a Connection or Statement otion
299 private function setDB2Option( $name, $const, $type ) {
300 if ( defined( $const ) ) {
301 if ( $type & self
::CONN_OPTION
) {
302 $this->mConnOptions
[$name] = constant( $const );
304 if ( $type & self
::STMT_OPTION
) {
305 $this->mStmtOptions
[$name] = constant( $const );
309 "$const is not defined. ibm_db2 version is likely too low." );
314 * Outputs debug information in the appropriate place
315 * @param $string String: the relevant debug message
317 private function installPrint( $string ) {
318 wfDebug( "$string\n" );
319 if ( $this->mMode
== self
::INSTALL_MODE
) {
320 print "<li><pre>$string</pre></li>";
326 * Opens a database connection and returns it
327 * Closes any existing connection
329 * @param $server String: hostname
330 * @param $user String
331 * @param $password String
332 * @param $dbName String: database name
333 * @return a fresh connection
335 public function open( $server, $user, $password, $dbName ) {
336 // Load the port number
338 wfProfileIn( __METHOD__
);
340 // Load IBM DB2 driver if missing
343 // Test for IBM DB2 support, to avoid suppressed fatal error
344 if ( !function_exists( 'db2_connect' ) ) {
346 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
349 $this->installPrint( $error );
350 $this->reportConnectionError( $error );
353 if ( strlen( $user ) < 1 ) {
357 // Close existing connection
360 $this->mServer
= $server;
361 $this->mPort
= $port = $wgDBport;
362 $this->mUser
= $user;
363 $this->mPassword
= $password;
364 $this->mDBname
= $dbName;
366 $this->openUncataloged( $dbName, $user, $password, $server, $port );
368 // Apply connection config
369 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
370 // Some MediaWiki code is still transaction-less (?).
371 // The strategy is to keep AutoCommit on for that code
372 // but switch it off whenever a transaction is begun.
373 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
375 if ( !$this->mConn
) {
376 $this->installPrint( "DB connection error\n" );
378 "Server: $server, Database: $dbName, User: $user, Password: "
379 . substr( $password, 0, 3 ) . "...\n" );
380 $this->installPrint( $this->lastError() . "\n" );
384 $this->mOpened
= true;
385 $this->applySchema();
387 wfProfileOut( __METHOD__
);
392 * Opens a cataloged database connection, sets mConn
394 protected function openCataloged( $dbName, $user, $password ) {
395 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
399 * Opens an uncataloged database connection, sets mConn
401 protected function openUncataloged( $dbName, $user, $password, $server, $port )
403 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
404 $str .= "DATABASE=$dbName;";
405 $str .= "HOSTNAME=$server;";
406 // port was formerly validated to not be 0
407 $str .= "PORT=$port;";
408 $str .= "PROTOCOL=TCPIP;";
409 $str .= "UID=$user;";
410 $str .= "PWD=$password;";
412 @$this->mConn
= db2_pconnect( $str, $user, $password );
416 * Closes a database connection, if it is open
417 * Returns success, true if already closed
419 public function close() {
420 $this->mOpened
= false;
421 if ( $this->mConn
) {
422 if ( $this->trxLevel() > 0 ) {
425 return db2_close( $this->mConn
);
432 * Returns a fresh instance of this class
434 * @param $server String: hostname of database server
435 * @param $user String: username
436 * @param $password String
437 * @param $dbName String: database name on the server
438 * @param $flags Integer: database behaviour flags (optional, unused)
439 * @return DatabaseIbm_db2 object
441 static function newFromParams( $server, $user, $password, $dbName,
444 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
449 * Retrieves the most current database error
450 * Forces a database rollback
452 public function lastError() {
453 $connerr = db2_conn_errormsg();
458 $stmterr = db2_stmt_errormsg();
468 * Get the last error number
469 * Return 0 if no error
472 public function lastErrno() {
473 $connerr = db2_conn_error();
477 $stmterr = db2_stmt_error();
485 * Is a database connection open?
488 public function isOpen() { return $this->mOpened
; }
491 * The DBMS-dependent part of query()
492 * @param $sql String: SQL query.
493 * @return object Result object for fetch functions or false on failure
497 public function doQuery( $sql ) {
498 $this->applySchema();
500 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
501 if( $ret == false ) {
502 $error = db2_stmt_errormsg();
503 $this->installPrint( "<pre>$sql</pre>" );
504 $this->installPrint( $error );
505 throw new DBUnexpectedError( $this, 'SQL error: '
506 . htmlspecialchars( $error ) );
508 $this->mLastResult
= $ret;
509 $this->mAffectedRows
= null; // Not calculated until asked for
514 * @return string Version information from the database
516 public function getServerVersion() {
517 $info = db2_server_info( $this->mConn
);
518 return $info->DBMS_VER
;
522 * Queries whether a given table exists
525 public function tableExists( $table ) {
526 $schema = $this->mSchema
;
528 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
529 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
531 $res = $this->query( $sql );
536 // If the table exists, there should be one of it
537 @$row = $this->fetchRow( $res );
539 if ( $count == '1' ||
$count == 1 ) {
547 * Fetch the next row from the given result object, in object form.
548 * Fields can be retrieved with $row->fieldname, with fields acting like
551 * @param $res SQL result object as returned from Database::query(), etc.
552 * @return DB2 row object
553 * @throws DBUnexpectedError Thrown if the database returns an error
555 public function fetchObject( $res ) {
556 if ( $res instanceof ResultWrapper
) {
559 @$row = db2_fetch_object( $res );
560 if( $this->lastErrno() ) {
561 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
562 . htmlspecialchars( $this->lastError() ) );
568 * Fetch the next row from the given result object, in associative array
569 * form. Fields are retrieved with $row['fieldname'].
571 * @param $res SQL result object as returned from Database::query(), etc.
572 * @return DB2 row object
573 * @throws DBUnexpectedError Thrown if the database returns an error
575 public function fetchRow( $res ) {
576 if ( $res instanceof ResultWrapper
) {
579 @$row = db2_fetch_array( $res );
580 if ( $this->lastErrno() ) {
581 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
582 . htmlspecialchars( $this->lastError() ) );
588 * Create tables, stored procedures, and so on
590 public function setup_database() {
592 // TODO: switch to root login if available
594 // Switch into the correct namespace
595 $this->applySchema();
598 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
599 if ( $res !== true ) {
600 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
604 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
605 if ( $res !== true ) {
606 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
608 print '<li>Foreign keys done</li>';
611 // TODO: populate interwiki links
613 if ( $this->lastError() ) {
615 'Errors encountered during table creation -- rolled back' );
616 $this->installPrint( 'Please install again' );
621 } catch ( MWException
$mwe ) {
622 print "<br><pre>$mwe</pre><br>";
628 * Doesn't escape numbers
630 * @param $s String: string to escape
631 * @return escaped string
633 public function addQuotes( $s ) {
634 //$this->installPrint( "DB2::addQuotes( $s )\n" );
635 if ( is_null( $s ) ) {
637 } elseif ( $s instanceof Blob
) {
638 return "'" . $s->fetch( $s ) . "'";
639 } elseif ( $s instanceof IBM_DB2Blob
) {
640 return "'" . $this->decodeBlob( $s ) . "'";
642 $s = $this->strencode( $s );
643 if ( is_numeric( $s ) ) {
651 * Verifies that a DB2 column/field type is numeric
653 * @param $type String: DB2 column type
654 * @return Boolean: true if numeric
656 public function is_numeric_type( $type ) {
657 switch ( strtoupper( $type ) ) {
672 * Alias for addQuotes()
673 * @param $s String: string to escape
674 * @return escaped string
676 public function strencode( $s ) {
677 // Bloody useless function
678 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
679 // But also necessary
680 $s = db2_escape_string( $s );
681 // Wide characters are evil -- some of them look like '
682 $s = utf8_encode( $s );
684 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
685 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
686 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
691 * Switch into the database schema
693 protected function applySchema() {
694 if ( !( $this->mSchemaSet
) ) {
695 $this->mSchemaSet
= true;
697 $this->doQuery( "SET SCHEMA = $this->mSchema" );
703 * Start a transaction (mandatory)
705 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
706 // BEGIN is implicit for DB2
707 // However, it requires that AutoCommit be off.
709 // Some MediaWiki code is still transaction-less (?).
710 // The strategy is to keep AutoCommit on for that code
711 // but switch it off whenever a transaction is begun.
712 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
714 $this->mTrxLevel
= 1;
719 * Must have a preceding begin()
721 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
722 db2_commit( $this->mConn
);
724 // Some MediaWiki code is still transaction-less (?).
725 // The strategy is to keep AutoCommit on for that code
726 // but switch it off whenever a transaction is begun.
727 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
729 $this->mTrxLevel
= 0;
733 * Cancel a transaction
735 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
736 db2_rollback( $this->mConn
);
737 // turn auto-commit back on
738 // not sure if this is appropriate
739 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
740 $this->mTrxLevel
= 0;
744 * Makes an encoded list of strings from an array
746 * LIST_COMMA - comma separated, no field names
747 * LIST_AND - ANDed WHERE clause (without the WHERE)
748 * LIST_OR - ORed WHERE clause (without the WHERE)
749 * LIST_SET - comma separated with field names, like a SET clause
750 * LIST_NAMES - comma separated field names
751 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
753 function makeList( $a, $mode = LIST_COMMA
) {
754 if ( !is_array( $a ) ) {
755 throw new DBUnexpectedError( $this,
756 'DatabaseBase::makeList called with incorrect parameters' );
759 // if this is for a prepared UPDATE statement
760 // (this should be promoted to the parent class
761 // once other databases use prepared statements)
762 if ( $mode == LIST_SET_PREPARED
) {
765 foreach ( $a as $field => $value ) {
767 $list .= ", $field = ?";
769 $list .= "$field = ?";
778 // otherwise, call the usual function
779 return parent
::makeList( $a, $mode );
783 * Construct a LIMIT query with optional offset
784 * This is used for query pages
786 * @param $sql string SQL query we will append the limit too
787 * @param $limit integer the SQL limit
788 * @param $offset integer the SQL offset (default false)
790 public function limitResult( $sql, $limit, $offset=false ) {
791 if( !is_numeric( $limit ) ) {
792 throw new DBUnexpectedError( $this,
793 "Invalid non-numeric limit passed to limitResult()\n" );
796 if ( stripos( $sql, 'where' ) === false ) {
797 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
799 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
802 return "$sql FETCH FIRST $limit ROWS ONLY ";
806 * Handle reserved keyword replacement in table names
808 * @param $name Object
811 public function tableName( $name ) {
812 // we want maximum compatibility with MySQL schema
817 * Generates a timestamp in an insertable format
819 * @param $ts timestamp
820 * @return String: timestamp value
822 public function timestamp( $ts = 0 ) {
823 // TS_MW cannot be easily distinguished from an integer
824 return wfTimestamp( TS_DB2
, $ts );
828 * Return the next in a sequence, save the value for retrieval via insertId()
829 * @param $seqName String: name of a defined sequence in the database
830 * @return next value in that sequence
832 public function nextSequenceValue( $seqName ) {
833 // Not using sequences in the primary schema to allow for easier migration
835 // Emulating MySQL behaviour of using NULL to signal that sequences
838 $safeseq = preg_replace( "/'/", "''", $seqName );
839 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
840 $row = $this->fetchRow( $res );
841 $this->mInsertId = $row[0];
842 return $this->mInsertId;
848 * This must be called after nextSequenceVal
849 * @return Last sequence value used as a primary key
851 public function insertId() {
852 return $this->mInsertId
;
856 * Updates the mInsertId property with the value of the last insert
857 * into a generated column
859 * @param $table String: sanitized table name
860 * @param $primaryKey Mixed: string name of the primary key
861 * @param $stmt Resource: prepared statement resource
862 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
864 private function calcInsertId( $table, $primaryKey, $stmt ) {
866 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
871 * INSERT wrapper, inserts an array into a table
873 * $args may be a single associative array, or an array of arrays
874 * with numeric keys, for multi-row insert
876 * @param $table String: Name of the table to insert to.
877 * @param $args Array: Items to insert into the table.
878 * @param $fname String: Name of the function, for profiling
879 * @param $options String or Array. Valid options: IGNORE
881 * @return bool Success of insert operation. IGNORE always returns true.
883 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
886 if ( !count( $args ) ) {
889 // get database-specific table name (not used)
890 $table = $this->tableName( $table );
891 // format options as an array
892 $options = IBM_DB2Helper
::makeArray( $options );
893 // format args as an array of arrays
894 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
895 $args = array( $args );
898 // prevent insertion of NULL into primary key columns
899 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
900 // if there's only one primary key
901 // we'll be able to read its value after insertion
903 if ( count( $primaryKeys ) == 1 ) {
904 $primaryKey = $primaryKeys[0];
908 $keys = array_keys( $args[0] );
909 $key_count = count( $keys );
911 // If IGNORE is set, we use savepoints to emulate mysql's behavior
912 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
916 // If we are not in a transaction, we need to be for savepoint trickery
917 if ( !$this->mTrxLevel
) {
921 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
922 if ( $key_count == 1 ) {
925 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
927 //$this->installPrint( "Preparing the following SQL:" );
928 //$this->installPrint( "$sql" );
929 //$this->installPrint( print_r( $args, true ));
930 $stmt = $this->prepare( $sql );
932 // start a transaction/enter transaction mode
937 foreach ( $args as $row ) {
938 //$this->installPrint( "Inserting " . print_r( $row, true ));
939 // insert each row into the database
940 $res = $res & $this->execute( $stmt, $row );
942 $this->installPrint( 'Last error:' );
943 $this->installPrint( $this->lastError() );
945 // get the last inserted value into a generated column
946 $this->calcInsertId( $table, $primaryKey, $stmt );
949 $olde = error_reporting( 0 );
950 // For future use, we may want to track the number of actual inserts
951 // Right now, insert (all writes) simply return true/false
952 $numrowsinserted = 0;
954 // always return true
957 foreach ( $args as $row ) {
958 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
959 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
961 $this->execute( $stmt, $row );
964 $this->installPrint( 'Last error:' );
965 $this->installPrint( $this->lastError() );
967 // get the last inserted value into a generated column
968 $this->calcInsertId( $table, $primaryKey, $stmt );
970 $errNum = $this->lastErrno();
972 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
973 $this->mStmtOptions
);
975 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
976 $this->mStmtOptions
);
981 $olde = error_reporting( $olde );
982 // Set the affected row count for the whole operation
983 $this->mAffectedRows
= $numrowsinserted;
987 $this->freePrepared( $stmt );
993 * Given a table name and a hash of columns with values
994 * Removes primary key columns from the hash where the value is NULL
996 * @param $table String: name of the table
997 * @param $args Array of hashes of column names with values
998 * @return Array: tuple( filtered array of columns, array of primary keys )
1000 private function removeNullPrimaryKeys( $table, $args ) {
1001 $schema = $this->mSchema
;
1002 // find out the primary keys
1003 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
1004 strtoupper( $table )
1008 $row = $this->fetchObject( $keyres );
1010 $row = $this->fetchObject( $keyres )
1013 $keys[] = strtolower( $row->column_name
);
1015 // remove primary keys
1016 foreach ( $args as $ai => $row ) {
1017 foreach ( $keys as $key ) {
1018 if ( $row[$key] == null ) {
1019 unset( $row[$key] );
1024 // return modified hash
1025 return array( $args, $keys );
1029 * UPDATE wrapper, takes a condition array and a SET array
1031 * @param $table String: The table to UPDATE
1032 * @param $values An array of values to SET
1033 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1034 * @param $fname String: The Class::Function calling this function
1036 * @param $options An array of UPDATE options, can be one or
1037 * more of IGNORE, LOW_PRIORITY
1040 public function update( $table, $values, $conds, $fname = 'Database::update',
1041 $options = array() )
1043 $table = $this->tableName( $table );
1044 $opts = $this->makeUpdateOptions( $options );
1045 $sql = "UPDATE $opts $table SET "
1046 . $this->makeList( $values, LIST_SET_PREPARED
);
1047 if ( $conds != '*' ) {
1048 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1050 $stmt = $this->prepare( $sql );
1051 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1052 // assuming for now that an array with string keys will work
1053 // if not, convert to simple array first
1054 $result = $this->execute( $stmt, $values );
1055 $this->freePrepared( $stmt );
1061 * DELETE query wrapper
1063 * Use $conds == "*" to delete all rows
1065 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1067 throw new DBUnexpectedError( $this,
1068 'Database::delete() called with no conditions' );
1070 $table = $this->tableName( $table );
1071 $sql = "DELETE FROM $table";
1072 if ( $conds != '*' ) {
1073 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1075 $result = $this->query( $sql, $fname );
1081 * Returns the number of rows affected by the last query or 0
1082 * @return Integer: the number of rows affected by the last query
1084 public function affectedRows() {
1085 if ( !is_null( $this->mAffectedRows
) ) {
1086 // Forced result for simulated queries
1087 return $this->mAffectedRows
;
1089 if( empty( $this->mLastResult
) ) {
1092 return db2_num_rows( $this->mLastResult
);
1096 * Simulates REPLACE with a DELETE followed by INSERT
1097 * @param $table Object
1098 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1099 * @param $rows Array: rows to insert
1100 * @param $fname String: name of the function for profiling
1103 function replace( $table, $uniqueIndexes, $rows,
1104 $fname = 'DatabaseIbm_db2::replace' )
1106 $table = $this->tableName( $table );
1108 if ( count( $rows )==0 ) {
1113 if ( !is_array( reset( $rows ) ) ) {
1114 $rows = array( $rows );
1117 foreach( $rows as $row ) {
1118 # Delete rows which collide
1119 if ( $uniqueIndexes ) {
1120 $sql = "DELETE FROM $table WHERE ";
1122 foreach ( $uniqueIndexes as $index ) {
1129 if ( is_array( $index ) ) {
1131 foreach ( $index as $col ) {
1137 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1140 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1144 $this->query( $sql, $fname );
1147 # Now insert the row
1148 $sql = "INSERT INTO $table ( "
1149 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1150 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1151 $this->query( $sql, $fname );
1156 * Returns the number of rows in the result set
1157 * Has to be called right after the corresponding select query
1158 * @param $res Object result set
1159 * @return Integer: number of rows
1161 public function numRows( $res ) {
1162 if ( $res instanceof ResultWrapper
) {
1163 $res = $res->result
;
1165 if ( $this->mNumRows
) {
1166 return $this->mNumRows
;
1173 * Moves the row pointer of the result set
1174 * @param $res Object: result set
1175 * @param $row Integer: row number
1176 * @return success or failure
1178 public function dataSeek( $res, $row ) {
1179 if ( $res instanceof ResultWrapper
) {
1180 $res = $res->result
;
1182 return db2_fetch_row( $res, $row );
1186 # Fix notices in Block.php
1190 * Frees memory associated with a statement resource
1191 * @param $res Object: statement resource to free
1192 * @return Boolean success or failure
1194 public function freeResult( $res ) {
1195 if ( $res instanceof ResultWrapper
) {
1196 $res = $res->result
;
1198 if ( !@db2_free_result
( $res ) ) {
1199 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1204 * Returns the number of columns in a resource
1205 * @param $res Object: statement resource
1206 * @return Number of fields/columns in resource
1208 public function numFields( $res ) {
1209 if ( $res instanceof ResultWrapper
) {
1210 $res = $res->result
;
1212 return db2_num_fields( $res );
1216 * Returns the nth column name
1217 * @param $res Object: statement resource
1218 * @param $n Integer: Index of field or column
1219 * @return String name of nth column
1221 public function fieldName( $res, $n ) {
1222 if ( $res instanceof ResultWrapper
) {
1223 $res = $res->result
;
1225 return db2_field_name( $res, $n );
1231 * @param $table Array or string, table name(s) (prefix auto-added)
1232 * @param $vars Array or string, field name(s) to be retrieved
1233 * @param $conds Array or string, condition(s) for WHERE
1234 * @param $fname String: calling function name (use __METHOD__)
1235 * for logs/profiling
1236 * @param $options Associative array of options
1237 * (e.g. array('GROUP BY' => 'page_title')),
1238 * see Database::makeSelectOptions code for list of
1240 * @param $join_conds Associative array of table join conditions (optional)
1241 * (e.g. array( 'page' => array('LEFT JOIN',
1242 * 'page_latest=rev_id') )
1243 * @return Mixed: database result resource for fetch functions or false
1246 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1248 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1251 // We must adjust for offset
1252 if ( isset( $options['LIMIT'] ) ) {
1253 if ( isset ( $options['OFFSET'] ) ) {
1254 $limit = $options['LIMIT'];
1255 $offset = $options['OFFSET'];
1259 // DB2 does not have a proper num_rows() function yet, so we must emulate
1260 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1264 // we want the count
1265 $vars2 = array( 'count( * ) as num_rows' );
1266 // respecting just the limit option
1267 $options2 = array();
1268 if ( isset( $options['LIMIT'] ) ) {
1269 $options2['LIMIT'] = $options['LIMIT'];
1271 // but don't try to emulate for GROUP BY
1272 if ( isset( $options['GROUP BY'] ) ) {
1276 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1278 $obj = $this->fetchObject( $res2 );
1279 $this->mNumRows
= $obj->num_rows
;
1285 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1286 * Has limited support for per-column options (colnum => 'DISTINCT')
1290 * @param $options Associative array of options to be turned into
1291 * an SQL query, valid keys are listed in the function.
1294 function makeSelectOptions( $options ) {
1295 $preLimitTail = $postLimitTail = '';
1298 $noKeyOptions = array();
1299 foreach ( $options as $key => $option ) {
1300 if ( is_numeric( $key ) ) {
1301 $noKeyOptions[$option] = true;
1305 if ( isset( $options['GROUP BY'] ) ) {
1306 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1308 if ( isset( $options['HAVING'] ) ) {
1309 $preLimitTail .= " HAVING {$options['HAVING']}";
1311 if ( isset( $options['ORDER BY'] ) ) {
1312 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1315 if ( isset( $noKeyOptions['DISTINCT'] )
1316 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1318 $startOpts .= 'DISTINCT';
1321 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1325 * Returns link to IBM DB2 free download
1326 * @return String: wikitext of a link to the server software's web site
1328 public static function getSoftwareLink() {
1329 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1333 * Get search engine class. All subclasses of this
1334 * need to implement this if they wish to use searching.
1338 public function getSearchEngine() {
1339 return 'SearchIBM_DB2';
1343 * Did the last database access fail because of deadlock?
1346 public function wasDeadlock() {
1348 $err = $this->lastErrno();
1350 // This is literal port of the MySQL logic and may be wrong for DB2
1351 case '40001': // sql0911n, Deadlock or timeout, rollback
1352 case '57011': // sql0904n, Resource unavailable, no rollback
1353 case '57033': // sql0913n, Deadlock or timeout, no rollback
1354 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1361 * Ping the server and try to reconnect if it there is no connection
1362 * The connection may be closed and reopened while this happens
1363 * @return Boolean: whether the connection exists
1365 public function ping() {
1366 // db2_ping() doesn't exist
1369 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1370 $this->mPassword
, $this->mServer
, $this->mPort
);
1374 ######################################
1375 # Unimplemented and not applicable
1376 ######################################
1381 public function getStatus( $which = '%' ) {
1382 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1387 * @return string $sql
1389 public function limitResultForUpdate( $sql, $num ) {
1390 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1395 * Only useful with fake prepare like in base Database class
1398 public function fillPreparedArg( $matches ) {
1399 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1403 ######################################
1405 ######################################
1408 * Returns information about an index
1409 * If errors are explicitly ignored, returns NULL on failure
1410 * @param $table String: table name
1411 * @param $index String: index name
1412 * @param $fname String: function name for logging and profiling
1413 * @return Object query row in object form
1415 public function indexInfo( $table, $index,
1416 $fname = 'DatabaseIbm_db2::indexExists' )
1418 $table = $this->tableName( $table );
1420 SELECT name as indexname
1421 FROM sysibm.sysindexes si
1422 WHERE si.name='$index' AND si.tbname='$table'
1423 AND sc.tbcreator='$this->mSchema'
1425 $res = $this->query( $sql, $fname );
1429 $row = $this->fetchObject( $res );
1430 if ( $row != null ) {
1438 * Returns an information object on a table column
1439 * @param $table String: table name
1440 * @param $field String: column name
1441 * @return IBM_DB2Field
1443 public function fieldInfo( $table, $field ) {
1444 return IBM_DB2Field
::fromText( $this, $table, $field );
1448 * db2_field_type() wrapper
1449 * @param $res Object: result of executed statement
1450 * @param $index Mixed: number or name of the column
1451 * @return String column type
1453 public function fieldType( $res, $index ) {
1454 if ( $res instanceof ResultWrapper
) {
1455 $res = $res->result
;
1457 return db2_field_type( $res, $index );
1461 * Verifies that an index was created as unique
1462 * @param $table String: table name
1463 * @param $index String: index name
1464 * @param $fname function name for profiling
1467 public function indexUnique ( $table, $index,
1468 $fname = 'Database::indexUnique' )
1470 $table = $this->tableName( $table );
1472 SELECT si.name as indexname
1473 FROM sysibm.sysindexes si
1474 WHERE si.name='$index' AND si.tbname='$table'
1475 AND sc.tbcreator='$this->mSchema'
1476 AND si.uniquerule IN ( 'U', 'P' )
1478 $res = $this->query( $sql, $fname );
1482 if ( $this->fetchObject( $res ) ) {
1490 * Returns the size of a text field, or -1 for "unlimited"
1491 * @param $table String: table name
1492 * @param $field String: column name
1493 * @return Integer: length or -1 for unlimited
1495 public function textFieldSize( $table, $field ) {
1496 $table = $this->tableName( $table );
1498 SELECT length as size
1499 FROM sysibm.syscolumns sc
1500 WHERE sc.name='$field' AND sc.tbname='$table'
1501 AND sc.tbcreator='$this->mSchema'
1503 $res = $this->query( $sql );
1504 $row = $this->fetchObject( $res );
1510 * DELETE where the condition is a join
1511 * @param $delTable String: deleting from this table
1512 * @param $joinTable String: using data from this table
1513 * @param $delVar String: variable in deleteable table
1514 * @param $joinVar String: variable in data table
1515 * @param $conds Array: conditionals for join table
1516 * @param $fname String: function name for profiling
1518 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1519 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1522 throw new DBUnexpectedError( $this,
1523 'Database::deleteJoin() called with empty $conds' );
1526 $delTable = $this->tableName( $delTable );
1527 $joinTable = $this->tableName( $joinTable );
1529 DELETE FROM $delTable
1531 SELECT $joinVar FROM $joinTable
1534 if ( $conds != '*' ) {
1535 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1539 $this->query( $sql, $fname );
1543 * Description is left as an exercise for the reader
1544 * @param $b Mixed: data to be encoded
1545 * @return IBM_DB2Blob
1547 public function encodeBlob( $b ) {
1548 return new IBM_DB2Blob( $b );
1552 * Description is left as an exercise for the reader
1553 * @param $b IBM_DB2Blob: data to be decoded
1556 public function decodeBlob( $b ) {
1561 * Convert into a list of string being concatenated
1562 * @param $stringList Array: strings that need to be joined together
1564 * @return String: joined by the concatenation operator
1566 public function buildConcat( $stringList ) {
1567 // || is equivalent to CONCAT
1568 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1569 return implode( ' || ', $stringList );
1573 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1574 * @param $column String: name of timestamp column
1575 * @return String: SQL code
1577 public function extractUnixEpoch( $column ) {
1579 // see SpecialAncientpages
1582 ######################################
1583 # Prepared statements
1584 ######################################
1587 * Intended to be compatible with the PEAR::DB wrapper functions.
1588 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1590 * ? = scalar value, quoted as necessary
1591 * ! = raw SQL bit (a function for instance)
1592 * & = filename; reads the file and inserts as a blob
1593 * (we don't use this though...)
1594 * @param $sql String: SQL statement with appropriate markers
1595 * @param $func String: Name of the function, for profiling
1596 * @return resource a prepared DB2 SQL statement
1598 public function prepare( $sql, $func = 'DB2::prepare' ) {
1599 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1604 * Frees resources associated with a prepared statement
1605 * @return Boolean success or failure
1607 public function freePrepared( $prepared ) {
1608 return db2_free_stmt( $prepared );
1612 * Execute a prepared query with the various arguments
1613 * @param $prepared String: the prepared sql
1614 * @param $args Mixed: either an array here, or put scalars as varargs
1615 * @return Resource: results object
1617 public function execute( $prepared, $args = null ) {
1618 if( !is_array( $args ) ) {
1620 $args = func_get_args();
1621 array_shift( $args );
1623 $res = db2_execute( $prepared, $args );
1625 $this->installPrint( db2_stmt_errormsg() );
1631 * Prepare & execute an SQL statement, quoting and inserting arguments
1632 * in the appropriate places.
1633 * @param $query String
1636 public function safeQuery( $query, $args = null ) {
1637 // copied verbatim from Database.php
1638 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1639 if( !is_array( $args ) ) {
1641 $args = func_get_args();
1642 array_shift( $args );
1644 $retval = $this->execute( $prepared, $args );
1645 $this->freePrepared( $prepared );
1650 * For faking prepared SQL statements on DBs that don't support
1652 * @param $preparedQuery String: a 'preparable' SQL statement
1653 * @param $args Array of arguments to fill it with
1654 * @return String: executable statement
1656 public function fillPrepared( $preparedQuery, $args ) {
1658 $this->preparedArgs
=& $args;
1660 foreach ( $args as $i => $arg ) {
1661 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1664 return $preparedQuery;
1668 * Switches module between regular and install modes
1670 public function setMode( $mode ) {
1671 $old = $this->mMode
;
1672 $this->mMode
= $mode;
1677 * Bitwise negation of a column or value in SQL
1678 * Same as (~field) in C
1679 * @param $field String
1682 function bitNot( $field ) {
1683 // expecting bit-fields smaller than 4bytes
1684 return "BITNOT( $field )";
1688 * Bitwise AND of two columns or values in SQL
1689 * Same as (fieldLeft & fieldRight) in C
1690 * @param $fieldLeft String
1691 * @param $fieldRight String
1694 function bitAnd( $fieldLeft, $fieldRight ) {
1695 return "BITAND( $fieldLeft, $fieldRight )";
1699 * Bitwise OR of two columns or values in SQL
1700 * Same as (fieldLeft | fieldRight) in C
1701 * @param $fieldLeft String
1702 * @param $fieldRight String
1705 function bitOr( $fieldLeft, $fieldRight ) {
1706 return "BITOR( $fieldLeft, $fieldRight )";
1710 class IBM_DB2Helper
{
1711 public static function makeArray( $maybeArray ) {
1712 if ( !is_array( $maybeArray ) ) {
1713 return array( $maybeArray );