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
459 public function doQuery( $sql ) {
460 $this->applySchema();
462 // Needed to handle any UTF-8 encoding issues in the raw sql
463 // Note that we fully support prepared statements for DB2
464 // prepare() and execute() should be used instead of doQuery() whenever possible
465 $sql = utf8_decode($sql);
467 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
468 if( $ret == false ) {
469 $error = db2_stmt_errormsg();
471 $this->installPrint( "<pre>$sql</pre>" );
472 $this->installPrint( $error );
473 throw new DBUnexpectedError( $this, 'SQL error: '
474 . htmlspecialchars( $error ) );
476 $this->mLastResult
= $ret;
477 $this->mAffectedRows
= null; // Not calculated until asked for
482 * @return string Version information from the database
484 public function getServerVersion() {
485 $info = db2_server_info( $this->mConn
);
486 return $info->DBMS_VER
;
490 * Queries whether a given table exists
493 public function tableExists( $table ) {
494 $schema = $this->mSchema
;
496 $sql = "SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST WHERE ST.NAME = '" .
497 strtoupper( $table ) .
498 "' AND ST.CREATOR = '" .
499 strtoupper( $schema ) . "'";
500 $res = $this->query( $sql );
505 // If the table exists, there should be one of it
506 @$row = $this->fetchRow( $res );
508 if ( $count == '1' ||
$count == 1 ) {
516 * Fetch the next row from the given result object, in object form.
517 * Fields can be retrieved with $row->fieldname, with fields acting like
520 * @param $res SQL result object as returned from Database::query(), etc.
521 * @return DB2 row object
522 * @throws DBUnexpectedError Thrown if the database returns an error
524 public function fetchObject( $res ) {
525 if ( $res instanceof ResultWrapper
) {
528 @$row = db2_fetch_object( $res );
529 if( $this->lastErrno() ) {
530 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
531 . htmlspecialchars( $this->lastError() ) );
537 * Fetch the next row from the given result object, in associative array
538 * form. Fields are retrieved with $row['fieldname'].
540 * @param $res SQL result object as returned from Database::query(), etc.
541 * @return DB2 row object
542 * @throws DBUnexpectedError Thrown if the database returns an error
544 public function fetchRow( $res ) {
545 if ( $res instanceof ResultWrapper
) {
548 if ( db2_num_rows( $res ) > 0) {
549 @$row = db2_fetch_array( $res );
550 if ( $this->lastErrno() ) {
551 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
552 . htmlspecialchars( $this->lastError() ) );
560 * Create tables, stored procedures, and so on
562 public function setup_database() {
564 // TODO: switch to root login if available
566 // Switch into the correct namespace
567 $this->applySchema();
570 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
571 if ( $res !== true ) {
572 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
576 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
577 if ( $res !== true ) {
578 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
580 print '<li>Foreign keys done</li>';
583 // TODO: populate interwiki links
585 if ( $this->lastError() ) {
587 'Errors encountered during table creation -- rolled back' );
588 $this->installPrint( 'Please install again' );
593 } catch ( MWException
$mwe ) {
594 print "<br><pre>$mwe</pre><br>";
600 * Doesn't escape numbers
602 * @param $s String: string to escape
603 * @return escaped string
605 public function addQuotes( $s ) {
606 //$this->installPrint( "DB2::addQuotes( $s )\n" );
607 if ( is_null( $s ) ) {
609 } elseif ( $s instanceof Blob
) {
610 return "'" . $s->fetch( $s ) . "'";
611 } elseif ( $s instanceof IBM_DB2Blob
) {
612 return "'" . $this->decodeBlob( $s ) . "'";
614 $s = $this->strencode( $s );
615 if ( is_numeric( $s ) ) {
623 * Verifies that a DB2 column/field type is numeric
625 * @param $type String: DB2 column type
626 * @return Boolean: true if numeric
628 public function is_numeric_type( $type ) {
629 switch ( strtoupper( $type ) ) {
644 * Alias for addQuotes()
645 * @param $s String: string to escape
646 * @return escaped string
648 public function strencode( $s ) {
649 // Bloody useless function
650 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
651 // But also necessary
652 $s = db2_escape_string( $s );
653 // Wide characters are evil -- some of them look like '
654 $s = utf8_encode( $s );
656 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
657 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
658 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
663 * Switch into the database schema
665 protected function applySchema() {
666 if ( !( $this->mSchemaSet
) ) {
667 $this->mSchemaSet
= true;
669 $this->doQuery( "SET SCHEMA = $this->mSchema" );
675 * Start a transaction (mandatory)
677 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
678 // BEGIN is implicit for DB2
679 // However, it requires that AutoCommit be off.
681 // Some MediaWiki code is still transaction-less (?).
682 // The strategy is to keep AutoCommit on for that code
683 // but switch it off whenever a transaction is begun.
684 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_OFF
);
686 $this->mTrxLevel
= 1;
691 * Must have a preceding begin()
693 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
694 db2_commit( $this->mConn
);
696 // Some MediaWiki code is still transaction-less (?).
697 // The strategy is to keep AutoCommit on for that code
698 // but switch it off whenever a transaction is begun.
699 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
701 $this->mTrxLevel
= 0;
705 * Cancel a transaction
707 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
708 db2_rollback( $this->mConn
);
709 // turn auto-commit back on
710 // not sure if this is appropriate
711 db2_autocommit( $this->mConn
, DB2_AUTOCOMMIT_ON
);
712 $this->mTrxLevel
= 0;
716 * Makes an encoded list of strings from an array
718 * LIST_COMMA - comma separated, no field names
719 * LIST_AND - ANDed WHERE clause (without the WHERE)
720 * LIST_OR - ORed WHERE clause (without the WHERE)
721 * LIST_SET - comma separated with field names, like a SET clause
722 * LIST_NAMES - comma separated field names
723 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
725 function makeList( $a, $mode = LIST_COMMA
) {
726 if ( !is_array( $a ) ) {
727 throw new DBUnexpectedError( $this,
728 'DatabaseIbm_db2::makeList called with incorrect parameters' );
731 // if this is for a prepared UPDATE statement
732 // (this should be promoted to the parent class
733 // once other databases use prepared statements)
734 if ( $mode == LIST_SET_PREPARED
) {
737 foreach ( $a as $field => $value ) {
739 $list .= ", $field = ?";
741 $list .= "$field = ?";
750 // otherwise, call the usual function
751 return parent
::makeList( $a, $mode );
755 * Construct a LIMIT query with optional offset
756 * This is used for query pages
758 * @param $sql string SQL query we will append the limit too
759 * @param $limit integer the SQL limit
760 * @param $offset integer the SQL offset (default false)
762 public function limitResult( $sql, $limit, $offset=false ) {
763 if( !is_numeric( $limit ) ) {
764 throw new DBUnexpectedError( $this,
765 "Invalid non-numeric limit passed to limitResult()\n" );
768 if ( stripos( $sql, 'where' ) === false ) {
769 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
771 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
774 return "$sql FETCH FIRST $limit ROWS ONLY ";
778 * Handle reserved keyword replacement in table names
780 * @param $name Object
783 public function tableName( $name ) {
784 // we want maximum compatibility with MySQL schema
789 * Generates a timestamp in an insertable format
791 * @param $ts timestamp
792 * @return String: timestamp value
794 public function timestamp( $ts = 0 ) {
795 // TS_MW cannot be easily distinguished from an integer
796 return wfTimestamp( TS_DB2
, $ts );
800 * Return the next in a sequence, save the value for retrieval via insertId()
801 * @param $seqName String: name of a defined sequence in the database
802 * @return next value in that sequence
804 public function nextSequenceValue( $seqName ) {
805 // Not using sequences in the primary schema to allow for easier migration
807 // Emulating MySQL behaviour of using NULL to signal that sequences
810 $safeseq = preg_replace( "/'/", "''", $seqName );
811 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
812 $row = $this->fetchRow( $res );
813 $this->mInsertId = $row[0];
814 return $this->mInsertId;
820 * This must be called after nextSequenceVal
821 * @return Last sequence value used as a primary key
823 public function insertId() {
824 return $this->mInsertId
;
828 * Updates the mInsertId property with the value of the last insert
829 * into a generated column
831 * @param $table String: sanitized table name
832 * @param $primaryKey Mixed: string name of the primary key
833 * @param $stmt Resource: prepared statement resource
834 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
836 private function calcInsertId( $table, $primaryKey, $stmt ) {
838 $this->mInsertId
= db2_last_insert_id( $this->mConn
);
843 * INSERT wrapper, inserts an array into a table
845 * $args may be a single associative array, or an array of arrays
846 * with numeric keys, for multi-row insert
848 * @param $table String: Name of the table to insert to.
849 * @param $args Array: Items to insert into the table.
850 * @param $fname String: Name of the function, for profiling
851 * @param $options String or Array. Valid options: IGNORE
853 * @return bool Success of insert operation. IGNORE always returns true.
855 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
858 if ( !count( $args ) ) {
861 // get database-specific table name (not used)
862 $table = $this->tableName( $table );
863 // format options as an array
864 $options = IBM_DB2Helper
::makeArray( $options );
865 // format args as an array of arrays
866 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
867 $args = array( $args );
870 // prevent insertion of NULL into primary key columns
871 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
872 // if there's only one primary key
873 // we'll be able to read its value after insertion
875 if ( count( $primaryKeys ) == 1 ) {
876 $primaryKey = $primaryKeys[0];
880 $keys = array_keys( $args[0] );
881 $key_count = count( $keys );
883 // If IGNORE is set, we use savepoints to emulate mysql's behavior
884 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
888 // If we are not in a transaction, we need to be for savepoint trickery
889 if ( !$this->mTrxLevel
) {
893 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
894 if ( $key_count == 1 ) {
897 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
899 $this->installPrint( "Preparing the following SQL:" );
900 $this->installPrint( "$sql" );
901 $this->installPrint( print_r( $args, true ));
902 $stmt = $this->prepare( $sql );
904 // start a transaction/enter transaction mode
909 foreach ( $args as $row ) {
910 //$this->installPrint( "Inserting " . print_r( $row, true ));
911 // insert each row into the database
912 $res = $res & $this->execute( $stmt, $row );
914 $this->installPrint( 'Last error:' );
915 $this->installPrint( $this->lastError() );
917 // get the last inserted value into a generated column
918 $this->calcInsertId( $table, $primaryKey, $stmt );
921 $olde = error_reporting( 0 );
922 // For future use, we may want to track the number of actual inserts
923 // Right now, insert (all writes) simply return true/false
924 $numrowsinserted = 0;
926 // always return true
929 foreach ( $args as $row ) {
930 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
931 db2_exec( $this->mConn
, $overhead, $this->mStmtOptions
);
933 $res2 = $this->execute( $stmt, $row );
936 $this->installPrint( 'Last error:' );
937 $this->installPrint( $this->lastError() );
939 // get the last inserted value into a generated column
940 $this->calcInsertId( $table, $primaryKey, $stmt );
942 $errNum = $this->lastErrno();
944 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore",
945 $this->mStmtOptions
);
947 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore",
948 $this->mStmtOptions
);
953 $olde = error_reporting( $olde );
954 // Set the affected row count for the whole operation
955 $this->mAffectedRows
= $numrowsinserted;
959 $this->freePrepared( $stmt );
965 * Given a table name and a hash of columns with values
966 * Removes primary key columns from the hash where the value is NULL
968 * @param $table String: name of the table
969 * @param $args Array of hashes of column names with values
970 * @return Array: tuple( filtered array of columns, array of primary keys )
972 private function removeNullPrimaryKeys( $table, $args ) {
973 $schema = $this->mSchema
;
975 // find out the primary keys
976 $keyres = $this->doQuery( "SELECT NAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME = '"
977 . strtoupper( $table )
978 . "' AND TBCREATOR = '"
979 . strtoupper( $schema )
980 . "' AND KEYSEQ > 0" );
984 $row = $this->fetchRow( $keyres );
986 $row = $this->fetchRow( $keyres )
989 $keys[] = strtolower( $row[0] );
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 $this->insert($table, $row);
1129 * Returns the number of rows in the result set
1130 * Has to be called right after the corresponding select query
1131 * @param $res Object result set
1132 * @return Integer: number of rows
1134 public function numRows( $res ) {
1135 if ( $res instanceof ResultWrapper
) {
1136 $res = $res->result
;
1139 if ( $this->mNumRows
) {
1140 return $this->mNumRows
;
1147 * Moves the row pointer of the result set
1148 * @param $res Object: result set
1149 * @param $row Integer: row number
1150 * @return success or failure
1152 public function dataSeek( $res, $row ) {
1153 if ( $res instanceof ResultWrapper
) {
1154 $res = $res->result
;
1156 return db2_fetch_row( $res, $row );
1160 # Fix notices in Block.php
1164 * Frees memory associated with a statement resource
1165 * @param $res Object: statement resource to free
1166 * @return Boolean success or failure
1168 public function freeResult( $res ) {
1169 if ( $res instanceof ResultWrapper
) {
1170 $res = $res->result
;
1172 if ( !@db2_free_result
( $res ) ) {
1173 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1178 * Returns the number of columns in a resource
1179 * @param $res Object: statement resource
1180 * @return Number of fields/columns in resource
1182 public function numFields( $res ) {
1183 if ( $res instanceof ResultWrapper
) {
1184 $res = $res->result
;
1186 return db2_num_fields( $res );
1190 * Returns the nth column name
1191 * @param $res Object: statement resource
1192 * @param $n Integer: Index of field or column
1193 * @return String name of nth column
1195 public function fieldName( $res, $n ) {
1196 if ( $res instanceof ResultWrapper
) {
1197 $res = $res->result
;
1199 return db2_field_name( $res, $n );
1205 * @param $table Array or string, table name(s) (prefix auto-added)
1206 * @param $vars Array or string, field name(s) to be retrieved
1207 * @param $conds Array or string, condition(s) for WHERE
1208 * @param $fname String: calling function name (use __METHOD__)
1209 * for logs/profiling
1210 * @param $options Associative array of options
1211 * (e.g. array('GROUP BY' => 'page_title')),
1212 * see Database::makeSelectOptions code for list of
1214 * @param $join_conds Associative array of table join conditions (optional)
1215 * (e.g. array( 'page' => array('LEFT JOIN',
1216 * 'page_latest=rev_id') )
1217 * @return Mixed: database result resource for fetch functions or false
1220 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1222 $res = parent
::select( $table, $vars, $conds, $fname, $options,
1225 // We must adjust for offset
1226 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1227 $limit = $options['LIMIT'];
1228 $offset = $options['OFFSET'];
1231 // DB2 does not have a proper num_rows() function yet, so we must emulate
1232 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1236 // we want the count
1237 $vars2 = array( 'count( * ) as num_rows' );
1238 // respecting just the limit option
1239 $options2 = array();
1240 if ( isset( $options['LIMIT'] ) ) {
1241 $options2['LIMIT'] = $options['LIMIT'];
1243 // but don't try to emulate for GROUP BY
1244 if ( isset( $options['GROUP BY'] ) ) {
1248 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2,
1250 $obj = $this->fetchObject( $res2 );
1251 $this->mNumRows
= $obj->num_rows
;
1257 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1258 * Has limited support for per-column options (colnum => 'DISTINCT')
1262 * @param $options Associative array of options to be turned into
1263 * an SQL query, valid keys are listed in the function.
1266 function makeSelectOptions( $options ) {
1267 $preLimitTail = $postLimitTail = '';
1270 $noKeyOptions = array();
1271 foreach ( $options as $key => $option ) {
1272 if ( is_numeric( $key ) ) {
1273 $noKeyOptions[$option] = true;
1277 if ( isset( $options['GROUP BY'] ) ) {
1278 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1280 if ( isset( $options['HAVING'] ) ) {
1281 $preLimitTail .= " HAVING {$options['HAVING']}";
1283 if ( isset( $options['ORDER BY'] ) ) {
1284 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1287 if ( isset( $noKeyOptions['DISTINCT'] )
1288 ||
isset( $noKeyOptions['DISTINCTROW'] ) )
1290 $startOpts .= 'DISTINCT';
1293 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1297 * Returns link to IBM DB2 free download
1298 * @return String: wikitext of a link to the server software's web site
1300 public static function getSoftwareLink() {
1301 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1305 * Get search engine class. All subclasses of this
1306 * need to implement this if they wish to use searching.
1310 public function getSearchEngine() {
1311 return 'SearchIBM_DB2';
1315 * Did the last database access fail because of deadlock?
1318 public function wasDeadlock() {
1320 $err = $this->lastErrno();
1322 // This is literal port of the MySQL logic and may be wrong for DB2
1323 case '40001': // sql0911n, Deadlock or timeout, rollback
1324 case '57011': // sql0904n, Resource unavailable, no rollback
1325 case '57033': // sql0913n, Deadlock or timeout, no rollback
1326 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1333 * Ping the server and try to reconnect if it there is no connection
1334 * The connection may be closed and reopened while this happens
1335 * @return Boolean: whether the connection exists
1337 public function ping() {
1338 // db2_ping() doesn't exist
1341 $this->mConn
= $this->openUncataloged( $this->mDBName
, $this->mUser
,
1342 $this->mPassword
, $this->mServer
, $this->mPort
);
1346 ######################################
1347 # Unimplemented and not applicable
1348 ######################################
1353 public function getStatus( $which = '%' ) {
1354 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1359 * @return string $sql
1361 public function limitResultForUpdate( $sql, $num ) {
1362 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1367 * Only useful with fake prepare like in base Database class
1370 public function fillPreparedArg( $matches ) {
1371 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1375 ######################################
1377 ######################################
1380 * Returns information about an index
1381 * If errors are explicitly ignored, returns NULL on failure
1382 * @param $table String: table name
1383 * @param $index String: index name
1384 * @param $fname String: function name for logging and profiling
1385 * @return Object query row in object form
1387 public function indexInfo( $table, $index,
1388 $fname = 'DatabaseIbm_db2::indexExists' )
1390 $table = $this->tableName( $table );
1392 SELECT name as indexname
1393 FROM sysibm.sysindexes si
1394 WHERE si.name='$index' AND si.tbname='$table'
1395 AND sc.tbcreator='$this->mSchema'
1397 $res = $this->query( $sql, $fname );
1401 $row = $this->fetchObject( $res );
1402 if ( $row != null ) {
1410 * Returns an information object on a table column
1411 * @param $table String: table name
1412 * @param $field String: column name
1413 * @return IBM_DB2Field
1415 public function fieldInfo( $table, $field ) {
1416 return IBM_DB2Field
::fromText( $this, $table, $field );
1420 * db2_field_type() wrapper
1421 * @param $res Object: result of executed statement
1422 * @param $index Mixed: number or name of the column
1423 * @return String column type
1425 public function fieldType( $res, $index ) {
1426 if ( $res instanceof ResultWrapper
) {
1427 $res = $res->result
;
1429 return db2_field_type( $res, $index );
1433 * Verifies that an index was created as unique
1434 * @param $table String: table name
1435 * @param $index String: index name
1436 * @param $fname function name for profiling
1439 public function indexUnique ( $table, $index,
1440 $fname = 'DatabaseIbm_db2::indexUnique' )
1442 $table = $this->tableName( $table );
1444 SELECT si.name as indexname
1445 FROM sysibm.sysindexes si
1446 WHERE si.name='$index' AND si.tbname='$table'
1447 AND sc.tbcreator='$this->mSchema'
1448 AND si.uniquerule IN ( 'U', 'P' )
1450 $res = $this->query( $sql, $fname );
1454 if ( $this->fetchObject( $res ) ) {
1462 * Returns the size of a text field, or -1 for "unlimited"
1463 * @param $table String: table name
1464 * @param $field String: column name
1465 * @return Integer: length or -1 for unlimited
1467 public function textFieldSize( $table, $field ) {
1468 $table = $this->tableName( $table );
1470 SELECT length as size
1471 FROM sysibm.syscolumns sc
1472 WHERE sc.name='$field' AND sc.tbname='$table'
1473 AND sc.tbcreator='$this->mSchema'
1475 $res = $this->query( $sql );
1476 $row = $this->fetchObject( $res );
1482 * DELETE where the condition is a join
1483 * @param $delTable String: deleting from this table
1484 * @param $joinTable String: using data from this table
1485 * @param $delVar String: variable in deleteable table
1486 * @param $joinVar String: variable in data table
1487 * @param $conds Array: conditionals for join table
1488 * @param $fname String: function name for profiling
1490 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1491 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1494 throw new DBUnexpectedError( $this,
1495 'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
1498 $delTable = $this->tableName( $delTable );
1499 $joinTable = $this->tableName( $joinTable );
1501 DELETE FROM $delTable
1503 SELECT $joinVar FROM $joinTable
1506 if ( $conds != '*' ) {
1507 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1511 $this->query( $sql, $fname );
1515 * Description is left as an exercise for the reader
1516 * @param $b Mixed: data to be encoded
1517 * @return IBM_DB2Blob
1519 public function encodeBlob( $b ) {
1520 return new IBM_DB2Blob( $b );
1524 * Description is left as an exercise for the reader
1525 * @param $b IBM_DB2Blob: data to be decoded
1528 public function decodeBlob( $b ) {
1533 * Convert into a list of string being concatenated
1534 * @param $stringList Array: strings that need to be joined together
1536 * @return String: joined by the concatenation operator
1538 public function buildConcat( $stringList ) {
1539 // || is equivalent to CONCAT
1540 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1541 return implode( ' || ', $stringList );
1545 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1546 * @param $column String: name of timestamp column
1547 * @return String: SQL code
1549 public function extractUnixEpoch( $column ) {
1551 // see SpecialAncientpages
1554 ######################################
1555 # Prepared statements
1556 ######################################
1559 * Intended to be compatible with the PEAR::DB wrapper functions.
1560 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1562 * ? = scalar value, quoted as necessary
1563 * ! = raw SQL bit (a function for instance)
1564 * & = filename; reads the file and inserts as a blob
1565 * (we don't use this though...)
1566 * @param $sql String: SQL statement with appropriate markers
1567 * @param $func String: Name of the function, for profiling
1568 * @return resource a prepared DB2 SQL statement
1570 public function prepare( $sql, $func = 'DB2::prepare' ) {
1571 $stmt = db2_prepare( $this->mConn
, $sql, $this->mStmtOptions
);
1576 * Frees resources associated with a prepared statement
1577 * @return Boolean success or failure
1579 public function freePrepared( $prepared ) {
1580 return db2_free_stmt( $prepared );
1584 * Execute a prepared query with the various arguments
1585 * @param $prepared String: the prepared sql
1586 * @param $args Mixed: either an array here, or put scalars as varargs
1587 * @return Resource: results object
1589 public function execute( $prepared, $args = null ) {
1590 if( !is_array( $args ) ) {
1592 $args = func_get_args();
1593 array_shift( $args );
1595 $res = db2_execute( $prepared, $args );
1597 $this->installPrint( db2_stmt_errormsg() );
1603 * Prepare & execute an SQL statement, quoting and inserting arguments
1604 * in the appropriate places.
1605 * @param $query String
1608 public function safeQuery( $query, $args = null ) {
1609 // copied verbatim from Database.php
1610 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1611 if( !is_array( $args ) ) {
1613 $args = func_get_args();
1614 array_shift( $args );
1616 $retval = $this->execute( $prepared, $args );
1617 $this->freePrepared( $prepared );
1622 * For faking prepared SQL statements on DBs that don't support
1624 * @param $preparedQuery String: a 'preparable' SQL statement
1625 * @param $args Array of arguments to fill it with
1626 * @return String: executable statement
1628 public function fillPrepared( $preparedQuery, $args ) {
1630 $this->preparedArgs
=& $args;
1632 foreach ( $args as $i => $arg ) {
1633 db2_bind_param( $preparedQuery, $i+
1, $args[$i] );
1636 return $preparedQuery;
1640 * Switches module between regular and install modes
1642 public function setMode( $mode ) {
1643 $old = $this->mMode
;
1644 $this->mMode
= $mode;
1649 * Bitwise negation of a column or value in SQL
1650 * Same as (~field) in C
1651 * @param $field String
1654 function bitNot( $field ) {
1655 // expecting bit-fields smaller than 4bytes
1656 return "BITNOT( $field )";
1660 * Bitwise AND of two columns or values in SQL
1661 * Same as (fieldLeft & fieldRight) in C
1662 * @param $fieldLeft String
1663 * @param $fieldRight String
1666 function bitAnd( $fieldLeft, $fieldRight ) {
1667 return "BITAND( $fieldLeft, $fieldRight )";
1671 * Bitwise OR of two columns or values in SQL
1672 * Same as (fieldLeft | fieldRight) in C
1673 * @param $fieldLeft String
1674 * @param $fieldRight String
1677 function bitOr( $fieldLeft, $fieldRight ) {
1678 return "BITOR( $fieldLeft, $fieldRight )";
1682 class IBM_DB2Helper
{
1683 public static function makeArray( $maybeArray ) {
1684 if ( !is_array( $maybeArray ) ) {
1685 return array( $maybeArray );