Rm unused assignment of $wgOut. $wgOut needs to be gone from Database code.
[mediawiki.git] / includes / db / DatabaseIbm_db2.php
blobad2862eedcae8c8d967b9c696dbc2ef82c632379
1 <?php
2 /**
3 * This is the IBM DB2 database abstraction layer.
4 * See maintenance/ibm_db2/README for development notes
5 * and other specific information
7 * @file
8 * @ingroup Database
9 * @author leo.petr+mediawiki@gmail.com
12 /**
13 * This represents a column in a DB2 database
14 * @ingroup Database
16 class IBM_DB2Field implements Field {
17 private $name = '';
18 private $tablename = '';
19 private $type = '';
20 private $nullable = false;
21 private $max_length = 0;
23 /**
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 ) {
31 global $wgDBmwschema;
33 $q = <<<SQL
34 SELECT
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;
39 SQL;
40 $res = $db->query(
41 sprintf( $q,
42 $db->addQuotes( $wgDBmwschema ),
43 $db->addQuotes( $table ),
44 $db->addQuotes( $field )
47 $row = $db->fetchObject( $res );
48 if ( !$row ) {
49 return null;
51 $n = new IBM_DB2Field;
52 $n->type = $row->typname;
53 $n->nullable = ( $row->attnotnull == 'N' );
54 $n->name = $field;
55 $n->tablename = $table;
56 $n->max_length = $row->attlen;
57 return $n;
59 /**
60 * Get column name
61 * @return string column name
63 function name() { return $this->name; }
64 /**
65 * Get table name
66 * @return string table name
68 function tableName() { return $this->tablename; }
69 /**
70 * Get column type
71 * @return string column type
73 function type() { return $this->type; }
74 /**
75 * Can column be null?
76 * @return bool true or false
78 function isNullable() { return $this->nullable; }
79 /**
80 * How much can you fit in the column per row?
81 * @return int length
83 function maxLength() { return $this->max_length; }
86 /**
87 * Wrapper around binary large objects
88 * @ingroup Database
90 class IBM_DB2Blob {
91 private $mData;
93 public function __construct( $data ) {
94 $this->mData = $data;
97 public function getData() {
98 return $this->mData;
101 public function __toString() {
102 return $this->mData;
107 * Primary database interface
108 * @ingroup Database
110 class DatabaseIbm_db2 extends DatabaseBase {
112 * Inherited members
113 protected $mLastQuery = '';
114 protected $mPHPError = false;
116 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
117 protected $mOpened = false;
119 protected $mTablePrefix;
120 protected $mFlags;
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() {
175 return true;
179 * Returns true if this database supports (and uses) triggers (e.g. on the
180 * page table)
182 function cleanupTriggers() {
183 return true;
187 * Returns true if this database is strict about what can be put into an
188 * IP field.
189 * Specifically, it uses a NULL value instead of an empty string.
191 function strictIPs() {
192 return true;
196 * Returns true if this database uses timestamps rather than integers
198 function realTimestamps() {
199 return true;
203 * Returns true if this database does an implicit sort when doing GROUP BY
205 function implicitGroupby() {
206 return false;
210 * Returns true if this database does an implicit order by when the column
211 * has an index
212 * For example: SELECT page_title FROM page LIMIT 1
214 function implicitOrderby() {
215 return false;
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() {
223 return true;
227 * Returns true if this database can use functional indexes
229 function functionalIndexes() {
230 return true;
234 * Returns a unique string representing the wiki on the server
236 function getWikiID() {
237 if( $this->mSchema ) {
238 return "{$this->mDBname}-{$this->mSchema}";
239 } else {
240 return $this->mDBname;
244 function getType() {
245 return 'ibm_db2';
248 ######################################
249 # Setup
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,
263 $password = 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 ) ) {
271 $wgOut = null;
273 $this->mFlags = DBO_TRX | $flags;
275 if ( $schema == self::USE_GLOBAL ) {
276 $this->mSchema = $wgDBmwschema;
277 } else {
278 $this->mSchema = $schema;
281 // configure the connection and statement objects
282 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
283 self::CONN_OPTION | self::STMT_OPTION );
284 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
285 self::STMT_OPTION );
286 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
287 self::STMT_OPTION );
289 $this->open( $server, $user, $password, $dbName );
293 * Enables options only if the ibm_db2 extension version supports them
294 * @param $name String: name of the option in the options array
295 * @param $const String: name of the constant holding the right option value
296 * @param $type Integer: whether this is a Connection or Statement otion
298 private function setDB2Option( $name, $const, $type ) {
299 if ( defined( $const ) ) {
300 if ( $type & self::CONN_OPTION ) {
301 $this->mConnOptions[$name] = constant( $const );
303 if ( $type & self::STMT_OPTION ) {
304 $this->mStmtOptions[$name] = constant( $const );
306 } else {
307 $this->installPrint(
308 "$const is not defined. ibm_db2 version is likely too low." );
313 * Outputs debug information in the appropriate place
314 * @param $string String: the relevant debug message
316 private function installPrint( $string ) {
317 wfDebug( "$string\n" );
318 if ( $this->mMode == self::INSTALL_MODE ) {
319 print "<li><pre>$string</pre></li>";
320 flush();
325 * Opens a database connection and returns it
326 * Closes any existing connection
328 * @param $server String: hostname
329 * @param $user String
330 * @param $password String
331 * @param $dbName String: database name
332 * @return a fresh connection
334 public function open( $server, $user, $password, $dbName ) {
335 // Load the port number
336 global $wgDBport;
337 wfProfileIn( __METHOD__ );
339 // Load IBM DB2 driver if missing
340 wfDl( 'ibm_db2' );
342 // Test for IBM DB2 support, to avoid suppressed fatal error
343 if ( !function_exists( 'db2_connect' ) ) {
344 $error = <<<ERROR
345 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
347 ERROR;
348 $this->installPrint( $error );
349 $this->reportConnectionError( $error );
352 if ( strlen( $user ) < 1 ) {
353 return null;
356 // Close existing connection
357 $this->close();
358 // Cache conn info
359 $this->mServer = $server;
360 $this->mPort = $port = $wgDBport;
361 $this->mUser = $user;
362 $this->mPassword = $password;
363 $this->mDBname = $dbName;
365 $this->openUncataloged( $dbName, $user, $password, $server, $port );
367 // Apply connection config
368 db2_set_option( $this->mConn, $this->mConnOptions, 1 );
369 // Some MediaWiki code is still transaction-less (?).
370 // The strategy is to keep AutoCommit on for that code
371 // but switch it off whenever a transaction is begun.
372 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
374 if ( !$this->mConn ) {
375 $this->installPrint( "DB connection error\n" );
376 $this->installPrint(
377 "Server: $server, Database: $dbName, User: $user, Password: "
378 . substr( $password, 0, 3 ) . "...\n" );
379 $this->installPrint( $this->lastError() . "\n" );
380 return null;
383 $this->mOpened = true;
384 $this->applySchema();
386 wfProfileOut( __METHOD__ );
387 return $this->mConn;
391 * Opens a cataloged database connection, sets mConn
393 protected function openCataloged( $dbName, $user, $password ) {
394 @$this->mConn = db2_pconnect( $dbName, $user, $password );
398 * Opens an uncataloged database connection, sets mConn
400 protected function openUncataloged( $dbName, $user, $password, $server, $port )
402 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
403 $str .= "DATABASE=$dbName;";
404 $str .= "HOSTNAME=$server;";
405 // port was formerly validated to not be 0
406 $str .= "PORT=$port;";
407 $str .= "PROTOCOL=TCPIP;";
408 $str .= "UID=$user;";
409 $str .= "PWD=$password;";
411 @$this->mConn = db2_pconnect( $str, $user, $password );
415 * Closes a database connection, if it is open
416 * Returns success, true if already closed
418 public function close() {
419 $this->mOpened = false;
420 if ( $this->mConn ) {
421 if ( $this->trxLevel() > 0 ) {
422 $this->commit();
424 return db2_close( $this->mConn );
425 } else {
426 return true;
431 * Retrieves the most current database error
432 * Forces a database rollback
434 public function lastError() {
435 $connerr = db2_conn_errormsg();
436 if ( $connerr ) {
437 //$this->rollback();
438 return $connerr;
440 $stmterr = db2_stmt_errormsg();
441 if ( $stmterr ) {
442 //$this->rollback();
443 return $stmterr;
446 return false;
450 * Get the last error number
451 * Return 0 if no error
452 * @return integer
454 public function lastErrno() {
455 $connerr = db2_conn_error();
456 if ( $connerr ) {
457 return $connerr;
459 $stmterr = db2_stmt_error();
460 if ( $stmterr ) {
461 return $stmterr;
463 return 0;
467 * Is a database connection open?
468 * @return
470 public function isOpen() { return $this->mOpened; }
473 * The DBMS-dependent part of query()
474 * @param $sql String: SQL query.
475 * @return object Result object for fetch functions or false on failure
476 * @access private
478 /*private*/
479 public function doQuery( $sql ) {
480 $this->applySchema();
482 $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
483 if( $ret == false ) {
484 $error = db2_stmt_errormsg();
485 $this->installPrint( "<pre>$sql</pre>" );
486 $this->installPrint( $error );
487 throw new DBUnexpectedError( $this, 'SQL error: '
488 . htmlspecialchars( $error ) );
490 $this->mLastResult = $ret;
491 $this->mAffectedRows = null; // Not calculated until asked for
492 return $ret;
496 * @return string Version information from the database
498 public function getServerVersion() {
499 $info = db2_server_info( $this->mConn );
500 return $info->DBMS_VER;
504 * Queries whether a given table exists
505 * @return boolean
507 public function tableExists( $table ) {
508 $schema = $this->mSchema;
509 $sql = <<< EOF
510 SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST
511 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
512 EOF;
513 $res = $this->query( $sql );
514 if ( !$res ) {
515 return false;
518 // If the table exists, there should be one of it
519 @$row = $this->fetchRow( $res );
520 $count = $row[0];
521 if ( $count == '1' || $count == 1 ) {
522 return true;
525 return false;
529 * Fetch the next row from the given result object, in object form.
530 * Fields can be retrieved with $row->fieldname, with fields acting like
531 * member variables.
533 * @param $res SQL result object as returned from Database::query(), etc.
534 * @return DB2 row object
535 * @throws DBUnexpectedError Thrown if the database returns an error
537 public function fetchObject( $res ) {
538 if ( $res instanceof ResultWrapper ) {
539 $res = $res->result;
541 @$row = db2_fetch_object( $res );
542 if( $this->lastErrno() ) {
543 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
544 . htmlspecialchars( $this->lastError() ) );
546 return $row;
550 * Fetch the next row from the given result object, in associative array
551 * form. Fields are retrieved with $row['fieldname'].
553 * @param $res SQL result object as returned from Database::query(), etc.
554 * @return DB2 row object
555 * @throws DBUnexpectedError Thrown if the database returns an error
557 public function fetchRow( $res ) {
558 if ( $res instanceof ResultWrapper ) {
559 $res = $res->result;
561 @$row = db2_fetch_array( $res );
562 if ( $this->lastErrno() ) {
563 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
564 . htmlspecialchars( $this->lastError() ) );
566 return $row;
570 * Create tables, stored procedures, and so on
572 public function setup_database() {
573 try {
574 // TODO: switch to root login if available
576 // Switch into the correct namespace
577 $this->applySchema();
578 $this->begin();
580 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
581 if ( $res !== true ) {
582 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
583 } else {
584 print ' done</li>';
586 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
587 if ( $res !== true ) {
588 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
589 } else {
590 print '<li>Foreign keys done</li>';
593 // TODO: populate interwiki links
595 if ( $this->lastError() ) {
596 $this->installPrint(
597 'Errors encountered during table creation -- rolled back' );
598 $this->installPrint( 'Please install again' );
599 $this->rollback();
600 } else {
601 $this->commit();
603 } catch ( MWException $mwe ) {
604 print "<br><pre>$mwe</pre><br>";
609 * Escapes strings
610 * Doesn't escape numbers
612 * @param $s String: string to escape
613 * @return escaped string
615 public function addQuotes( $s ) {
616 //$this->installPrint( "DB2::addQuotes( $s )\n" );
617 if ( is_null( $s ) ) {
618 return 'NULL';
619 } elseif ( $s instanceof Blob ) {
620 return "'" . $s->fetch( $s ) . "'";
621 } elseif ( $s instanceof IBM_DB2Blob ) {
622 return "'" . $this->decodeBlob( $s ) . "'";
624 $s = $this->strencode( $s );
625 if ( is_numeric( $s ) ) {
626 return $s;
627 } else {
628 return "'$s'";
633 * Verifies that a DB2 column/field type is numeric
635 * @param $type String: DB2 column type
636 * @return Boolean: true if numeric
638 public function is_numeric_type( $type ) {
639 switch ( strtoupper( $type ) ) {
640 case 'SMALLINT':
641 case 'INTEGER':
642 case 'INT':
643 case 'BIGINT':
644 case 'DECIMAL':
645 case 'REAL':
646 case 'DOUBLE':
647 case 'DECFLOAT':
648 return true;
650 return false;
654 * Alias for addQuotes()
655 * @param $s String: string to escape
656 * @return escaped string
658 public function strencode( $s ) {
659 // Bloody useless function
660 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
661 // But also necessary
662 $s = db2_escape_string( $s );
663 // Wide characters are evil -- some of them look like '
664 $s = utf8_encode( $s );
665 // Fix its stupidity
666 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
667 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
668 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
669 return $s;
673 * Switch into the database schema
675 protected function applySchema() {
676 if ( !( $this->mSchemaSet ) ) {
677 $this->mSchemaSet = true;
678 $this->begin();
679 $this->doQuery( "SET SCHEMA = $this->mSchema" );
680 $this->commit();
685 * Start a transaction (mandatory)
687 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
688 // BEGIN is implicit for DB2
689 // However, it requires that AutoCommit be off.
691 // Some MediaWiki code is still transaction-less (?).
692 // The strategy is to keep AutoCommit on for that code
693 // but switch it off whenever a transaction is begun.
694 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_OFF );
696 $this->mTrxLevel = 1;
700 * End a transaction
701 * Must have a preceding begin()
703 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
704 db2_commit( $this->mConn );
706 // Some MediaWiki code is still transaction-less (?).
707 // The strategy is to keep AutoCommit on for that code
708 // but switch it off whenever a transaction is begun.
709 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
711 $this->mTrxLevel = 0;
715 * Cancel a transaction
717 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
718 db2_rollback( $this->mConn );
719 // turn auto-commit back on
720 // not sure if this is appropriate
721 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
722 $this->mTrxLevel = 0;
726 * Makes an encoded list of strings from an array
727 * $mode:
728 * LIST_COMMA - comma separated, no field names
729 * LIST_AND - ANDed WHERE clause (without the WHERE)
730 * LIST_OR - ORed WHERE clause (without the WHERE)
731 * LIST_SET - comma separated with field names, like a SET clause
732 * LIST_NAMES - comma separated field names
733 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
735 function makeList( $a, $mode = LIST_COMMA ) {
736 if ( !is_array( $a ) ) {
737 throw new DBUnexpectedError( $this,
738 'DatabaseIbm_db2::makeList called with incorrect parameters' );
741 // if this is for a prepared UPDATE statement
742 // (this should be promoted to the parent class
743 // once other databases use prepared statements)
744 if ( $mode == LIST_SET_PREPARED ) {
745 $first = true;
746 $list = '';
747 foreach ( $a as $field => $value ) {
748 if ( !$first ) {
749 $list .= ", $field = ?";
750 } else {
751 $list .= "$field = ?";
752 $first = false;
755 $list .= '';
757 return $list;
760 // otherwise, call the usual function
761 return parent::makeList( $a, $mode );
765 * Construct a LIMIT query with optional offset
766 * This is used for query pages
768 * @param $sql string SQL query we will append the limit too
769 * @param $limit integer the SQL limit
770 * @param $offset integer the SQL offset (default false)
772 public function limitResult( $sql, $limit, $offset=false ) {
773 if( !is_numeric( $limit ) ) {
774 throw new DBUnexpectedError( $this,
775 "Invalid non-numeric limit passed to limitResult()\n" );
777 if( $offset ) {
778 if ( stripos( $sql, 'where' ) === false ) {
779 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
780 } else {
781 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
784 return "$sql FETCH FIRST $limit ROWS ONLY ";
788 * Handle reserved keyword replacement in table names
790 * @param $name Object
791 * @return String
793 public function tableName( $name ) {
794 // we want maximum compatibility with MySQL schema
795 return $name;
799 * Generates a timestamp in an insertable format
801 * @param $ts timestamp
802 * @return String: timestamp value
804 public function timestamp( $ts = 0 ) {
805 // TS_MW cannot be easily distinguished from an integer
806 return wfTimestamp( TS_DB2, $ts );
810 * Return the next in a sequence, save the value for retrieval via insertId()
811 * @param $seqName String: name of a defined sequence in the database
812 * @return next value in that sequence
814 public function nextSequenceValue( $seqName ) {
815 // Not using sequences in the primary schema to allow for easier migration
816 // from MySQL
817 // Emulating MySQL behaviour of using NULL to signal that sequences
818 // aren't used
820 $safeseq = preg_replace( "/'/", "''", $seqName );
821 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
822 $row = $this->fetchRow( $res );
823 $this->mInsertId = $row[0];
824 return $this->mInsertId;
826 return null;
830 * This must be called after nextSequenceVal
831 * @return Last sequence value used as a primary key
833 public function insertId() {
834 return $this->mInsertId;
838 * Updates the mInsertId property with the value of the last insert
839 * into a generated column
841 * @param $table String: sanitized table name
842 * @param $primaryKey Mixed: string name of the primary key
843 * @param $stmt Resource: prepared statement resource
844 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
846 private function calcInsertId( $table, $primaryKey, $stmt ) {
847 if ( $primaryKey ) {
848 $this->mInsertId = db2_last_insert_id( $this->mConn );
853 * INSERT wrapper, inserts an array into a table
855 * $args may be a single associative array, or an array of arrays
856 * with numeric keys, for multi-row insert
858 * @param $table String: Name of the table to insert to.
859 * @param $args Array: Items to insert into the table.
860 * @param $fname String: Name of the function, for profiling
861 * @param $options String or Array. Valid options: IGNORE
863 * @return bool Success of insert operation. IGNORE always returns true.
865 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
866 $options = array() )
868 if ( !count( $args ) ) {
869 return true;
871 // get database-specific table name (not used)
872 $table = $this->tableName( $table );
873 // format options as an array
874 $options = IBM_DB2Helper::makeArray( $options );
875 // format args as an array of arrays
876 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
877 $args = array( $args );
880 // prevent insertion of NULL into primary key columns
881 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
882 // if there's only one primary key
883 // we'll be able to read its value after insertion
884 $primaryKey = false;
885 if ( count( $primaryKeys ) == 1 ) {
886 $primaryKey = $primaryKeys[0];
889 // get column names
890 $keys = array_keys( $args[0] );
891 $key_count = count( $keys );
893 // If IGNORE is set, we use savepoints to emulate mysql's behavior
894 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
896 // assume success
897 $res = true;
898 // If we are not in a transaction, we need to be for savepoint trickery
899 if ( !$this->mTrxLevel ) {
900 $this->begin();
903 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
904 if ( $key_count == 1 ) {
905 $sql .= '( ? )';
906 } else {
907 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
909 //$this->installPrint( "Preparing the following SQL:" );
910 //$this->installPrint( "$sql" );
911 //$this->installPrint( print_r( $args, true ));
912 $stmt = $this->prepare( $sql );
914 // start a transaction/enter transaction mode
915 $this->begin();
917 if ( !$ignore ) {
918 //$first = true;
919 foreach ( $args as $row ) {
920 //$this->installPrint( "Inserting " . print_r( $row, true ));
921 // insert each row into the database
922 $res = $res & $this->execute( $stmt, $row );
923 if ( !$res ) {
924 $this->installPrint( 'Last error:' );
925 $this->installPrint( $this->lastError() );
927 // get the last inserted value into a generated column
928 $this->calcInsertId( $table, $primaryKey, $stmt );
930 } else {
931 $olde = error_reporting( 0 );
932 // For future use, we may want to track the number of actual inserts
933 // Right now, insert (all writes) simply return true/false
934 $numrowsinserted = 0;
936 // always return true
937 $res = true;
939 foreach ( $args as $row ) {
940 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
941 db2_exec( $this->mConn, $overhead, $this->mStmtOptions );
943 $this->execute( $stmt, $row );
945 if ( !$res2 ) {
946 $this->installPrint( 'Last error:' );
947 $this->installPrint( $this->lastError() );
949 // get the last inserted value into a generated column
950 $this->calcInsertId( $table, $primaryKey, $stmt );
952 $errNum = $this->lastErrno();
953 if ( $errNum ) {
954 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore",
955 $this->mStmtOptions );
956 } else {
957 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore",
958 $this->mStmtOptions );
959 $numrowsinserted++;
963 $olde = error_reporting( $olde );
964 // Set the affected row count for the whole operation
965 $this->mAffectedRows = $numrowsinserted;
967 // commit either way
968 $this->commit();
969 $this->freePrepared( $stmt );
971 return $res;
975 * Given a table name and a hash of columns with values
976 * Removes primary key columns from the hash where the value is NULL
978 * @param $table String: name of the table
979 * @param $args Array of hashes of column names with values
980 * @return Array: tuple( filtered array of columns, array of primary keys )
982 private function removeNullPrimaryKeys( $table, $args ) {
983 $schema = $this->mSchema;
984 // find out the primary keys
985 $keyres = db2_primary_keys( $this->mConn, null, strtoupper( $schema ),
986 strtoupper( $table )
988 $keys = array();
989 for (
990 $row = $this->fetchObject( $keyres );
991 $row != null;
992 $row = $this->fetchObject( $keyres )
995 $keys[] = strtolower( $row->column_name );
997 // remove primary keys
998 foreach ( $args as $ai => $row ) {
999 foreach ( $keys as $key ) {
1000 if ( $row[$key] == null ) {
1001 unset( $row[$key] );
1004 $args[$ai] = $row;
1006 // return modified hash
1007 return array( $args, $keys );
1011 * UPDATE wrapper, takes a condition array and a SET array
1013 * @param $table String: The table to UPDATE
1014 * @param $values An array of values to SET
1015 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1016 * @param $fname String: The Class::Function calling this function
1017 * ( for the log )
1018 * @param $options An array of UPDATE options, can be one or
1019 * more of IGNORE, LOW_PRIORITY
1020 * @return Boolean
1022 public function update( $table, $values, $conds, $fname = 'DatabaseIbm_db2::update',
1023 $options = array() )
1025 $table = $this->tableName( $table );
1026 $opts = $this->makeUpdateOptions( $options );
1027 $sql = "UPDATE $opts $table SET "
1028 . $this->makeList( $values, LIST_SET_PREPARED );
1029 if ( $conds != '*' ) {
1030 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1032 $stmt = $this->prepare( $sql );
1033 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1034 // assuming for now that an array with string keys will work
1035 // if not, convert to simple array first
1036 $result = $this->execute( $stmt, $values );
1037 $this->freePrepared( $stmt );
1039 return $result;
1043 * DELETE query wrapper
1045 * Use $conds == "*" to delete all rows
1047 public function delete( $table, $conds, $fname = 'DatabaseIbm_db2::delete' ) {
1048 if ( !$conds ) {
1049 throw new DBUnexpectedError( $this,
1050 'DatabaseIbm_db2::delete() called with no conditions' );
1052 $table = $this->tableName( $table );
1053 $sql = "DELETE FROM $table";
1054 if ( $conds != '*' ) {
1055 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1057 $result = $this->query( $sql, $fname );
1059 return $result;
1063 * Returns the number of rows affected by the last query or 0
1064 * @return Integer: the number of rows affected by the last query
1066 public function affectedRows() {
1067 if ( !is_null( $this->mAffectedRows ) ) {
1068 // Forced result for simulated queries
1069 return $this->mAffectedRows;
1071 if( empty( $this->mLastResult ) ) {
1072 return 0;
1074 return db2_num_rows( $this->mLastResult );
1078 * Simulates REPLACE with a DELETE followed by INSERT
1079 * @param $table Object
1080 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1081 * @param $rows Array: rows to insert
1082 * @param $fname String: name of the function for profiling
1083 * @return nothing
1085 function replace( $table, $uniqueIndexes, $rows,
1086 $fname = 'DatabaseIbm_db2::replace' )
1088 $table = $this->tableName( $table );
1090 if ( count( $rows )==0 ) {
1091 return;
1094 # Single row case
1095 if ( !is_array( reset( $rows ) ) ) {
1096 $rows = array( $rows );
1099 foreach( $rows as $row ) {
1100 # Delete rows which collide
1101 if ( $uniqueIndexes ) {
1102 $sql = "DELETE FROM $table WHERE ";
1103 $first = true;
1104 foreach ( $uniqueIndexes as $index ) {
1105 if ( $first ) {
1106 $first = false;
1107 $sql .= '( ';
1108 } else {
1109 $sql .= ' ) OR ( ';
1111 if ( is_array( $index ) ) {
1112 $first2 = true;
1113 foreach ( $index as $col ) {
1114 if ( $first2 ) {
1115 $first2 = false;
1116 } else {
1117 $sql .= ' AND ';
1119 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1121 } else {
1122 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1125 $sql .= ' )';
1126 $this->query( $sql, $fname );
1129 # Now insert the row
1130 $sql = "INSERT INTO $table ( "
1131 . $this->makeList( array_keys( $row ), LIST_NAMES )
1132 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA ) . ' )';
1133 $this->query( $sql, $fname );
1138 * Returns the number of rows in the result set
1139 * Has to be called right after the corresponding select query
1140 * @param $res Object result set
1141 * @return Integer: number of rows
1143 public function numRows( $res ) {
1144 if ( $res instanceof ResultWrapper ) {
1145 $res = $res->result;
1147 if ( $this->mNumRows ) {
1148 return $this->mNumRows;
1149 } else {
1150 return 0;
1155 * Moves the row pointer of the result set
1156 * @param $res Object: result set
1157 * @param $row Integer: row number
1158 * @return success or failure
1160 public function dataSeek( $res, $row ) {
1161 if ( $res instanceof ResultWrapper ) {
1162 $res = $res->result;
1164 return db2_fetch_row( $res, $row );
1168 # Fix notices in Block.php
1172 * Frees memory associated with a statement resource
1173 * @param $res Object: statement resource to free
1174 * @return Boolean success or failure
1176 public function freeResult( $res ) {
1177 if ( $res instanceof ResultWrapper ) {
1178 $res = $res->result;
1180 if ( !@db2_free_result( $res ) ) {
1181 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1186 * Returns the number of columns in a resource
1187 * @param $res Object: statement resource
1188 * @return Number of fields/columns in resource
1190 public function numFields( $res ) {
1191 if ( $res instanceof ResultWrapper ) {
1192 $res = $res->result;
1194 return db2_num_fields( $res );
1198 * Returns the nth column name
1199 * @param $res Object: statement resource
1200 * @param $n Integer: Index of field or column
1201 * @return String name of nth column
1203 public function fieldName( $res, $n ) {
1204 if ( $res instanceof ResultWrapper ) {
1205 $res = $res->result;
1207 return db2_field_name( $res, $n );
1211 * SELECT wrapper
1213 * @param $table Array or string, table name(s) (prefix auto-added)
1214 * @param $vars Array or string, field name(s) to be retrieved
1215 * @param $conds Array or string, condition(s) for WHERE
1216 * @param $fname String: calling function name (use __METHOD__)
1217 * for logs/profiling
1218 * @param $options Associative array of options
1219 * (e.g. array('GROUP BY' => 'page_title')),
1220 * see Database::makeSelectOptions code for list of
1221 * supported stuff
1222 * @param $join_conds Associative array of table join conditions (optional)
1223 * (e.g. array( 'page' => array('LEFT JOIN',
1224 * 'page_latest=rev_id') )
1225 * @return Mixed: database result resource for fetch functions or false
1226 * on failure
1228 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1230 $res = parent::select( $table, $vars, $conds, $fname, $options,
1231 $join_conds );
1233 // We must adjust for offset
1234 if ( isset( $options['LIMIT'] ) && isset ( $options['OFFSET'] ) ) {
1235 $limit = $options['LIMIT'];
1236 $offset = $options['OFFSET'];
1239 // DB2 does not have a proper num_rows() function yet, so we must emulate
1240 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1241 // a working one
1242 // TODO: Yay!
1244 // we want the count
1245 $vars2 = array( 'count( * ) as num_rows' );
1246 // respecting just the limit option
1247 $options2 = array();
1248 if ( isset( $options['LIMIT'] ) ) {
1249 $options2['LIMIT'] = $options['LIMIT'];
1251 // but don't try to emulate for GROUP BY
1252 if ( isset( $options['GROUP BY'] ) ) {
1253 return $res;
1256 $res2 = parent::select( $table, $vars2, $conds, $fname, $options2,
1257 $join_conds );
1258 $obj = $this->fetchObject( $res2 );
1259 $this->mNumRows = $obj->num_rows;
1261 return $res;
1265 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1266 * Has limited support for per-column options (colnum => 'DISTINCT')
1268 * @private
1270 * @param $options Associative array of options to be turned into
1271 * an SQL query, valid keys are listed in the function.
1272 * @return Array
1274 function makeSelectOptions( $options ) {
1275 $preLimitTail = $postLimitTail = '';
1276 $startOpts = '';
1278 $noKeyOptions = array();
1279 foreach ( $options as $key => $option ) {
1280 if ( is_numeric( $key ) ) {
1281 $noKeyOptions[$option] = true;
1285 if ( isset( $options['GROUP BY'] ) ) {
1286 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1288 if ( isset( $options['HAVING'] ) ) {
1289 $preLimitTail .= " HAVING {$options['HAVING']}";
1291 if ( isset( $options['ORDER BY'] ) ) {
1292 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1295 if ( isset( $noKeyOptions['DISTINCT'] )
1296 || isset( $noKeyOptions['DISTINCTROW'] ) )
1298 $startOpts .= 'DISTINCT';
1301 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1305 * Returns link to IBM DB2 free download
1306 * @return String: wikitext of a link to the server software's web site
1308 public static function getSoftwareLink() {
1309 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1313 * Get search engine class. All subclasses of this
1314 * need to implement this if they wish to use searching.
1316 * @return String
1318 public function getSearchEngine() {
1319 return 'SearchIBM_DB2';
1323 * Did the last database access fail because of deadlock?
1324 * @return Boolean
1326 public function wasDeadlock() {
1327 // get SQLSTATE
1328 $err = $this->lastErrno();
1329 switch( $err ) {
1330 // This is literal port of the MySQL logic and may be wrong for DB2
1331 case '40001': // sql0911n, Deadlock or timeout, rollback
1332 case '57011': // sql0904n, Resource unavailable, no rollback
1333 case '57033': // sql0913n, Deadlock or timeout, no rollback
1334 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1335 return true;
1337 return false;
1341 * Ping the server and try to reconnect if it there is no connection
1342 * The connection may be closed and reopened while this happens
1343 * @return Boolean: whether the connection exists
1345 public function ping() {
1346 // db2_ping() doesn't exist
1347 // Emulate
1348 $this->close();
1349 $this->mConn = $this->openUncataloged( $this->mDBName, $this->mUser,
1350 $this->mPassword, $this->mServer, $this->mPort );
1352 return false;
1354 ######################################
1355 # Unimplemented and not applicable
1356 ######################################
1358 * Not implemented
1359 * @return string ''
1361 public function getStatus( $which = '%' ) {
1362 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1363 return '';
1366 * Not implemented
1367 * @return string $sql
1369 public function limitResultForUpdate( $sql, $num ) {
1370 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1371 return $sql;
1375 * Only useful with fake prepare like in base Database class
1376 * @return string
1378 public function fillPreparedArg( $matches ) {
1379 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1380 return '';
1383 ######################################
1384 # Reflection
1385 ######################################
1388 * Returns information about an index
1389 * If errors are explicitly ignored, returns NULL on failure
1390 * @param $table String: table name
1391 * @param $index String: index name
1392 * @param $fname String: function name for logging and profiling
1393 * @return Object query row in object form
1395 public function indexInfo( $table, $index,
1396 $fname = 'DatabaseIbm_db2::indexExists' )
1398 $table = $this->tableName( $table );
1399 $sql = <<<SQL
1400 SELECT name as indexname
1401 FROM sysibm.sysindexes si
1402 WHERE si.name='$index' AND si.tbname='$table'
1403 AND sc.tbcreator='$this->mSchema'
1404 SQL;
1405 $res = $this->query( $sql, $fname );
1406 if ( !$res ) {
1407 return null;
1409 $row = $this->fetchObject( $res );
1410 if ( $row != null ) {
1411 return $row;
1412 } else {
1413 return false;
1418 * Returns an information object on a table column
1419 * @param $table String: table name
1420 * @param $field String: column name
1421 * @return IBM_DB2Field
1423 public function fieldInfo( $table, $field ) {
1424 return IBM_DB2Field::fromText( $this, $table, $field );
1428 * db2_field_type() wrapper
1429 * @param $res Object: result of executed statement
1430 * @param $index Mixed: number or name of the column
1431 * @return String column type
1433 public function fieldType( $res, $index ) {
1434 if ( $res instanceof ResultWrapper ) {
1435 $res = $res->result;
1437 return db2_field_type( $res, $index );
1441 * Verifies that an index was created as unique
1442 * @param $table String: table name
1443 * @param $index String: index name
1444 * @param $fname function name for profiling
1445 * @return Bool
1447 public function indexUnique ( $table, $index,
1448 $fname = 'DatabaseIbm_db2::indexUnique' )
1450 $table = $this->tableName( $table );
1451 $sql = <<<SQL
1452 SELECT si.name as indexname
1453 FROM sysibm.sysindexes si
1454 WHERE si.name='$index' AND si.tbname='$table'
1455 AND sc.tbcreator='$this->mSchema'
1456 AND si.uniquerule IN ( 'U', 'P' )
1457 SQL;
1458 $res = $this->query( $sql, $fname );
1459 if ( !$res ) {
1460 return null;
1462 if ( $this->fetchObject( $res ) ) {
1463 return true;
1465 return false;
1470 * Returns the size of a text field, or -1 for "unlimited"
1471 * @param $table String: table name
1472 * @param $field String: column name
1473 * @return Integer: length or -1 for unlimited
1475 public function textFieldSize( $table, $field ) {
1476 $table = $this->tableName( $table );
1477 $sql = <<<SQL
1478 SELECT length as size
1479 FROM sysibm.syscolumns sc
1480 WHERE sc.name='$field' AND sc.tbname='$table'
1481 AND sc.tbcreator='$this->mSchema'
1482 SQL;
1483 $res = $this->query( $sql );
1484 $row = $this->fetchObject( $res );
1485 $size = $row->size;
1486 return $size;
1490 * DELETE where the condition is a join
1491 * @param $delTable String: deleting from this table
1492 * @param $joinTable String: using data from this table
1493 * @param $delVar String: variable in deleteable table
1494 * @param $joinVar String: variable in data table
1495 * @param $conds Array: conditionals for join table
1496 * @param $fname String: function name for profiling
1498 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1499 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1501 if ( !$conds ) {
1502 throw new DBUnexpectedError( $this,
1503 'DatabaseIbm_db2::deleteJoin() called with empty $conds' );
1506 $delTable = $this->tableName( $delTable );
1507 $joinTable = $this->tableName( $joinTable );
1508 $sql = <<<SQL
1509 DELETE FROM $delTable
1510 WHERE $delVar IN (
1511 SELECT $joinVar FROM $joinTable
1513 SQL;
1514 if ( $conds != '*' ) {
1515 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1517 $sql .= ' )';
1519 $this->query( $sql, $fname );
1523 * Description is left as an exercise for the reader
1524 * @param $b Mixed: data to be encoded
1525 * @return IBM_DB2Blob
1527 public function encodeBlob( $b ) {
1528 return new IBM_DB2Blob( $b );
1532 * Description is left as an exercise for the reader
1533 * @param $b IBM_DB2Blob: data to be decoded
1534 * @return mixed
1536 public function decodeBlob( $b ) {
1537 return "$b";
1541 * Convert into a list of string being concatenated
1542 * @param $stringList Array: strings that need to be joined together
1543 * by the SQL engine
1544 * @return String: joined by the concatenation operator
1546 public function buildConcat( $stringList ) {
1547 // || is equivalent to CONCAT
1548 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1549 return implode( ' || ', $stringList );
1553 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1554 * @param $column String: name of timestamp column
1555 * @return String: SQL code
1557 public function extractUnixEpoch( $column ) {
1558 // TODO
1559 // see SpecialAncientpages
1562 ######################################
1563 # Prepared statements
1564 ######################################
1567 * Intended to be compatible with the PEAR::DB wrapper functions.
1568 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1570 * ? = scalar value, quoted as necessary
1571 * ! = raw SQL bit (a function for instance)
1572 * & = filename; reads the file and inserts as a blob
1573 * (we don't use this though...)
1574 * @param $sql String: SQL statement with appropriate markers
1575 * @param $func String: Name of the function, for profiling
1576 * @return resource a prepared DB2 SQL statement
1578 public function prepare( $sql, $func = 'DB2::prepare' ) {
1579 $stmt = db2_prepare( $this->mConn, $sql, $this->mStmtOptions );
1580 return $stmt;
1584 * Frees resources associated with a prepared statement
1585 * @return Boolean success or failure
1587 public function freePrepared( $prepared ) {
1588 return db2_free_stmt( $prepared );
1592 * Execute a prepared query with the various arguments
1593 * @param $prepared String: the prepared sql
1594 * @param $args Mixed: either an array here, or put scalars as varargs
1595 * @return Resource: results object
1597 public function execute( $prepared, $args = null ) {
1598 if( !is_array( $args ) ) {
1599 # Pull the var args
1600 $args = func_get_args();
1601 array_shift( $args );
1603 $res = db2_execute( $prepared, $args );
1604 if ( !$res ) {
1605 $this->installPrint( db2_stmt_errormsg() );
1607 return $res;
1611 * Prepare & execute an SQL statement, quoting and inserting arguments
1612 * in the appropriate places.
1613 * @param $query String
1614 * @param $args ...
1616 public function safeQuery( $query, $args = null ) {
1617 // copied verbatim from Database.php
1618 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1619 if( !is_array( $args ) ) {
1620 # Pull the var args
1621 $args = func_get_args();
1622 array_shift( $args );
1624 $retval = $this->execute( $prepared, $args );
1625 $this->freePrepared( $prepared );
1626 return $retval;
1630 * For faking prepared SQL statements on DBs that don't support
1631 * it directly.
1632 * @param $preparedQuery String: a 'preparable' SQL statement
1633 * @param $args Array of arguments to fill it with
1634 * @return String: executable statement
1636 public function fillPrepared( $preparedQuery, $args ) {
1637 reset( $args );
1638 $this->preparedArgs =& $args;
1640 foreach ( $args as $i => $arg ) {
1641 db2_bind_param( $preparedQuery, $i+1, $args[$i] );
1644 return $preparedQuery;
1648 * Switches module between regular and install modes
1650 public function setMode( $mode ) {
1651 $old = $this->mMode;
1652 $this->mMode = $mode;
1653 return $old;
1657 * Bitwise negation of a column or value in SQL
1658 * Same as (~field) in C
1659 * @param $field String
1660 * @return String
1662 function bitNot( $field ) {
1663 // expecting bit-fields smaller than 4bytes
1664 return "BITNOT( $field )";
1668 * Bitwise AND of two columns or values in SQL
1669 * Same as (fieldLeft & fieldRight) in C
1670 * @param $fieldLeft String
1671 * @param $fieldRight String
1672 * @return String
1674 function bitAnd( $fieldLeft, $fieldRight ) {
1675 return "BITAND( $fieldLeft, $fieldRight )";
1679 * Bitwise OR of two columns or values in SQL
1680 * Same as (fieldLeft | fieldRight) in C
1681 * @param $fieldLeft String
1682 * @param $fieldRight String
1683 * @return String
1685 function bitOr( $fieldLeft, $fieldRight ) {
1686 return "BITOR( $fieldLeft, $fieldRight )";
1690 class IBM_DB2Helper {
1691 public static function makeArray( $maybeArray ) {
1692 if ( !is_array( $maybeArray ) ) {
1693 return array( $maybeArray );
1696 return $maybeArray;