* Installer for Oracle fixes
[mediawiki.git] / includes / db / DatabaseIbm_db2.php
blobb695d0b705542feff45043b5b6feadab3bd62963
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 {
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 nullable() { 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 $mOut, $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 DatabaseIbm_db2( $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->mOut =& $wgOut;
274 $this->mFlags = DBO_TRX | $flags;
276 if ( $schema == self::USE_GLOBAL ) {
277 $this->mSchema = $wgDBmwschema;
278 } else {
279 $this->mSchema = $schema;
282 // configure the connection and statement objects
283 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
284 self::CONN_OPTION | self::STMT_OPTION );
285 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
286 self::STMT_OPTION );
287 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
288 self::STMT_OPTION );
290 $this->open( $server, $user, $password, $dbName );
294 * Enables options only if the ibm_db2 extension version supports them
295 * @param $name String: name of the option in the options array
296 * @param $const String: name of the constant holding the right option value
297 * @param $type Integer: whether this is a Connection or Statement otion
299 private function setDB2Option( $name, $const, $type ) {
300 if ( defined( $const ) ) {
301 if ( $type & self::CONN_OPTION ) {
302 $this->mConnOptions[$name] = constant( $const );
304 if ( $type & self::STMT_OPTION ) {
305 $this->mStmtOptions[$name] = constant( $const );
307 } else {
308 $this->installPrint(
309 "$const is not defined. ibm_db2 version is likely too low." );
314 * Outputs debug information in the appropriate place
315 * @param $string String: the relevant debug message
317 private function installPrint( $string ) {
318 wfDebug( "$string\n" );
319 if ( $this->mMode == self::INSTALL_MODE ) {
320 print "<li><pre>$string</pre></li>";
321 flush();
326 * Opens a database connection and returns it
327 * Closes any existing connection
329 * @param $server String: hostname
330 * @param $user String
331 * @param $password String
332 * @param $dbName String: database name
333 * @return a fresh connection
335 public function open( $server, $user, $password, $dbName ) {
336 // Load the port number
337 global $wgDBport;
338 wfProfileIn( __METHOD__ );
340 // Load IBM DB2 driver if missing
341 wfDl( 'ibm_db2' );
343 // Test for IBM DB2 support, to avoid suppressed fatal error
344 if ( !function_exists( 'db2_connect' ) ) {
345 $error = <<<ERROR
346 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
348 ERROR;
349 $this->installPrint( $error );
350 $this->reportConnectionError( $error );
353 if ( strlen( $user ) < 1 ) {
354 return null;
357 // Close existing connection
358 $this->close();
359 // Cache conn info
360 $this->mServer = $server;
361 $this->mPort = $port = $wgDBport;
362 $this->mUser = $user;
363 $this->mPassword = $password;
364 $this->mDBname = $dbName;
366 $this->openUncataloged( $dbName, $user, $password, $server, $port );
368 // Apply connection config
369 db2_set_option( $this->mConn, $this->mConnOptions, 1 );
370 // Some MediaWiki code is still transaction-less (?).
371 // The strategy is to keep AutoCommit on for that code
372 // but switch it off whenever a transaction is begun.
373 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
375 if ( !$this->mConn ) {
376 $this->installPrint( "DB connection error\n" );
377 $this->installPrint(
378 "Server: $server, Database: $dbName, User: $user, Password: "
379 . substr( $password, 0, 3 ) . "...\n" );
380 $this->installPrint( $this->lastError() . "\n" );
381 return null;
384 $this->mOpened = true;
385 $this->applySchema();
387 wfProfileOut( __METHOD__ );
388 return $this->mConn;
392 * Opens a cataloged database connection, sets mConn
394 protected function openCataloged( $dbName, $user, $password ) {
395 @$this->mConn = db2_pconnect( $dbName, $user, $password );
399 * Opens an uncataloged database connection, sets mConn
401 protected function openUncataloged( $dbName, $user, $password, $server, $port )
403 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
404 $str .= "DATABASE=$dbName;";
405 $str .= "HOSTNAME=$server;";
406 // port was formerly validated to not be 0
407 $str .= "PORT=$port;";
408 $str .= "PROTOCOL=TCPIP;";
409 $str .= "UID=$user;";
410 $str .= "PWD=$password;";
412 @$this->mConn = db2_pconnect( $str, $user, $password );
416 * Closes a database connection, if it is open
417 * Returns success, true if already closed
419 public function close() {
420 $this->mOpened = false;
421 if ( $this->mConn ) {
422 if ( $this->trxLevel() > 0 ) {
423 $this->commit();
425 return db2_close( $this->mConn );
426 } else {
427 return true;
432 * Returns a fresh instance of this class
434 * @param $server String: hostname of database server
435 * @param $user String: username
436 * @param $password String
437 * @param $dbName String: database name on the server
438 * @param $flags Integer: database behaviour flags (optional, unused)
439 * @return DatabaseIbm_db2 object
441 static function newFromParams( $server, $user, $password, $dbName,
442 $flags = 0 )
444 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
445 $flags );
449 * Retrieves the most current database error
450 * Forces a database rollback
452 public function lastError() {
453 $connerr = db2_conn_errormsg();
454 if ( $connerr ) {
455 //$this->rollback();
456 return $connerr;
458 $stmterr = db2_stmt_errormsg();
459 if ( $stmterr ) {
460 //$this->rollback();
461 return $stmterr;
464 return false;
468 * Get the last error number
469 * Return 0 if no error
470 * @return integer
472 public function lastErrno() {
473 $connerr = db2_conn_error();
474 if ( $connerr ) {
475 return $connerr;
477 $stmterr = db2_stmt_error();
478 if ( $stmterr ) {
479 return $stmterr;
481 return 0;
485 * Is a database connection open?
486 * @return
488 public function isOpen() { return $this->mOpened; }
491 * The DBMS-dependent part of query()
492 * @param $sql String: SQL query.
493 * @return object Result object for fetch functions or false on failure
494 * @access private
496 /*private*/
497 public function doQuery( $sql ) {
498 $this->applySchema();
500 $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
501 if( $ret == false ) {
502 $error = db2_stmt_errormsg();
503 $this->installPrint( "<pre>$sql</pre>" );
504 $this->installPrint( $error );
505 throw new DBUnexpectedError( $this, 'SQL error: '
506 . htmlspecialchars( $error ) );
508 $this->mLastResult = $ret;
509 $this->mAffectedRows = null; // Not calculated until asked for
510 return $ret;
514 * @return string Version information from the database
516 public function getServerVersion() {
517 $info = db2_server_info( $this->mConn );
518 return $info->DBMS_VER;
522 * Queries whether a given table exists
523 * @return boolean
525 public function tableExists( $table ) {
526 $schema = $this->mSchema;
527 $sql = <<< EOF
528 SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST
529 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
530 EOF;
531 $res = $this->query( $sql );
532 if ( !$res ) {
533 return false;
536 // If the table exists, there should be one of it
537 @$row = $this->fetchRow( $res );
538 $count = $row[0];
539 if ( $count == '1' || $count == 1 ) {
540 return true;
543 return false;
547 * Fetch the next row from the given result object, in object form.
548 * Fields can be retrieved with $row->fieldname, with fields acting like
549 * member variables.
551 * @param $res SQL result object as returned from Database::query(), etc.
552 * @return DB2 row object
553 * @throws DBUnexpectedError Thrown if the database returns an error
555 public function fetchObject( $res ) {
556 if ( $res instanceof ResultWrapper ) {
557 $res = $res->result;
559 @$row = db2_fetch_object( $res );
560 if( $this->lastErrno() ) {
561 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
562 . htmlspecialchars( $this->lastError() ) );
564 return $row;
568 * Fetch the next row from the given result object, in associative array
569 * form. Fields are retrieved with $row['fieldname'].
571 * @param $res SQL result object as returned from Database::query(), etc.
572 * @return DB2 row object
573 * @throws DBUnexpectedError Thrown if the database returns an error
575 public function fetchRow( $res ) {
576 if ( $res instanceof ResultWrapper ) {
577 $res = $res->result;
579 @$row = db2_fetch_array( $res );
580 if ( $this->lastErrno() ) {
581 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
582 . htmlspecialchars( $this->lastError() ) );
584 return $row;
588 * Create tables, stored procedures, and so on
590 public function setup_database() {
591 try {
592 // TODO: switch to root login if available
594 // Switch into the correct namespace
595 $this->applySchema();
596 $this->begin();
598 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
599 if ( $res !== true ) {
600 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
601 } else {
602 print ' done</li>';
604 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
605 if ( $res !== true ) {
606 print ' <b>FAILED</b>: ' . htmlspecialchars( $res ) . '</li>';
607 } else {
608 print '<li>Foreign keys done</li>';
610 $res = null;
612 // TODO: populate interwiki links
614 if ( $this->lastError() ) {
615 $this->installPrint(
616 'Errors encountered during table creation -- rolled back' );
617 $this->installPrint( 'Please install again' );
618 $this->rollback();
619 } else {
620 $this->commit();
622 } catch ( MWException $mwe ) {
623 print "<br><pre>$mwe</pre><br>";
628 * Escapes strings
629 * Doesn't escape numbers
631 * @param $s String: string to escape
632 * @return escaped string
634 public function addQuotes( $s ) {
635 //$this->installPrint( "DB2::addQuotes( $s )\n" );
636 if ( is_null( $s ) ) {
637 return 'NULL';
638 } elseif ( $s instanceof Blob ) {
639 return "'" . $s->fetch( $s ) . "'";
640 } elseif ( $s instanceof IBM_DB2Blob ) {
641 return "'" . $this->decodeBlob( $s ) . "'";
643 $s = $this->strencode( $s );
644 if ( is_numeric( $s ) ) {
645 return $s;
646 } else {
647 return "'$s'";
652 * Verifies that a DB2 column/field type is numeric
654 * @param $type String: DB2 column type
655 * @return Boolean: true if numeric
657 public function is_numeric_type( $type ) {
658 switch ( strtoupper( $type ) ) {
659 case 'SMALLINT':
660 case 'INTEGER':
661 case 'INT':
662 case 'BIGINT':
663 case 'DECIMAL':
664 case 'REAL':
665 case 'DOUBLE':
666 case 'DECFLOAT':
667 return true;
669 return false;
673 * Alias for addQuotes()
674 * @param $s String: string to escape
675 * @return escaped string
677 public function strencode( $s ) {
678 // Bloody useless function
679 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
680 // But also necessary
681 $s = db2_escape_string( $s );
682 // Wide characters are evil -- some of them look like '
683 $s = utf8_encode( $s );
684 // Fix its stupidity
685 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
686 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
687 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
688 return $s;
692 * Switch into the database schema
694 protected function applySchema() {
695 if ( !( $this->mSchemaSet ) ) {
696 $this->mSchemaSet = true;
697 $this->begin();
698 $this->doQuery( "SET SCHEMA = $this->mSchema" );
699 $this->commit();
704 * Start a transaction (mandatory)
706 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
707 // BEGIN is implicit for DB2
708 // However, it requires that AutoCommit be off.
710 // Some MediaWiki code is still transaction-less (?).
711 // The strategy is to keep AutoCommit on for that code
712 // but switch it off whenever a transaction is begun.
713 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_OFF );
715 $this->mTrxLevel = 1;
719 * End a transaction
720 * Must have a preceding begin()
722 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
723 db2_commit( $this->mConn );
725 // Some MediaWiki code is still transaction-less (?).
726 // The strategy is to keep AutoCommit on for that code
727 // but switch it off whenever a transaction is begun.
728 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
730 $this->mTrxLevel = 0;
734 * Cancel a transaction
736 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
737 db2_rollback( $this->mConn );
738 // turn auto-commit back on
739 // not sure if this is appropriate
740 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
741 $this->mTrxLevel = 0;
745 * Makes an encoded list of strings from an array
746 * $mode:
747 * LIST_COMMA - comma separated, no field names
748 * LIST_AND - ANDed WHERE clause (without the WHERE)
749 * LIST_OR - ORed WHERE clause (without the WHERE)
750 * LIST_SET - comma separated with field names, like a SET clause
751 * LIST_NAMES - comma separated field names
752 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
754 function makeList( $a, $mode = LIST_COMMA ) {
755 if ( !is_array( $a ) ) {
756 throw new DBUnexpectedError( $this,
757 'DatabaseBase::makeList called with incorrect parameters' );
760 // if this is for a prepared UPDATE statement
761 // (this should be promoted to the parent class
762 // once other databases use prepared statements)
763 if ( $mode == LIST_SET_PREPARED ) {
764 $first = true;
765 $list = '';
766 foreach ( $a as $field => $value ) {
767 if ( !$first ) {
768 $list .= ", $field = ?";
769 } else {
770 $list .= "$field = ?";
771 $first = false;
774 $list .= '';
776 return $list;
779 // otherwise, call the usual function
780 return parent::makeList( $a, $mode );
784 * Construct a LIMIT query with optional offset
785 * This is used for query pages
787 * @param $sql string SQL query we will append the limit too
788 * @param $limit integer the SQL limit
789 * @param $offset integer the SQL offset (default false)
791 public function limitResult( $sql, $limit, $offset=false ) {
792 if( !is_numeric( $limit ) ) {
793 throw new DBUnexpectedError( $this,
794 "Invalid non-numeric limit passed to limitResult()\n" );
796 if( $offset ) {
797 if ( stripos( $sql, 'where' ) === false ) {
798 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
799 } else {
800 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
803 return "$sql FETCH FIRST $limit ROWS ONLY ";
807 * Handle reserved keyword replacement in table names
809 * @param $name Object
810 * @return String
812 public function tableName( $name ) {
813 // we want maximum compatibility with MySQL schema
814 return $name;
818 * Generates a timestamp in an insertable format
820 * @param $ts timestamp
821 * @return String: timestamp value
823 public function timestamp( $ts = 0 ) {
824 // TS_MW cannot be easily distinguished from an integer
825 return wfTimestamp( TS_DB2, $ts );
829 * Return the next in a sequence, save the value for retrieval via insertId()
830 * @param $seqName String: name of a defined sequence in the database
831 * @return next value in that sequence
833 public function nextSequenceValue( $seqName ) {
834 // Not using sequences in the primary schema to allow for easier migration
835 // from MySQL
836 // Emulating MySQL behaviour of using NULL to signal that sequences
837 // aren't used
839 $safeseq = preg_replace( "/'/", "''", $seqName );
840 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
841 $row = $this->fetchRow( $res );
842 $this->mInsertId = $row[0];
843 return $this->mInsertId;
845 return null;
849 * This must be called after nextSequenceVal
850 * @return Last sequence value used as a primary key
852 public function insertId() {
853 return $this->mInsertId;
857 * Updates the mInsertId property with the value of the last insert
858 * into a generated column
860 * @param $table String: sanitized table name
861 * @param $primaryKey Mixed: string name of the primary key
862 * @param $stmt Resource: prepared statement resource
863 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
865 private function calcInsertId( $table, $primaryKey, $stmt ) {
866 if ( $primaryKey ) {
867 $this->mInsertId = db2_last_insert_id( $this->mConn );
872 * INSERT wrapper, inserts an array into a table
874 * $args may be a single associative array, or an array of arrays
875 * with numeric keys, for multi-row insert
877 * @param $table String: Name of the table to insert to.
878 * @param $args Array: Items to insert into the table.
879 * @param $fname String: Name of the function, for profiling
880 * @param $options String or Array. Valid options: IGNORE
882 * @return bool Success of insert operation. IGNORE always returns true.
884 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
885 $options = array() )
887 if ( !count( $args ) ) {
888 return true;
890 // get database-specific table name (not used)
891 $table = $this->tableName( $table );
892 // format options as an array
893 $options = IBM_DB2Helper::makeArray( $options );
894 // format args as an array of arrays
895 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
896 $args = array( $args );
899 // prevent insertion of NULL into primary key columns
900 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
901 // if there's only one primary key
902 // we'll be able to read its value after insertion
903 $primaryKey = false;
904 if ( count( $primaryKeys ) == 1 ) {
905 $primaryKey = $primaryKeys[0];
908 // get column names
909 $keys = array_keys( $args[0] );
910 $key_count = count( $keys );
912 // If IGNORE is set, we use savepoints to emulate mysql's behavior
913 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
915 // assume success
916 $res = true;
917 // If we are not in a transaction, we need to be for savepoint trickery
918 if ( !$this->mTrxLevel ) {
919 $this->begin();
922 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
923 if ( $key_count == 1 ) {
924 $sql .= '( ? )';
925 } else {
926 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
928 //$this->installPrint( "Preparing the following SQL:" );
929 //$this->installPrint( "$sql" );
930 //$this->installPrint( print_r( $args, true ));
931 $stmt = $this->prepare( $sql );
933 // start a transaction/enter transaction mode
934 $this->begin();
936 if ( !$ignore ) {
937 //$first = true;
938 foreach ( $args as $row ) {
939 //$this->installPrint( "Inserting " . print_r( $row, true ));
940 // insert each row into the database
941 $res = $res & $this->execute( $stmt, $row );
942 if ( !$res ) {
943 $this->installPrint( 'Last error:' );
944 $this->installPrint( $this->lastError() );
946 // get the last inserted value into a generated column
947 $this->calcInsertId( $table, $primaryKey, $stmt );
949 } else {
950 $olde = error_reporting( 0 );
951 // For future use, we may want to track the number of actual inserts
952 // Right now, insert (all writes) simply return true/false
953 $numrowsinserted = 0;
955 // always return true
956 $res = true;
958 foreach ( $args as $row ) {
959 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
960 db2_exec( $this->mConn, $overhead, $this->mStmtOptions );
962 $this->execute( $stmt, $row );
964 if ( !$res2 ) {
965 $this->installPrint( 'Last error:' );
966 $this->installPrint( $this->lastError() );
968 // get the last inserted value into a generated column
969 $this->calcInsertId( $table, $primaryKey, $stmt );
971 $errNum = $this->lastErrno();
972 if ( $errNum ) {
973 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore",
974 $this->mStmtOptions );
975 } else {
976 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore",
977 $this->mStmtOptions );
978 $numrowsinserted++;
982 $olde = error_reporting( $olde );
983 // Set the affected row count for the whole operation
984 $this->mAffectedRows = $numrowsinserted;
986 // commit either way
987 $this->commit();
988 $this->freePrepared( $stmt );
990 return $res;
994 * Given a table name and a hash of columns with values
995 * Removes primary key columns from the hash where the value is NULL
997 * @param $table String: name of the table
998 * @param $args Array of hashes of column names with values
999 * @return Array: tuple( filtered array of columns, array of primary keys )
1001 private function removeNullPrimaryKeys( $table, $args ) {
1002 $schema = $this->mSchema;
1003 // find out the primary keys
1004 $keyres = db2_primary_keys( $this->mConn, null, strtoupper( $schema ),
1005 strtoupper( $table )
1007 $keys = array();
1008 for (
1009 $row = $this->fetchObject( $keyres );
1010 $row != null;
1011 $row = $this->fetchObject( $keyres )
1014 $keys[] = strtolower( $row->column_name );
1016 // remove primary keys
1017 foreach ( $args as $ai => $row ) {
1018 foreach ( $keys as $key ) {
1019 if ( $row[$key] == null ) {
1020 unset( $row[$key] );
1023 $args[$ai] = $row;
1025 // return modified hash
1026 return array( $args, $keys );
1030 * UPDATE wrapper, takes a condition array and a SET array
1032 * @param $table String: The table to UPDATE
1033 * @param $values An array of values to SET
1034 * @param $conds An array of conditions ( WHERE ). Use '*' to update all rows.
1035 * @param $fname String: The Class::Function calling this function
1036 * ( for the log )
1037 * @param $options An array of UPDATE options, can be one or
1038 * more of IGNORE, LOW_PRIORITY
1039 * @return Boolean
1041 public function update( $table, $values, $conds, $fname = 'Database::update',
1042 $options = array() )
1044 $table = $this->tableName( $table );
1045 $opts = $this->makeUpdateOptions( $options );
1046 $sql = "UPDATE $opts $table SET "
1047 . $this->makeList( $values, LIST_SET_PREPARED );
1048 if ( $conds != '*' ) {
1049 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1051 $stmt = $this->prepare( $sql );
1052 $this->installPrint( 'UPDATE: ' . print_r( $values, true ) );
1053 // assuming for now that an array with string keys will work
1054 // if not, convert to simple array first
1055 $result = $this->execute( $stmt, $values );
1056 $this->freePrepared( $stmt );
1058 return $result;
1062 * DELETE query wrapper
1064 * Use $conds == "*" to delete all rows
1066 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1067 if ( !$conds ) {
1068 throw new DBUnexpectedError( $this,
1069 'Database::delete() called with no conditions' );
1071 $table = $this->tableName( $table );
1072 $sql = "DELETE FROM $table";
1073 if ( $conds != '*' ) {
1074 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1076 $result = $this->query( $sql, $fname );
1078 return $result;
1082 * Returns the number of rows affected by the last query or 0
1083 * @return Integer: the number of rows affected by the last query
1085 public function affectedRows() {
1086 if ( !is_null( $this->mAffectedRows ) ) {
1087 // Forced result for simulated queries
1088 return $this->mAffectedRows;
1090 if( empty( $this->mLastResult ) ) {
1091 return 0;
1093 return db2_num_rows( $this->mLastResult );
1097 * Simulates REPLACE with a DELETE followed by INSERT
1098 * @param $table Object
1099 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1100 * @param $rows Array: rows to insert
1101 * @param $fname String: name of the function for profiling
1102 * @return nothing
1104 function replace( $table, $uniqueIndexes, $rows,
1105 $fname = 'DatabaseIbm_db2::replace' )
1107 $table = $this->tableName( $table );
1109 if ( count( $rows )==0 ) {
1110 return;
1113 # Single row case
1114 if ( !is_array( reset( $rows ) ) ) {
1115 $rows = array( $rows );
1118 foreach( $rows as $row ) {
1119 # Delete rows which collide
1120 if ( $uniqueIndexes ) {
1121 $sql = "DELETE FROM $table WHERE ";
1122 $first = true;
1123 foreach ( $uniqueIndexes as $index ) {
1124 if ( $first ) {
1125 $first = false;
1126 $sql .= '( ';
1127 } else {
1128 $sql .= ' ) OR ( ';
1130 if ( is_array( $index ) ) {
1131 $first2 = true;
1132 foreach ( $index as $col ) {
1133 if ( $first2 ) {
1134 $first2 = false;
1135 } else {
1136 $sql .= ' AND ';
1138 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1140 } else {
1141 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1144 $sql .= ' )';
1145 $this->query( $sql, $fname );
1148 # Now insert the row
1149 $sql = "INSERT INTO $table ( "
1150 . $this->makeList( array_keys( $row ), LIST_NAMES )
1151 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA ) . ' )';
1152 $this->query( $sql, $fname );
1157 * Returns the number of rows in the result set
1158 * Has to be called right after the corresponding select query
1159 * @param $res Object result set
1160 * @return Integer: number of rows
1162 public function numRows( $res ) {
1163 if ( $res instanceof ResultWrapper ) {
1164 $res = $res->result;
1166 if ( $this->mNumRows ) {
1167 return $this->mNumRows;
1168 } else {
1169 return 0;
1174 * Moves the row pointer of the result set
1175 * @param $res Object: result set
1176 * @param $row Integer: row number
1177 * @return success or failure
1179 public function dataSeek( $res, $row ) {
1180 if ( $res instanceof ResultWrapper ) {
1181 $res = $res->result;
1183 return db2_fetch_row( $res, $row );
1187 # Fix notices in Block.php
1191 * Frees memory associated with a statement resource
1192 * @param $res Object: statement resource to free
1193 * @return Boolean success or failure
1195 public function freeResult( $res ) {
1196 if ( $res instanceof ResultWrapper ) {
1197 $res = $res->result;
1199 if ( !@db2_free_result( $res ) ) {
1200 throw new DBUnexpectedError( $this, "Unable to free DB2 result\n" );
1205 * Returns the number of columns in a resource
1206 * @param $res Object: statement resource
1207 * @return Number of fields/columns in resource
1209 public function numFields( $res ) {
1210 if ( $res instanceof ResultWrapper ) {
1211 $res = $res->result;
1213 return db2_num_fields( $res );
1217 * Returns the nth column name
1218 * @param $res Object: statement resource
1219 * @param $n Integer: Index of field or column
1220 * @return String name of nth column
1222 public function fieldName( $res, $n ) {
1223 if ( $res instanceof ResultWrapper ) {
1224 $res = $res->result;
1226 return db2_field_name( $res, $n );
1230 * SELECT wrapper
1232 * @param $table Array or string, table name(s) (prefix auto-added)
1233 * @param $vars Array or string, field name(s) to be retrieved
1234 * @param $conds Array or string, condition(s) for WHERE
1235 * @param $fname String: calling function name (use __METHOD__)
1236 * for logs/profiling
1237 * @param $options Associative array of options
1238 * (e.g. array('GROUP BY' => 'page_title')),
1239 * see Database::makeSelectOptions code for list of
1240 * supported stuff
1241 * @param $join_conds Associative array of table join conditions (optional)
1242 * (e.g. array( 'page' => array('LEFT JOIN',
1243 * 'page_latest=rev_id') )
1244 * @return Mixed: database result resource for fetch functions or false
1245 * on failure
1247 public function select( $table, $vars, $conds = '', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1249 $res = parent::select( $table, $vars, $conds, $fname, $options,
1250 $join_conds );
1252 // We must adjust for offset
1253 if ( isset( $options['LIMIT'] ) ) {
1254 if ( isset ( $options['OFFSET'] ) ) {
1255 $limit = $options['LIMIT'];
1256 $offset = $options['OFFSET'];
1260 // DB2 does not have a proper num_rows() function yet, so we must emulate
1261 // DB2 9.5.4 and the corresponding ibm_db2 driver will introduce
1262 // a working one
1263 // TODO: Yay!
1265 // we want the count
1266 $vars2 = array( 'count( * ) as num_rows' );
1267 // respecting just the limit option
1268 $options2 = array();
1269 if ( isset( $options['LIMIT'] ) ) {
1270 $options2['LIMIT'] = $options['LIMIT'];
1272 // but don't try to emulate for GROUP BY
1273 if ( isset( $options['GROUP BY'] ) ) {
1274 return $res;
1277 $res2 = parent::select( $table, $vars2, $conds, $fname, $options2,
1278 $join_conds );
1279 $obj = $this->fetchObject( $res2 );
1280 $this->mNumRows = $obj->num_rows;
1282 return $res;
1286 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1287 * Has limited support for per-column options (colnum => 'DISTINCT')
1289 * @private
1291 * @param $options Associative array of options to be turned into
1292 * an SQL query, valid keys are listed in the function.
1293 * @return Array
1295 function makeSelectOptions( $options ) {
1296 $preLimitTail = $postLimitTail = '';
1297 $startOpts = '';
1299 $noKeyOptions = array();
1300 foreach ( $options as $key => $option ) {
1301 if ( is_numeric( $key ) ) {
1302 $noKeyOptions[$option] = true;
1306 if ( isset( $options['GROUP BY'] ) ) {
1307 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1309 if ( isset( $options['HAVING'] ) ) {
1310 $preLimitTail .= " HAVING {$options['HAVING']}";
1312 if ( isset( $options['ORDER BY'] ) ) {
1313 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1316 if ( isset( $noKeyOptions['DISTINCT'] )
1317 || isset( $noKeyOptions['DISTINCTROW'] ) )
1319 $startOpts .= 'DISTINCT';
1322 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1326 * Returns link to IBM DB2 free download
1327 * @return String: wikitext of a link to the server software's web site
1329 public static function getSoftwareLink() {
1330 return '[http://www.ibm.com/db2/express/ IBM DB2]';
1334 * Get search engine class. All subclasses of this
1335 * need to implement this if they wish to use searching.
1337 * @return String
1339 public function getSearchEngine() {
1340 return 'SearchIBM_DB2';
1344 * Did the last database access fail because of deadlock?
1345 * @return Boolean
1347 public function wasDeadlock() {
1348 // get SQLSTATE
1349 $err = $this->lastErrno();
1350 switch( $err ) {
1351 // This is literal port of the MySQL logic and may be wrong for DB2
1352 case '40001': // sql0911n, Deadlock or timeout, rollback
1353 case '57011': // sql0904n, Resource unavailable, no rollback
1354 case '57033': // sql0913n, Deadlock or timeout, no rollback
1355 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1356 return true;
1358 return false;
1362 * Ping the server and try to reconnect if it there is no connection
1363 * The connection may be closed and reopened while this happens
1364 * @return Boolean: whether the connection exists
1366 public function ping() {
1367 // db2_ping() doesn't exist
1368 // Emulate
1369 $this->close();
1370 $this->mConn = $this->openUncataloged( $this->mDBName, $this->mUser,
1371 $this->mPassword, $this->mServer, $this->mPort );
1373 return false;
1375 ######################################
1376 # Unimplemented and not applicable
1377 ######################################
1379 * Not implemented
1380 * @return string ''
1382 public function getStatus( $which = '%' ) {
1383 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1384 return '';
1387 * Not implemented
1388 * @return string $sql
1390 public function limitResultForUpdate( $sql, $num ) {
1391 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1392 return $sql;
1396 * Only useful with fake prepare like in base Database class
1397 * @return string
1399 public function fillPreparedArg( $matches ) {
1400 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1401 return '';
1404 ######################################
1405 # Reflection
1406 ######################################
1409 * Returns information about an index
1410 * If errors are explicitly ignored, returns NULL on failure
1411 * @param $table String: table name
1412 * @param $index String: index name
1413 * @param $fname String: function name for logging and profiling
1414 * @return Object query row in object form
1416 public function indexInfo( $table, $index,
1417 $fname = 'DatabaseIbm_db2::indexExists' )
1419 $table = $this->tableName( $table );
1420 $sql = <<<SQL
1421 SELECT name as indexname
1422 FROM sysibm.sysindexes si
1423 WHERE si.name='$index' AND si.tbname='$table'
1424 AND sc.tbcreator='$this->mSchema'
1425 SQL;
1426 $res = $this->query( $sql, $fname );
1427 if ( !$res ) {
1428 return null;
1430 $row = $this->fetchObject( $res );
1431 if ( $row != null ) {
1432 return $row;
1433 } else {
1434 return false;
1439 * Returns an information object on a table column
1440 * @param $table String: table name
1441 * @param $field String: column name
1442 * @return IBM_DB2Field
1444 public function fieldInfo( $table, $field ) {
1445 return IBM_DB2Field::fromText( $this, $table, $field );
1449 * db2_field_type() wrapper
1450 * @param $res Object: result of executed statement
1451 * @param $index Mixed: number or name of the column
1452 * @return String column type
1454 public function fieldType( $res, $index ) {
1455 if ( $res instanceof ResultWrapper ) {
1456 $res = $res->result;
1458 return db2_field_type( $res, $index );
1462 * Verifies that an index was created as unique
1463 * @param $table String: table name
1464 * @param $index String: index name
1465 * @param $fname function name for profiling
1466 * @return Bool
1468 public function indexUnique ( $table, $index,
1469 $fname = 'Database::indexUnique' )
1471 $table = $this->tableName( $table );
1472 $sql = <<<SQL
1473 SELECT si.name as indexname
1474 FROM sysibm.sysindexes si
1475 WHERE si.name='$index' AND si.tbname='$table'
1476 AND sc.tbcreator='$this->mSchema'
1477 AND si.uniquerule IN ( 'U', 'P' )
1478 SQL;
1479 $res = $this->query( $sql, $fname );
1480 if ( !$res ) {
1481 return null;
1483 if ( $this->fetchObject( $res ) ) {
1484 return true;
1486 return false;
1491 * Returns the size of a text field, or -1 for "unlimited"
1492 * @param $table String: table name
1493 * @param $field String: column name
1494 * @return Integer: length or -1 for unlimited
1496 public function textFieldSize( $table, $field ) {
1497 $table = $this->tableName( $table );
1498 $sql = <<<SQL
1499 SELECT length as size
1500 FROM sysibm.syscolumns sc
1501 WHERE sc.name='$field' AND sc.tbname='$table'
1502 AND sc.tbcreator='$this->mSchema'
1503 SQL;
1504 $res = $this->query( $sql );
1505 $row = $this->fetchObject( $res );
1506 $size = $row->size;
1507 return $size;
1511 * DELETE where the condition is a join
1512 * @param $delTable String: deleting from this table
1513 * @param $joinTable String: using data from this table
1514 * @param $delVar String: variable in deleteable table
1515 * @param $joinVar String: variable in data table
1516 * @param $conds Array: conditionals for join table
1517 * @param $fname String: function name for profiling
1519 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar,
1520 $conds, $fname = "DatabaseIbm_db2::deleteJoin" )
1522 if ( !$conds ) {
1523 throw new DBUnexpectedError( $this,
1524 'Database::deleteJoin() called with empty $conds' );
1527 $delTable = $this->tableName( $delTable );
1528 $joinTable = $this->tableName( $joinTable );
1529 $sql = <<<SQL
1530 DELETE FROM $delTable
1531 WHERE $delVar IN (
1532 SELECT $joinVar FROM $joinTable
1534 SQL;
1535 if ( $conds != '*' ) {
1536 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1538 $sql .= ' )';
1540 $this->query( $sql, $fname );
1544 * Description is left as an exercise for the reader
1545 * @param $b Mixed: data to be encoded
1546 * @return IBM_DB2Blob
1548 public function encodeBlob( $b ) {
1549 return new IBM_DB2Blob( $b );
1553 * Description is left as an exercise for the reader
1554 * @param $b IBM_DB2Blob: data to be decoded
1555 * @return mixed
1557 public function decodeBlob( $b ) {
1558 return "$b";
1562 * Convert into a list of string being concatenated
1563 * @param $stringList Array: strings that need to be joined together
1564 * by the SQL engine
1565 * @return String: joined by the concatenation operator
1567 public function buildConcat( $stringList ) {
1568 // || is equivalent to CONCAT
1569 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1570 return implode( ' || ', $stringList );
1574 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1575 * @param $column String: name of timestamp column
1576 * @return String: SQL code
1578 public function extractUnixEpoch( $column ) {
1579 // TODO
1580 // see SpecialAncientpages
1583 ######################################
1584 # Prepared statements
1585 ######################################
1588 * Intended to be compatible with the PEAR::DB wrapper functions.
1589 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1591 * ? = scalar value, quoted as necessary
1592 * ! = raw SQL bit (a function for instance)
1593 * & = filename; reads the file and inserts as a blob
1594 * (we don't use this though...)
1595 * @param $sql String: SQL statement with appropriate markers
1596 * @param $func String: Name of the function, for profiling
1597 * @return resource a prepared DB2 SQL statement
1599 public function prepare( $sql, $func = 'DB2::prepare' ) {
1600 $stmt = db2_prepare( $this->mConn, $sql, $this->mStmtOptions );
1601 return $stmt;
1605 * Frees resources associated with a prepared statement
1606 * @return Boolean success or failure
1608 public function freePrepared( $prepared ) {
1609 return db2_free_stmt( $prepared );
1613 * Execute a prepared query with the various arguments
1614 * @param $prepared String: the prepared sql
1615 * @param $args Mixed: either an array here, or put scalars as varargs
1616 * @return Resource: results object
1618 public function execute( $prepared, $args = null ) {
1619 if( !is_array( $args ) ) {
1620 # Pull the var args
1621 $args = func_get_args();
1622 array_shift( $args );
1624 $res = db2_execute( $prepared, $args );
1625 if ( !$res ) {
1626 $this->installPrint( db2_stmt_errormsg() );
1628 return $res;
1632 * Prepare & execute an SQL statement, quoting and inserting arguments
1633 * in the appropriate places.
1634 * @param $query String
1635 * @param $args ...
1637 public function safeQuery( $query, $args = null ) {
1638 // copied verbatim from Database.php
1639 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1640 if( !is_array( $args ) ) {
1641 # Pull the var args
1642 $args = func_get_args();
1643 array_shift( $args );
1645 $retval = $this->execute( $prepared, $args );
1646 $this->freePrepared( $prepared );
1647 return $retval;
1651 * For faking prepared SQL statements on DBs that don't support
1652 * it directly.
1653 * @param $preparedQuery String: a 'preparable' SQL statement
1654 * @param $args Array of arguments to fill it with
1655 * @return String: executable statement
1657 public function fillPrepared( $preparedQuery, $args ) {
1658 reset( $args );
1659 $this->preparedArgs =& $args;
1661 foreach ( $args as $i => $arg ) {
1662 db2_bind_param( $preparedQuery, $i+1, $args[$i] );
1665 return $preparedQuery;
1669 * Switches module between regular and install modes
1671 public function setMode( $mode ) {
1672 $old = $this->mMode;
1673 $this->mMode = $mode;
1674 return $old;
1678 * Bitwise negation of a column or value in SQL
1679 * Same as (~field) in C
1680 * @param $field String
1681 * @return String
1683 function bitNot( $field ) {
1684 // expecting bit-fields smaller than 4bytes
1685 return "BITNOT( $field )";
1689 * Bitwise AND of two columns or values in SQL
1690 * Same as (fieldLeft & fieldRight) in C
1691 * @param $fieldLeft String
1692 * @param $fieldRight String
1693 * @return String
1695 function bitAnd( $fieldLeft, $fieldRight ) {
1696 return "BITAND( $fieldLeft, $fieldRight )";
1700 * Bitwise OR of two columns or values in SQL
1701 * Same as (fieldLeft | fieldRight) in C
1702 * @param $fieldLeft String
1703 * @param $fieldRight String
1704 * @return String
1706 function bitOr( $fieldLeft, $fieldRight ) {
1707 return "BITOR( $fieldLeft, $fieldRight )";
1711 class IBM_DB2Helper {
1712 public static function makeArray( $maybeArray ) {
1713 if ( !is_array( $maybeArray ) ) {
1714 return array( $maybeArray );
1717 return $maybeArray;