a2a2be0b4e87de28d26729599592a5f27643670d
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
= '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 __construct( $server = false, $user = false,
264 $dbName = false, $flags = 0,
265 $schema = self
::USE_GLOBAL
)
267 global $wgDBmwschema;
269 if ( $schema == self
::USE_GLOBAL
) {
270 $this->mSchema
= $wgDBmwschema;
272 $this->mSchema
= $schema;
275 // configure the connection and statement objects
276 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
277 self
::CONN_OPTION | self
::STMT_OPTION
);
278 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
280 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
283 parent
::__construct( $server, $user, $password, $dbName, $flags );
287 * Enables options only if the ibm_db2 extension version supports them
288 * @param $name String: name of the option in the options array
289 * @param $const String: name of the constant holding the right option value
290 * @param $type Integer: whether this is a Connection or Statement otion
292 private function setDB2Option( $name, $const, $type ) {
293 if ( defined( $const ) ) {
294 if ( $type & self
::CONN_OPTION
) {
295 $this->mConnOptions
[$name] = constant( $const );
297 if ( $type & self
::STMT_OPTION
) {
298 $this->mStmtOptions
[$name] = constant( $const );
302 "$const is not defined. ibm_db2 version is likely too low." );
307 * Outputs debug information in the appropriate place
308 * @param $string String: the relevant debug message
310 private function installPrint( $string ) {
311 wfDebug( "$string\n" );
312 if ( $this->mMode
== self
::INSTALL_MODE
) {
313 print "<li><pre>$string</pre></li>";
319 * Opens a database connection and returns it
320 * Closes any existing connection
322 * @param $server String: hostname
323 * @param $user String
324 * @param $password String
325 * @param $dbName String: database name
326 * @return a fresh connection
328 public function open( $server, $user, $password, $dbName ) {
329 // Load the port number
331 wfProfileIn( __METHOD__
);
333 // Load IBM DB2 driver if missing
336 // Test for IBM DB2 support, to avoid suppressed fatal error
337 if ( !function_exists( 'db2_connect' ) ) {
339 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
342 $this->installPrint( $error );
343 $this->reportConnectionError( $error );
346 if ( strlen( $user ) < 1 ) {
350 // Close existing connection
353 $this->mServer
= $server;
354 $this->mPort
= $port = $wgDBport;
355 $this->mUser
= $user;
356 $this->mPassword
= $password;
357 $this->mDBname
= $dbName;
359 $this->openUncataloged( $dbName, $user, $password, $server, $port );
361 // Apply connection config
362 db2_set_option( $this->mConn
, $this->mConnOptions
, 1 );
363 // Some MediaWiki code is still transaction-less (?).
364 // The strategy is to keep AutoCommit on for that code
365 // but switch it off whenever a transaction is begun.
366 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
368 if ( !$this->mConn
) {
369 $this->installPrint( "DB connection error\n" );
371 "Server: $server, Database: $dbName, User: $user, Password: "
372 . substr( $password, 0, 3 ) . "...\n" );
373 $this->installPrint( $this->lastError() . "\n" );
377 $this->mOpened
= true;
378 $this->applySchema();
380 wfProfileOut( __METHOD__
);
385 * Opens a cataloged database connection, sets mConn
387 protected function openCataloged( $dbName, $user, $password ) {
388 @$this->mConn
= db2_pconnect( $dbName, $user, $password );
392 * Opens an uncataloged database connection, sets mConn
394 protected function openUncataloged( $dbName, $user, $password, $server, $port )
396 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
397 $str .= "DATABASE=$dbName;";
398 $str .= "HOSTNAME=$server;";
399 // port was formerly validated to not be 0
400 $str .= "PORT=$port;";
401 $str .= "PROTOCOL=TCPIP;";
402 $str .= "UID=$user;";
403 $str .= "PWD=$password;";
405 @$this->mConn
= db2_pconnect( $str, $user, $password );
409 * Closes a database connection, if it is open
410 * Returns success, true if already closed
412 public function close() {
413 $this->mOpened
= false;
414 if ( $this->mConn
) {
415 if ( $this->trxLevel() > 0 ) {
418 return db2_close( $this->mConn
);
425 * Retrieves the most current database error
426 * Forces a database rollback
428 public function lastError() {
429 $connerr = db2_conn_errormsg();
434 $stmterr = db2_stmt_errormsg();
444 * Get the last error number
445 * Return 0 if no error
448 public function lastErrno() {
449 $connerr = db2_conn_error();
453 $stmterr = db2_stmt_error();
461 * Is a database connection open?
464 public function isOpen() { return $this->mOpened
; }
467 * The DBMS-dependent part of query()
468 * @param $sql String: SQL query.
469 * @return object Result object for fetch functions or false on failure
473 public function doQuery( $sql ) {
474 $this->applySchema();
476 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
477 if( $ret == false ) {
478 $error = db2_stmt_errormsg();
479 $this->installPrint( "<pre>$sql</pre>" );
480 $this->installPrint( $error );
481 throw new DBUnexpectedError( $this, 'SQL error: '
482 . htmlspecialchars( $error ) );
484 $this->mLastResult
= $ret;
485 $this->mAffectedRows
= null; // Not calculated until asked for
490 * @return string Version information from the database
492 public function getServerVersion() {
493 $info = db2_server_info( $this->mConn
);
494 return $info->DBMS_VER
;
498 * Queries whether a given table exists
501 public function tableExists( $table ) {
502 $schema = $this->mSchema
;
504 SELECT
COUNT( * ) FROM SYSIBM
.SYSTABLES ST
505 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
507 $res = $this->query( $sql );
512 // If the table exists, there should be one of it
513 @$row = $this->fetchRow( $res );
515 if ( $count == '1' ||
$count == 1 ) {
523 * Fetch the next row from the given result object, in object form.
524 * Fields can be retrieved with $row->fieldname, with fields acting like
527 * @param $res SQL result object as returned from Database::query(), etc.
528 * @return DB2 row object
529 * @throws DBUnexpectedError Thrown if the database returns an error
531 public function fetchObject( $res ) {
532 if ( $res instanceof ResultWrapper
) {
535 @$row = db2_fetch_object( $res );
536 if( $this->lastErrno() ) {
537 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
538 . htmlspecialchars( $this->lastError() ) );
544 * Fetch the next row from the given result object, in associative array
545 * form. Fields are retrieved with $row['fieldname'].
547 * @param $res SQL result object as returned from Database::query(), etc.
548 * @return DB2 row object
549 * @throws DBUnexpectedError Thrown if the database returns an error
551 public function fetchRow( $res ) {
552 if ( $res instanceof ResultWrapper
) {
555 @$row = db2_fetch_array( $res );
556 if ( $this->lastErrno() ) {
557 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
558 . htmlspecialchars( $this->lastError() ) );
564 * Create tables, stored procedures, and so on
566 public function setup_database() {
568 // TODO: switch to root login if available
570 // Switch into the correct namespace
571 $this->applySchema();
574 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
575 if ( $res !== true ) {
576 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
580 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
581 if ( $res !== true ) {
582 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
584 print '<li>Foreign keys done</li>';
587 // TODO: populate interwiki links
589 if ( $this->lastError() ) {
591 'Errors encountered during table creation -- rolled back' );
592 $this->installPrint( 'Please install again' );
597 } catch ( MWException
$mwe ) {
598 print "<br><pre>$mwe</pre><br>";
604 * Doesn't escape numbers
606 * @param $s String: string to escape
607 * @return escaped string
609 public function addQuotes( $s ) {
610 //$this->installPrint( "DB2::addQuotes( $s )\n" );
611 if ( is_null( $s ) ) {
613 } elseif ( $s instanceof Blob
) {
614 return "'" . $s->fetch( $s ) . "'";
615 } elseif ( $s instanceof IBM_DB2Blob
) {
616 return "'" . $this->decodeBlob( $s ) . "'";
618 $s = $this->strencode( $s );
619 if ( is_numeric( $s ) ) {
627 * Verifies that a DB2 column/field type is numeric
629 * @param $type String: DB2 column type
630 * @return Boolean: true if numeric
632 public function is_numeric_type( $type ) {
633 switch ( strtoupper( $type ) ) {
648 * Alias for addQuotes()
649 * @param $s String: string to escape
650 * @return escaped string
652 public function strencode( $s ) {
653 // Bloody useless function
654 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
655 // But also necessary
656 $s = db2_escape_string( $s );
657 // Wide characters are evil -- some of them look like '
658 $s = utf8_encode( $s );
660 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
661 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
662 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
667 * Switch into the database schema
669 protected function applySchema() {
670 if ( !( $this->mSchemaSet
) ) {
671 $this->mSchemaSet
= true;
673 $this->doQuery( "SET SCHEMA = $this->mSchema" );
679 * Start a transaction (mandatory)
681 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
682 // BEGIN is implicit for DB2
683 // However, it requires that AutoCommit be off.
685 // Some MediaWiki code is still transaction-less (?).
686 // The strategy is to keep AutoCommit on for that code
687 // but switch it off whenever a transaction is begun.
688 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
690 $this->mTrxLevel
= 1;
695 * Must have a preceding begin()
697 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
698 db2_commit( $this->mConn
);
700 // Some MediaWiki code is still transaction-less (?).
701 // The strategy is to keep AutoCommit on for that code
702 // but switch it off whenever a transaction is begun.
703 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
705 $this->mTrxLevel
= 0;
709 * Cancel a transaction
711 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
712 db2_rollback( $this->mConn
);
713 // turn auto-commit back on
714 // not sure if this is appropriate
715 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
716 $this->mTrxLevel
= 0;
720 * Makes an encoded list of strings from an array
722 * LIST_COMMA - comma separated, no field names
723 * LIST_AND - ANDed WHERE clause (without the WHERE)
724 * LIST_OR - ORed WHERE clause (without the WHERE)
725 * LIST_SET - comma separated with field names, like a SET clause
726 * LIST_NAMES - comma separated field names
727 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
729 function makeList( $a, $mode = LIST_COMMA
) {
730 if ( !is_array( $a ) ) {
731 throw new DBUnexpectedError( $this,
732 'DatabaseIbm_db2::makeList called with incorrect parameters' );
735 // if this is for a prepared UPDATE statement
736 // (this should be promoted to the parent class
737 // once other databases use prepared statements)
738 if ( $mode == LIST_SET_PREPARED
) {
741 foreach ( $a as $field => $value ) {
743 $list .= ", $field = ?";
745 $list .= "$field = ?";
754 // otherwise, call the usual function
755 return parent
::makeList( $a, $mode );
759 * Construct a LIMIT query with optional offset
760 * This is used for query pages
762 * @param $sql string SQL query we will append the limit too
763 * @param $limit integer the SQL limit
764 * @param $offset integer the SQL offset (default false)
766 public function limitResult( $sql, $limit, $offset=false ) {
767 if( !is_numeric( $limit ) ) {
768 throw new DBUnexpectedError( $this,
769 "Invalid non-numeric limit passed to limitResult()\n" );
772 if ( stripos( $sql, 'where' ) === false ) {
773 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
775 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
778 return "$sql FETCH FIRST $limit ROWS ONLY ";
782 * Handle reserved keyword replacement in table names
784 * @param $name Object
787 public function tableName( $name ) {
788 // we want maximum compatibility with MySQL schema
793 * Generates a timestamp in an insertable format
795 * @param $ts timestamp
796 * @return String: timestamp value
798 public function timestamp( $ts = 0 ) {
799 // TS_MW cannot be easily distinguished from an integer
800 return wfTimestamp( TS_DB2
, $ts );
804 * Return the next in a sequence, save the value for retrieval via insertId()
805 * @param $seqName String: name of a defined sequence in the database
806 * @return next value in that sequence
808 public function nextSequenceValue( $seqName ) {
809 // Not using sequences in the primary schema to allow for easier migration
811 // Emulating MySQL behaviour of using NULL to signal that sequences
814 $safeseq = preg_replace( "/'/", "''", $seqName );
815 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
816 $row = $this->fetchRow( $res );
817 $this->mInsertId = $row[0];
818 return $this->mInsertId;
824 * This must be called after nextSequenceVal
825 * @return Last sequence value used as a primary key
827 public function insertId() {
828 return $this->mInsertId
;
832 * Updates the mInsertId property with the value of the last insert
833 * into a generated column
835 * @param $table String: sanitized table name
836 * @param $primaryKey Mixed: string name of the primary key
837 * @param $stmt Resource: prepared statement resource
838 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
840 private function calcInsertId( $table, $primaryKey, $stmt ) {
842 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
847 * INSERT wrapper, inserts an array into a table
849 * $args may be a single associative array, or an array of arrays
850 * with numeric keys, for multi-row insert
852 * @param $table String: Name of the table to insert to.
853 * @param $args Array: Items to insert into the table.
854 * @param $fname String: Name of the function, for profiling
855 * @param $options String or Array. Valid options: IGNORE
857 * @return bool Success of insert operation. IGNORE always returns true.
859 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
862 if ( !count( $args ) ) {
865 // get database-specific table name (not used)
866 $table = $this->tableName( $table );
867 // format options as an array
868 $options = IBM_DB2Helper
::makeArray( $options );
869 // format args as an array of arrays
870 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
871 $args = array( $args );
874 // prevent insertion of NULL into primary key columns
875 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
876 // if there's only one primary key
877 // we'll be able to read its value after insertion
879 if ( count( $primaryKeys ) == 1 ) {
880 $primaryKey = $primaryKeys[0];
884 $keys = array_keys( $args[0] );
885 $key_count = count( $keys );
887 // If IGNORE is set, we use savepoints to emulate mysql's behavior
888 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
892 // If we are not in a transaction, we need to be for savepoint trickery
893 if ( !$this->mTrxLevel
) {
897 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
898 if ( $key_count == 1 ) {
901 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
903 //$this->installPrint( "Preparing the following SQL:" );
904 //$this->installPrint( "$sql" );
905 //$this->installPrint( print_r( $args, true ));
906 $stmt = $this->prepare( $sql );
908 // start a transaction/enter transaction mode
913 foreach ( $args as $row ) {
914 //$this->installPrint( "Inserting " . print_r( $row, true ));
915 // insert each row into the database
916 $res = $res & $this->execute( $stmt, $row );
918 $this->installPrint( 'Last error:' );
919 $this->installPrint( $this->lastError() );
921 // get the last inserted value into a generated column
922 $this->calcInsertId( $table, $primaryKey, $stmt );
925 $olde = error_reporting( 0 );
926 // For future use, we may want to track the number of actual inserts
927 // Right now, insert (all writes) simply return true/false
928 $numrowsinserted = 0;
930 // always return true
933 foreach ( $args as $row ) {
934 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
935 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
937 $this->execute( $stmt, $row );
940 $this->installPrint( 'Last error:' );
941 $this->installPrint( $this->lastError() );
943 // get the last inserted value into a generated column
944 $this->calcInsertId( $table, $primaryKey, $stmt );
946 $errNum = $this->lastErrno();
948 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
949 $this->mStmtOptions
);
951 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
952 $this->mStmtOptions
);
957 $olde = error_reporting( $olde );
958 // Set the affected row count for the whole operation
959 $this->mAffectedRows
= $numrowsinserted;
963 $this->freePrepared( $stmt );
969 * Given a table name and a hash of columns with values
970 * Removes primary key columns from the hash where the value is NULL
972 * @param $table String: name of the table
973 * @param $args Array of hashes of column names with values
974 * @return Array: tuple( filtered array of columns, array of primary keys )
976 private function removeNullPrimaryKeys( $table, $args ) {
977 $schema = $this->mSchema
;
978 // find out the primary keys
979 $keyres = db2_primary_keys( $this->mConn
, null, strtoupper( $schema ),
984 $row = $this->fetchObject( $keyres );
986 $row = $this->fetchObject( $keyres )
989 $keys[] = strtolower( $row->column_name
);
991 // remove primary keys
992 foreach ( $args as $ai => $row ) {
993 foreach ( $keys as $key ) {
994 if ( $row[$key] == null ) {
1000 // return modified hash
1001 return array( $args, $keys );
1005 * UPDATE wrapper, takes a condition array and a SET array
1007 * @param $table String: The table to UPDATE
1008 * @param $values An array of values to SET
1009 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1010 * @param $fname String: The Class::Function calling this function
1012 * @param $options An array of UPDATE options, can be one or
1013 * more of IGNORE, LOW_PRIORITY
1016 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1017 $options = array() )
1019 $table = $this->tableName( $table );
1020 $opts = $this->makeUpdateOptions( $options );
1021 $sql = "UPDATE $opts $table SET "
1022 . $this->makeList( $values, LIST_SET_PREPARED
);
1023 if ( $conds != '*' ) {
1024 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1026 $stmt = $this->prepare( $sql );
1027 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1028 // assuming for now that an array with string keys will work
1029 // if not, convert to simple array first
1030 $result = $this->execute( $stmt, $values );
1031 $this->freePrepared( $stmt );
1037 * DELETE query wrapper
1039 * Use $conds == "*" to delete all rows
1041 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1043 throw new DBUnexpectedError( $this,
1044 'DatabaseIbm_db2::delete() called with no conditions' );
1046 $table = $this->tableName( $table );
1047 $sql = "DELETE FROM $table";
1048 if ( $conds != '*' ) {
1049 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1051 $result = $this->query( $sql, $fname );
1057 * Returns the number of rows affected by the last query or 0
1058 * @return Integer: the number of rows affected by the last query
1060 public function affectedRows() {
1061 if ( !is_null( $this->mAffectedRows
) ) {
1062 // Forced result for simulated queries
1063 return $this->mAffectedRows
;
1065 if( empty( $this->mLastResult
) ) {
1068 return db2_num_rows( $this->mLastResult
);
1072 * Simulates REPLACE with a DELETE followed by INSERT
1073 * @param $table Object
1074 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1075 * @param $rows Array: rows to insert
1076 * @param $fname String: name of the function for profiling
1079 function replace( $table, $uniqueIndexes, $rows,
1080 $fname = 'DatabaseIbm_db2::replace' )
1082 $table = $this->tableName( $table );
1084 if ( count( $rows )==0 ) {
1089 if ( !is_array( reset( $rows ) ) ) {
1090 $rows = array( $rows );
1093 foreach( $rows as $row ) {
1094 # Delete rows which collide
1095 if ( $uniqueIndexes ) {
1096 $sql = "DELETE FROM $table WHERE ";
1098 foreach ( $uniqueIndexes as $index ) {
1105 if ( is_array( $index ) ) {
1107 foreach ( $index as $col ) {
1113 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1116 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1120 $this->query( $sql, $fname );
1123 # Now insert the row
1124 $sql = "INSERT INTO $table ( "
1125 . $this->makeList( array_keys( $row ), LIST_NAMES
)
1126 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA
) . ' )';
1127 $this->query( $sql, $fname );
1132 * Returns the number of rows in the result set
1133 * Has to be called right after the corresponding select query
1134 * @param $res Object result set
1135 * @return Integer: number of rows
1137 public function numRows( $res ) {
1138 if ( $res instanceof ResultWrapper
) {
1139 $res = $res->result
;
1141 if ( $this->mNumRows
) {
1142 return $this->mNumRows
;
1149 * Moves the row pointer of the result set
1150 * @param $res Object: result set
1151 * @param $row Integer: row number
1152 * @return success or failure
1154 public function dataSeek( $res, $row ) {
1155 if ( $res instanceof ResultWrapper
) {
1156 $res = $res->result
;
1158 return db2_fetch_row( $res, $row );
1162 # Fix notices in Block.php
1166 * Frees memory associated with a statement resource
1167 * @param $res Object: statement resource to free
1168 * @return Boolean success or failure
1170 public function freeResult( $res ) {
1171 if ( $res instanceof ResultWrapper
) {
1172 $res = $res->result
;
1174 if ( !@db2_free_result
( $res ) ) {
1175 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1180 * Returns the number of columns in a resource
1181 * @param $res Object: statement resource
1182 * @return Number of fields/columns in resource
1184 public function numFields( $res ) {
1185 if ( $res instanceof ResultWrapper
) {
1186 $res = $res->result
;
1188 return db2_num_fields( $res );
1192 * Returns the nth column name
1193 * @param $res Object: statement resource
1194 * @param $n Integer: Index of field or column
1195 * @return String name of nth column
1197 public function fieldName( $res, $n ) {
1198 if ( $res instanceof ResultWrapper
) {
1199 $res = $res->result
;
1201 return db2_field_name( $res, $n );
1207 * @param $table Array or string, table name(s) (prefix auto-added)
1208 * @param $vars Array or string, field name(s) to be retrieved
1209 * @param $conds Array or string, condition(s) for WHERE
1210 * @param $fname String: calling function name (use __METHOD__)
1211 * for logs/profiling
1212 * @param $options Associative array of options
1213 * (e.g. array('GROUP BY' => 'page_title')),
1214 * see Database::makeSelectOptions code for list of
1216 * @param $join_conds Associative array of table join conditions (optional)
1217 * (e.g. array( 'page' => array('LEFT JOIN',
1218 * 'page_latest=rev_id') )
1219 * @return Mixed: database result resource for fetch functions or false
1222 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1224 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1227 // We must adjust for offset
1228 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1229 $limit = $options['LIMIT'];
1230 $offset = $options['OFFSET'];
1233 // DB2 does not have a proper num_rows() function yet, so we must emulate
1234 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1238 // we want the count
1239 $vars2 = array( 'count( * ) as num_rows' );
1240 // respecting just the limit option
1241 $options2 = array();
1242 if ( isset( $options['LIMIT'] ) ) {
1243 $options2['LIMIT'] = $options['LIMIT'];
1245 // but don't try to emulate for GROUP BY
1246 if ( isset( $options['GROUP BY'] ) ) {
1250 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1252 $obj = $this->fetchObject( $res2 );
1253 $this->mNumRows
= $obj->num_rows
;
1259 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1260 * Has limited support for per-column options (colnum => 'DISTINCT')
1264 * @param $options Associative array of options to be turned into
1265 * an SQL query, valid keys are listed in the function.
1268 function makeSelectOptions( $options ) {
1269 $preLimitTail = $postLimitTail = '';
1272 $noKeyOptions = array();
1273 foreach ( $options as $key => $option ) {
1274 if ( is_numeric( $key ) ) {
1275 $noKeyOptions[$option] = true;
1279 if ( isset( $options['GROUP BY'] ) ) {
1280 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1282 if ( isset( $options['HAVING'] ) ) {
1283 $preLimitTail .= " HAVING {$options['HAVING']}";
1285 if ( isset( $options['ORDER BY'] ) ) {
1286 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1289 if ( isset( $noKeyOptions['DISTINCT'] )
1290 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1292 $startOpts .= 'DISTINCT';
1295 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1299 * Returns link to IBM DB2 free download
1300 * @return String: wikitext of a link to the server software's web site
1302 public static function getSoftwareLink() {
1303 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1307 * Get search engine class. All subclasses of this
1308 * need to implement this if they wish to use searching.
1312 public function getSearchEngine() {
1313 return 'SearchIBM_DB2';
1317 * Did the last database access fail because of deadlock?
1320 public function wasDeadlock() {
1322 $err = $this->lastErrno();
1324 // This is literal port of the MySQL logic and may be wrong for DB2
1325 case '40001': // sql0911n, Deadlock or timeout, rollback
1326 case '57011': // sql0904n, Resource unavailable, no rollback
1327 case '57033': // sql0913n, Deadlock or timeout, no rollback
1328 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1335 * Ping the server and try to reconnect if it there is no connection
1336 * The connection may be closed and reopened while this happens
1337 * @return Boolean: whether the connection exists
1339 public function ping() {
1340 // db2_ping() doesn't exist
1343 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1344 $this->mPassword
, $this->mServer
, $this->mPort
);
1348 ######################################
1349 # Unimplemented and not applicable
1350 ######################################
1355 public function getStatus( $which = '%' ) {
1356 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1361 * @return string $sql
1363 public function limitResultForUpdate( $sql, $num ) {
1364 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1369 * Only useful with fake prepare like in base Database class
1372 public function fillPreparedArg( $matches ) {
1373 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1377 ######################################
1379 ######################################
1382 * Returns information about an index
1383 * If errors are explicitly ignored, returns NULL on failure
1384 * @param $table String: table name
1385 * @param $index String: index name
1386 * @param $fname String: function name for logging and profiling
1387 * @return Object query row in object form
1389 public function indexInfo( $table, $index,
1390 $fname = 'DatabaseIbm_db2::indexExists' )
1392 $table = $this->tableName( $table );
1394 SELECT name as indexname
1395 FROM sysibm.sysindexes si
1396 WHERE si.name='$index' AND si.tbname='$table'
1397 AND sc.tbcreator='$this->mSchema'
1399 $res = $this->query( $sql, $fname );
1403 $row = $this->fetchObject( $res );
1404 if ( $row != null ) {
1412 * Returns an information object on a table column
1413 * @param $table String: table name
1414 * @param $field String: column name
1415 * @return IBM_DB2Field
1417 public function fieldInfo( $table, $field ) {
1418 return IBM_DB2Field
::fromText( $this, $table, $field );
1422 * db2_field_type() wrapper
1423 * @param $res Object: result of executed statement
1424 * @param $index Mixed: number or name of the column
1425 * @return String column type
1427 public function fieldType( $res, $index ) {
1428 if ( $res instanceof ResultWrapper
) {
1429 $res = $res->result
;
1431 return db2_field_type( $res, $index );
1435 * Verifies that an index was created as unique
1436 * @param $table String: table name
1437 * @param $index String: index name
1438 * @param $fname function name for profiling
1441 public function indexUnique ( $table, $index,
1442 $fname = 'DatabaseIbm_db2::indexUnique' )
1444 $table = $this->tableName( $table );
1446 SELECT si.name as indexname
1447 FROM sysibm.sysindexes si
1448 WHERE si.name='$index' AND si.tbname='$table'
1449 AND sc.tbcreator='$this->mSchema'
1450 AND si.uniquerule IN ( 'U', 'P' )
1452 $res = $this->query( $sql, $fname );
1456 if ( $this->fetchObject( $res ) ) {
1464 * Returns the size of a text field, or -1 for "unlimited"
1465 * @param $table String: table name
1466 * @param $field String: column name
1467 * @return Integer: length or -1 for unlimited
1469 public function textFieldSize( $table, $field ) {
1470 $table = $this->tableName( $table );
1472 SELECT length as size
1473 FROM sysibm.syscolumns sc
1474 WHERE sc.name='$field' AND sc.tbname='$table'
1475 AND sc.tbcreator='$this->mSchema'
1477 $res = $this->query( $sql );
1478 $row = $this->fetchObject( $res );
1484 * DELETE where the condition is a join
1485 * @param $delTable String: deleting from this table
1486 * @param $joinTable String: using data from this table
1487 * @param $delVar String: variable in deleteable table
1488 * @param $joinVar String: variable in data table
1489 * @param $conds Array: conditionals for join table
1490 * @param $fname String: function name for profiling
1492 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1493 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1496 throw new DBUnexpectedError( $this,
1497 'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
1500 $delTable = $this->tableName( $delTable );
1501 $joinTable = $this->tableName( $joinTable );
1503 DELETE FROM $delTable
1505 SELECT $joinVar FROM $joinTable
1508 if ( $conds != '*' ) {
1509 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1513 $this->query( $sql, $fname );
1517 * Description is left as an exercise for the reader
1518 * @param $b Mixed: data to be encoded
1519 * @return IBM_DB2Blob
1521 public function encodeBlob( $b ) {
1522 return new IBM_DB2Blob( $b );
1526 * Description is left as an exercise for the reader
1527 * @param $b IBM_DB2Blob: data to be decoded
1530 public function decodeBlob( $b ) {
1535 * Convert into a list of string being concatenated
1536 * @param $stringList Array: strings that need to be joined together
1538 * @return String: joined by the concatenation operator
1540 public function buildConcat( $stringList ) {
1541 // || is equivalent to CONCAT
1542 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1543 return implode( ' || ', $stringList );
1547 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1548 * @param $column String: name of timestamp column
1549 * @return String: SQL code
1551 public function extractUnixEpoch( $column ) {
1553 // see SpecialAncientpages
1556 ######################################
1557 # Prepared statements
1558 ######################################
1561 * Intended to be compatible with the PEAR::DB wrapper functions.
1562 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1564 * ? = scalar value, quoted as necessary
1565 * ! = raw SQL bit (a function for instance)
1566 * & = filename; reads the file and inserts as a blob
1567 * (we don't use this though...)
1568 * @param $sql String: SQL statement with appropriate markers
1569 * @param $func String: Name of the function, for profiling
1570 * @return resource a prepared DB2 SQL statement
1572 public function prepare( $sql, $func = 'DB2::prepare' ) {
1573 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1578 * Frees resources associated with a prepared statement
1579 * @return Boolean success or failure
1581 public function freePrepared( $prepared ) {
1582 return db2_free_stmt( $prepared );
1586 * Execute a prepared query with the various arguments
1587 * @param $prepared String: the prepared sql
1588 * @param $args Mixed: either an array here, or put scalars as varargs
1589 * @return Resource: results object
1591 public function execute( $prepared, $args = null ) {
1592 if( !is_array( $args ) ) {
1594 $args = func_get_args();
1595 array_shift( $args );
1597 $res = db2_execute( $prepared, $args );
1599 $this->installPrint( db2_stmt_errormsg() );
1605 * Prepare & execute an SQL statement, quoting and inserting arguments
1606 * in the appropriate places.
1607 * @param $query String
1610 public function safeQuery( $query, $args = null ) {
1611 // copied verbatim from Database.php
1612 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1613 if( !is_array( $args ) ) {
1615 $args = func_get_args();
1616 array_shift( $args );
1618 $retval = $this->execute( $prepared, $args );
1619 $this->freePrepared( $prepared );
1624 * For faking prepared SQL statements on DBs that don't support
1626 * @param $preparedQuery String: a 'preparable' SQL statement
1627 * @param $args Array of arguments to fill it with
1628 * @return String: executable statement
1630 public function fillPrepared( $preparedQuery, $args ) {
1632 $this->preparedArgs
=& $args;
1634 foreach ( $args as $i => $arg ) {
1635 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1638 return $preparedQuery;
1642 * Switches module between regular and install modes
1644 public function setMode( $mode ) {
1645 $old = $this->mMode
;
1646 $this->mMode
= $mode;
1651 * Bitwise negation of a column or value in SQL
1652 * Same as (~field) in C
1653 * @param $field String
1656 function bitNot( $field ) {
1657 // expecting bit-fields smaller than 4bytes
1658 return "BITNOT( $field )";
1662 * Bitwise AND of two columns or values in SQL
1663 * Same as (fieldLeft & fieldRight) in C
1664 * @param $fieldLeft String
1665 * @param $fieldRight String
1668 function bitAnd( $fieldLeft, $fieldRight ) {
1669 return "BITAND( $fieldLeft, $fieldRight )";
1673 * Bitwise OR of two columns or values in SQL
1674 * Same as (fieldLeft | fieldRight) in C
1675 * @param $fieldLeft String
1676 * @param $fieldRight String
1679 function bitOr( $fieldLeft, $fieldRight ) {
1680 return "BITOR( $fieldLeft, $fieldRight )";
1684 class IBM_DB2Helper
{
1685 public static function makeArray( $maybeArray ) {
1686 if ( !is_array( $maybeArray ) ) {
1687 return array( $maybeArray );