3 * This script is the IBM DB2 database abstraction layer
5 * See maintenance/ibm_db2/README for development notes and other specific information
8 * @author leo.petr+mediawiki@gmail.com
12 * This represents a column in a DB2 database
17 private $tablename = '';
19 private $nullable = false;
20 private $max_length = 0;
23 * Builder method for the class
24 * @param DatabaseIbm_db2 $db Database interface
25 * @param string $table table name
26 * @param string $field column name
27 * @return IBM_DB2Field
29 static function fromText($db, $table, $field) {
34 lcase(coltype) AS typname,
35 nulls AS attnotnull, length AS attlen
36 FROM sysibm.syscolumns
37 WHERE tbcreator=%s AND tbname=%s AND name=%s;
39 $res = $db->query(sprintf($q,
40 $db->addQuotes($wgDBmwschema),
41 $db->addQuotes($table),
42 $db->addQuotes($field)));
43 $row = $db->fetchObject($res);
46 $n = new IBM_DB2Field
;
47 $n->type
= $row->typname
;
48 $n->nullable
= ($row->attnotnull
== 'N');
50 $n->tablename
= $table;
51 $n->max_length
= $row->attlen
;
56 * @return string column name
58 function name() { return $this->name
; }
61 * @return string table name
63 function tableName() { return $this->tablename
; }
66 * @return string column type
68 function type() { return $this->type
; }
71 * @return bool true or false
73 function nullable() { return $this->nullable
; }
75 * How much can you fit in the column per row?
78 function maxLength() { return $this->max_length
; }
82 * Wrapper around binary large objects
88 public function __construct($data) {
92 public function getData() {
96 public function __toString()
103 * Primary database interface
106 class DatabaseIbm_db2
extends DatabaseBase
{
109 protected $mLastQuery = '';
110 protected $mPHPError = false;
112 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
113 protected $mOut, $mOpened = false;
115 protected $mFailFunction;
116 protected $mTablePrefix;
118 protected $mTrxLevel = 0;
119 protected $mErrorCount = 0;
120 protected $mLBInfo = array();
121 protected $mFakeSlaveLag = null, $mFakeMaster = false;
125 /// Server port for uncataloged connections
126 protected $mPort = null;
127 /// Whether connection is cataloged
128 protected $mCataloged = null;
129 /// Schema for tables, stored procedures, triggers
130 protected $mSchema = null;
131 /// Whether the schema has been applied in this session
132 protected $mSchemaSet = false;
133 /// Result of last query
134 protected $mLastResult = null;
135 /// Number of rows affected by last INSERT/UPDATE/DELETE
136 protected $mAffectedRows = null;
137 /// Number of rows returned by last SELECT
138 protected $mNumRows = null;
140 /// Connection config options - see constructor
141 public $mConnOptions = array();
142 /// Statement config options -- see constructor
143 public $mStmtOptions = array();
146 const CATALOGED
= "cataloged";
147 const UNCATALOGED
= "uncataloged";
148 const USE_GLOBAL
= "get from global";
150 const NONE_OPTION
= 0x00;
151 const CONN_OPTION
= 0x01;
152 const STMT_OPTION
= 0x02;
154 const REGULAR_MODE
= 'regular';
155 const INSTALL_MODE
= 'install';
157 // Whether this is regular operation or the initial installation
158 protected $mMode = self
::REGULAR_MODE
;
160 /// Last sequence value used for a primary key
161 protected $mInsertId = null;
164 * These can be safely inherited
166 * Getter/Setter: (18)
186 * Administrative: (8)
188 * installErrorHandler
189 * restoreErrorHandler
190 * connectionErrorHandler
191 * reportConnectionError
205 * Prepared Statement: 6
222 * tableNamesWithUseIndexOrJOIN
238 * These have been implemented
240 * Administrative: 7 / 7
243 * openCataloged [Done]
245 * newFromParams [Done]
246 * openUncataloged [Done]
247 * setup_database [Done]
249 * Getter/Setter: 13 / 13
250 * cascadingDeletes [Done]
251 * cleanupTriggers [Done]
253 * realTimestamps [Done]
254 * impliciGroupby [Done]
255 * implicitOrderby [Done]
256 * searchableIPs [Done]
257 * functionalIndexes [Done]
260 * getServerVersion [Done]
261 * getSoftwareLink [Done]
262 * getSearchEngine [Done]
264 * Database driver wrapper: 23 / 23
277 * affectedRows [Done]
290 * Slave/master: 2 / 2
291 * setFakeSlaveLag [Done]
292 * setFakeMaster [Done]
300 * textFieldSize [Done]
302 * Generation: 16 / 16
306 * makeSelectOptions [Done]
307 * estimateRowCount [Done]
308 * nextSequenceValue [Done]
309 * useIndexClause [Done]
312 * lowPriorityOption [Done]
314 * limitResultForUpdate [Done]
321 ######################################
322 # Getters and Setters
323 ######################################
326 * Returns true if this database supports (and uses) cascading deletes
328 function cascadingDeletes() {
333 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
335 function cleanupTriggers() {
340 * Returns true if this database is strict about what can be put into an IP field.
341 * Specifically, it uses a NULL value instead of an empty string.
343 function strictIPs() {
348 * Returns true if this database uses timestamps rather than integers
350 function realTimestamps() {
355 * Returns true if this database does an implicit sort when doing GROUP BY
357 function implicitGroupby() {
362 * Returns true if this database does an implicit order by when the column has an index
363 * For example: SELECT page_title FROM page LIMIT 1
365 function implicitOrderby() {
370 * Returns true if this database can do a native search on IP columns
371 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
373 function searchableIPs() {
378 * Returns true if this database can use functional indexes
380 function functionalIndexes() {
385 * Returns a unique string representing the wiki on the server
387 function getWikiID() {
388 if( $this->mSchema
) {
389 return "{$this->mDBname}-{$this->mSchema}";
391 return $this->mDBname
;
399 ######################################
401 ######################################
406 * @param string $server hostname of database server
407 * @param string $user username
408 * @param string $password
409 * @param string $dbName database name on the server
410 * @param function $failFunction (optional)
411 * @param integer $flags database behaviour flags (optional, unused)
413 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
414 $dbName = false, $failFunction = false, $flags = 0,
415 $schema = self
::USE_GLOBAL
)
418 global $wgOut, $wgDBmwschema;
419 # Can't get a reference if it hasn't been set yet
420 if ( !isset( $wgOut ) ) {
423 $this->mOut
=& $wgOut;
424 $this->mFailFunction
= $failFunction;
425 $this->mFlags
= DBO_TRX |
$flags;
427 if ( $schema == self
::USE_GLOBAL
) {
428 $this->mSchema
= $wgDBmwschema;
431 $this->mSchema
= $schema;
434 // configure the connection and statement objects
435 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
436 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
437 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
439 $this->open( $server, $user, $password, $dbName);
443 * Enables options only if the ibm_db2 extension version supports them
444 * @param string $name Name of the option in the options array
445 * @param string $const Name of the constant holding the right option value
446 * @param int $type Whether this is a Connection or Statement otion
448 private function setDB2Option($name, $const, $type) {
449 if (defined($const)) {
450 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
451 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
454 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
459 * Outputs debug information in the appropriate place
460 * @param string $string The relevant debug message
462 private function installPrint($string) {
464 if ($this->mMode
== self
::INSTALL_MODE
) {
465 print "<li>$string</li>";
471 * Opens a database connection and returns it
472 * Closes any existing connection
473 * @return a fresh connection
474 * @param string $server hostname
475 * @param string $user
476 * @param string $password
477 * @param string $dbName database name
479 public function open( $server, $user, $password, $dbName )
481 // Load the port number
482 global $wgDBport_db2, $wgDBcataloged;
483 wfProfileIn( __METHOD__
);
485 // Load IBM DB2 driver if missing
486 if (!@extension_loaded
('ibm_db2')) {
489 // Test for IBM DB2 support, to avoid suppressed fatal error
490 if ( !function_exists( 'db2_connect' ) ) {
491 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
492 $this->installPrint($error);
493 $this->reportConnectionError($error);
496 if (!strlen($user)) { // Copied from Postgres
500 // Close existing connection
503 $this->mServer
= $server;
504 $this->mPort
= $port = $wgDBport_db2;
505 $this->mUser
= $user;
506 $this->mPassword
= $password;
507 $this->mDBname
= $dbName;
508 $this->mCataloged
= $cataloged = $wgDBcataloged;
510 if ( $cataloged == self
::CATALOGED
) {
511 $this->openCataloged($dbName, $user, $password);
513 elseif ( $cataloged == self
::UNCATALOGED
) {
514 $this->openUncataloged($dbName, $user, $password, $server, $port);
516 // Apply connection config
517 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
518 // Not all MediaWiki code is transactional
519 // Rather, turn autocommit off in the begin function and turn on after a commit
520 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
522 if ( $this->mConn
== false ) {
523 $this->installPrint( "DB connection error\n" );
524 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
525 $this->installPrint( $this->lastError()."\n" );
529 $this->mOpened
= true;
530 $this->applySchema();
532 wfProfileOut( __METHOD__
);
537 * Opens a cataloged database connection, sets mConn
539 protected function openCataloged( $dbName, $user, $password )
541 @$this->mConn
= db2_connect($dbName, $user, $password);
545 * Opens an uncataloged database connection, sets mConn
547 protected function openUncataloged( $dbName, $user, $password, $server, $port )
549 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
550 $str .= "DATABASE=$dbName;";
551 $str .= "HOSTNAME=$server;";
552 if ($port) $str .= "PORT=$port;";
553 $str .= "PROTOCOL=TCPIP;";
554 $str .= "UID=$user;";
555 $str .= "PWD=$password;";
557 @$this->mConn
= db2_connect($str, $user, $password);
561 * Closes a database connection, if it is open
562 * Returns success, true if already closed
564 public function close() {
565 $this->mOpened
= false;
566 if ( $this->mConn
) {
567 if ($this->trxLevel() > 0) {
570 return db2_close( $this->mConn
);
578 * Returns a fresh instance of this class
581 * @param string $server hostname of database server
582 * @param string $user username
583 * @param string $password
584 * @param string $dbName database name on the server
585 * @param function $failFunction (optional)
586 * @param integer $flags database behaviour flags (optional, unused)
588 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
590 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
594 * Retrieves the most current database error
595 * Forces a database rollback
597 public function lastError() {
598 $connerr = db2_conn_errormsg();
603 $stmterr = db2_stmt_errormsg();
613 * Get the last error number
614 * Return 0 if no error
617 public function lastErrno() {
618 $connerr = db2_conn_error();
619 if ($connerr) return $connerr;
620 $stmterr = db2_stmt_error();
621 if ($stmterr) return $stmterr;
626 * Is a database connection open?
629 public function isOpen() { return $this->mOpened
; }
632 * The DBMS-dependent part of query()
633 * @param $sql String: SQL query.
634 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
638 public function doQuery( $sql ) {
639 //print "<li><pre>$sql</pre></li>";
640 // Switch into the correct namespace
641 $this->applySchema();
643 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
648 $error = db2_stmt_errormsg();
649 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
651 $this->mLastResult
= $ret;
652 $this->mAffectedRows
= null; // Not calculated until asked for
657 * @return string Version information from the database
659 public function getServerVersion() {
660 $info = db2_server_info( $this->mConn
);
661 return $info->DBMS_VER
;
665 * Queries whether a given table exists
668 public function tableExists( $table ) {
669 $schema = $this->mSchema
;
671 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
672 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
674 $res = $this->query( $sql );
675 if (!$res) return false;
677 // If the table exists, there should be one of it
678 @$row = $this->fetchRow($res);
680 if ($count == '1' or $count == 1) {
688 * Fetch the next row from the given result object, in object form.
689 * Fields can be retrieved with $row->fieldname, with fields acting like
692 * @param $res SQL result object as returned from Database::query(), etc.
693 * @return DB2 row object
694 * @throws DBUnexpectedError Thrown if the database returns an error
696 public function fetchObject( $res ) {
697 if ( $res instanceof ResultWrapper
) {
700 @$row = db2_fetch_object( $res );
701 if( $this->lastErrno() ) {
702 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
708 * Fetch the next row from the given result object, in associative array
709 * form. Fields are retrieved with $row['fieldname'].
711 * @param $res SQL result object as returned from Database::query(), etc.
712 * @return DB2 row object
713 * @throws DBUnexpectedError Thrown if the database returns an error
715 public function fetchRow( $res ) {
716 if ( $res instanceof ResultWrapper
) {
719 @$row = db2_fetch_array( $res );
720 if ( $this->lastErrno() ) {
721 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
727 * Override if introduced to base Database class
729 public function initial_setup() {
734 * Create tables, stored procedures, and so on
736 public function setup_database() {
737 // Timeout was being changed earlier due to mysterious crashes
738 // Changing it now may cause more problems than not changing it
739 //set_time_limit(240);
741 // TODO: switch to root login if available
743 // Switch into the correct namespace
744 $this->applySchema();
747 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
750 // TODO: update mediawiki_version table
752 // TODO: populate interwiki links
754 if ($this->lastError()) {
755 print "<li>Errors encountered during table creation -- rolled back</li>\n";
756 print "<li>Please install again</li>\n";
763 catch (MWException
$mwe)
765 print "<br><pre>$mwe</pre><br>";
771 * Doesn't escape numbers
772 * @param string s string to escape
773 * @return escaped string
775 public function addQuotes( $s ) {
776 //$this->installPrint("DB2::addQuotes($s)\n");
777 if ( is_null( $s ) ) {
779 } else if ($s instanceof Blob
) {
780 return "'".$s->fetch($s)."'";
781 } else if ($s instanceof IBM_DB2Blob
) {
782 return "'".$this->decodeBlob($s)."'";
784 $s = $this->strencode($s);
785 if ( is_numeric($s) ) {
794 * Verifies that a DB2 column/field type is numeric
795 * @return bool true if numeric
796 * @param string $type DB2 column type
798 public function is_numeric_type( $type ) {
799 switch (strtoupper($type)) {
814 * Alias for addQuotes()
815 * @param string s string to escape
816 * @return escaped string
818 public function strencode( $s ) {
819 // Bloody useless function
820 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
821 // But also necessary
822 $s = db2_escape_string($s);
823 // Wide characters are evil -- some of them look like '
824 $s = utf8_encode($s);
826 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
827 $to = array("\\", "''", "\n", "\t", '"', "\r");
828 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
833 * Switch into the database schema
835 protected function applySchema() {
836 if ( !($this->mSchemaSet
) ) {
837 $this->mSchemaSet
= true;
839 $this->doQuery("SET SCHEMA = $this->mSchema");
845 * Start a transaction (mandatory)
847 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
848 // turn off auto-commit
849 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
850 $this->mTrxLevel
= 1;
855 * Must have a preceding begin()
857 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
858 db2_commit($this->mConn
);
859 // turn auto-commit back on
860 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
861 $this->mTrxLevel
= 0;
865 * Cancel a transaction
867 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
868 db2_rollback($this->mConn
);
869 // turn auto-commit back on
870 // not sure if this is appropriate
871 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
872 $this->mTrxLevel
= 0;
876 * Makes an encoded list of strings from an array
878 * LIST_COMMA - comma separated, no field names
879 * LIST_AND - ANDed WHERE clause (without the WHERE)
880 * LIST_OR - ORed WHERE clause (without the WHERE)
881 * LIST_SET - comma separated with field names, like a SET clause
882 * LIST_NAMES - comma separated field names
884 public function makeList( $a, $mode = LIST_COMMA
) {
885 if ( !is_array( $a ) ) {
886 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
891 foreach ( $a as $field => $value ) {
893 if ( $mode == LIST_AND
) {
895 } elseif($mode == LIST_OR
) {
903 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
905 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
907 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
908 if( count( $value ) == 0 ) {
909 throw new MWException( __METHOD__
.': empty input' );
910 } elseif( count( $value ) == 1 ) {
911 // Special-case single values, as IN isn't terribly efficient
912 // Don't necessarily assume the single key is 0; we don't
913 // enforce linear numeric ordering on other arrays here.
914 $value = array_values( $value );
915 $list .= $field." = ".$this->addQuotes( $value[0] );
917 $list .= $field." IN (".$this->makeList($value).") ";
919 } elseif( is_null($value) ) {
920 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
921 $list .= "$field IS ";
922 } elseif ( $mode == LIST_SET
) {
923 $list .= "$field = ";
927 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
928 $list .= "$field = ";
930 if ( $mode == LIST_NAMES
) {
933 // Leo: Can't insert quoted numbers into numeric columns
934 // (?) Might cause other problems. May have to check column type before insertion.
935 else if ( is_numeric($value) ) {
939 $list .= $this->addQuotes( $value );
947 * Construct a LIMIT query with optional offset
948 * This is used for query pages
949 * $sql string SQL query we will append the limit too
950 * $limit integer the SQL limit
951 * $offset integer the SQL offset (default false)
953 public function limitResult($sql, $limit, $offset=false) {
954 if( !is_numeric($limit) ) {
955 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
958 $this->installPrint("Offset parameter not supported in limitResult()\n");
960 // TODO implement proper offset handling
961 // idea: get all the rows between 0 and offset, advance cursor to offset
962 return "$sql FETCH FIRST $limit ROWS ONLY ";
966 * Handle reserved keyword replacement in table names
968 * @param $name Object
970 public function tableName( $name ) {
971 # Replace reserved words with better ones
976 // return 'pagecontent';
980 // we want maximum compatibility with MySQL schema
985 * Generates a timestamp in an insertable format
986 * @return string timestamp value
987 * @param timestamp $ts
989 public function timestamp( $ts=0 ) {
990 // TS_MW cannot be easily distinguished from an integer
991 return wfTimestamp(TS_DB2
,$ts);
995 * Return the next in a sequence, save the value for retrieval via insertId()
996 * @param string seqName Name of a defined sequence in the database
997 * @return next value in that sequence
999 public function nextSequenceValue( $seqName ) {
1000 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1001 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1003 $safeseq = preg_replace( "/'/", "''", $seqName );
1004 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1005 $row = $this->fetchRow( $res );
1006 $this->mInsertId = $row[0];
1007 $this->freeResult( $res );
1008 return $this->mInsertId;
1014 * This must be called after nextSequenceVal
1015 * @return Last sequence value used as a primary key
1017 public function insertId() {
1018 return $this->mInsertId
;
1022 * Updates the mInsertId property with the value of the last insert into a generated column
1023 * @param string $table Sanitized table name
1024 * @param mixed $primaryKey String name of the primary key or a bool if this call is a do-nothing
1025 * @param resource $stmt Prepared statement resource
1026 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1028 private function calcInsertId($table, $primaryKey, $stmt) {
1030 $id_row = $this->fetchRow($stmt);
1031 $this->mInsertId
= $id_row[0];
1036 * INSERT wrapper, inserts an array into a table
1038 * $args may be a single associative array, or an array of these with numeric keys,
1039 * for multi-row insert
1041 * @param array $table String: Name of the table to insert to.
1042 * @param array $args Array: Items to insert into the table.
1043 * @param array $fname String: Name of the function, for profiling
1044 * @param mixed $options String or Array. Valid options: IGNORE
1046 * @return bool Success of insert operation. IGNORE always returns true.
1048 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1049 if ( !count( $args ) ) {
1052 // get database-specific table name (not used)
1053 $table = $this->tableName( $table );
1054 // format options as an array
1055 if ( !is_array( $options ) ) $options = array( $options );
1056 // format args as an array of arrays
1057 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1058 $args = array($args);
1060 // prevent insertion of NULL into primary key columns
1061 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1062 // if there's only one primary key
1063 // we'll be able to read its value after insertion
1064 $primaryKey = false;
1065 if (count($primaryKeys) == 1) {
1066 $primaryKey = $primaryKeys[0];
1070 $keys = array_keys( $args[0] );
1071 $key_count = count($keys);
1073 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1074 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1078 // If we are not in a transaction, we need to be for savepoint trickery
1080 if (! $this->mTrxLevel
) {
1085 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1086 switch($key_count) {
1092 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1094 // add logic to read back the new primary key value
1096 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1098 $stmt = $this->prepare($sql);
1100 // start a transaction/enter transaction mode
1105 foreach ( $args as $row ) {
1106 // insert each row into the database
1107 $res = $res & $this->execute($stmt, $row);
1108 // get the last inserted value into a generated column
1109 $this->calcInsertId($table, $primaryKey, $stmt);
1113 $olde = error_reporting( 0 );
1114 // For future use, we may want to track the number of actual inserts
1115 // Right now, insert (all writes) simply return true/false
1116 $numrowsinserted = 0;
1118 // always return true
1121 foreach ( $args as $row ) {
1122 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1123 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1125 $res2 = $this->execute($stmt, $row);
1126 // get the last inserted value into a generated column
1127 $this->calcInsertId($table, $primaryKey, $stmt);
1129 $errNum = $this->lastErrno();
1131 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1134 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1139 $olde = error_reporting( $olde );
1140 // Set the affected row count for the whole operation
1141 $this->mAffectedRows
= $numrowsinserted;
1143 // commit either way
1150 * Given a table name and a hash of columns with values
1151 * Removes primary key columns from the hash where the value is NULL
1153 * @param string $table Name of the table
1154 * @param array $args Array of hashes of column names with values
1155 * @return array Tuple containing filtered array of columns, array of primary keys
1157 private function removeNullPrimaryKeys($table, $args) {
1158 $schema = $this->mSchema
;
1159 // find out the primary keys
1160 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1162 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1163 $keys[] = strtolower($row->column_name
);
1165 // remove primary keys
1166 foreach ($args as $ai => $row) {
1167 foreach ($keys as $ki => $key) {
1168 if ($row[$key] == null) {
1174 // return modified hash
1175 return array($args, $keys);
1179 * UPDATE wrapper, takes a condition array and a SET array
1181 * @param string $table The table to UPDATE
1182 * @param array $values An array of values to SET
1183 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1184 * @param string $fname The Class::Function calling this function
1186 * @param array $options An array of UPDATE options, can be one or
1187 * more of IGNORE, LOW_PRIORITY
1190 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1191 $table = $this->tableName( $table );
1192 $opts = $this->makeUpdateOptions( $options );
1193 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1194 if ( $conds != '*' ) {
1195 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1197 return $this->query( $sql, $fname );
1201 * DELETE query wrapper
1203 * Use $conds == "*" to delete all rows
1205 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1207 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1209 $table = $this->tableName( $table );
1210 $sql = "DELETE FROM $table";
1211 if ( $conds != '*' ) {
1212 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1214 return $this->query( $sql, $fname );
1218 * Returns the number of rows affected by the last query or 0
1219 * @return int the number of rows affected by the last query
1221 public function affectedRows() {
1222 if ( !is_null( $this->mAffectedRows
) ) {
1223 // Forced result for simulated queries
1224 return $this->mAffectedRows
;
1226 if( empty( $this->mLastResult
) )
1228 return db2_num_rows( $this->mLastResult
);
1232 * Simulates REPLACE with a DELETE followed by INSERT
1233 * @param $table Object
1234 * @param array $uniqueIndexes array consisting of indexes and arrays of indexes
1235 * @param array $rows Rows to insert
1236 * @param string $fname Name of the function for profiling
1239 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1240 $table = $this->tableName( $table );
1242 if (count($rows)==0) {
1247 if ( !is_array( reset( $rows ) ) ) {
1248 $rows = array( $rows );
1251 foreach( $rows as $row ) {
1252 # Delete rows which collide
1253 if ( $uniqueIndexes ) {
1254 $sql = "DELETE FROM $table WHERE ";
1256 foreach ( $uniqueIndexes as $index ) {
1263 if ( is_array( $index ) ) {
1265 foreach ( $index as $col ) {
1271 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1274 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1278 $this->query( $sql, $fname );
1281 # Now insert the row
1282 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1283 $this->makeList( $row, LIST_COMMA
) . ')';
1284 $this->query( $sql, $fname );
1289 * Returns the number of rows in the result set
1290 * Has to be called right after the corresponding select query
1291 * @param object $res result set
1292 * @return int number of rows
1294 public function numRows( $res ) {
1295 if ( $res instanceof ResultWrapper
) {
1296 $res = $res->result
;
1298 if ( $this->mNumRows
) {
1299 return $this->mNumRows
;
1307 * Moves the row pointer of the result set
1308 * @param object $res result set
1309 * @param int $row row number
1310 * @return success or failure
1312 public function dataSeek( $res, $row ) {
1313 if ( $res instanceof ResultWrapper
) {
1314 $res = $res->result
;
1316 return db2_fetch_row( $res, $row );
1320 # Fix notices in Block.php
1324 * Frees memory associated with a statement resource
1325 * @param object $res Statement resource to free
1326 * @return bool success or failure
1328 public function freeResult( $res ) {
1329 if ( $res instanceof ResultWrapper
) {
1330 $res = $res->result
;
1332 if ( !@db2_free_result
( $res ) ) {
1333 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1338 * Returns the number of columns in a resource
1339 * @param object $res Statement resource
1340 * @return Number of fields/columns in resource
1342 public function numFields( $res ) {
1343 if ( $res instanceof ResultWrapper
) {
1344 $res = $res->result
;
1346 return db2_num_fields( $res );
1350 * Returns the nth column name
1351 * @param object $res Statement resource
1352 * @param int $n Index of field or column
1353 * @return string name of nth column
1355 public function fieldName( $res, $n ) {
1356 if ( $res instanceof ResultWrapper
) {
1357 $res = $res->result
;
1359 return db2_field_name( $res, $n );
1365 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1366 * @param mixed $vars Array or string, field name(s) to be retrieved
1367 * @param mixed $conds Array or string, condition(s) for WHERE
1368 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1369 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1370 * see Database::makeSelectOptions code for list of supported stuff
1371 * @param array $join_conds Associative array of table join conditions (optional)
1372 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1373 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1375 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1377 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1379 // We must adjust for offset
1380 if ( isset( $options['LIMIT'] ) ) {
1381 if ( isset ($options['OFFSET'] ) ) {
1382 $limit = $options['LIMIT'];
1383 $offset = $options['OFFSET'];
1388 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1389 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1392 // we want the count
1393 $vars2 = array('count(*) as num_rows');
1394 // respecting just the limit option
1395 $options2 = array();
1396 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1397 // but don't try to emulate for GROUP BY
1398 if ( isset( $options['GROUP BY'] ) ) return $res;
1400 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1401 $obj = $this->fetchObject($res2);
1402 $this->mNumRows
= $obj->num_rows
;
1409 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1410 * Has limited support for per-column options (colnum => 'DISTINCT')
1414 * @param array $options an associative array of options to be turned into
1415 * an SQL query, valid keys are listed in the function.
1418 function makeSelectOptions( $options ) {
1419 $preLimitTail = $postLimitTail = '';
1422 $noKeyOptions = array();
1423 foreach ( $options as $key => $option ) {
1424 if ( is_numeric( $key ) ) {
1425 $noKeyOptions[$option] = true;
1429 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1430 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1431 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1433 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1435 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1439 * Returns link to IBM DB2 free download
1440 * @return string wikitext of a link to the server software's web site
1442 public function getSoftwareLink() {
1443 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1447 * Get search engine class. All subclasses of this
1448 * need to implement this if they wish to use searching.
1452 public function getSearchEngine() {
1453 return "SearchIBM_DB2";
1457 * Did the last database access fail because of deadlock?
1460 public function wasDeadlock() {
1462 $err = $this->lastErrno();
1464 case '40001': // sql0911n, Deadlock or timeout, rollback
1465 case '57011': // sql0904n, Resource unavailable, no rollback
1466 case '57033': // sql0913n, Deadlock or timeout, no rollback
1467 $this->installPrint("In a deadlock because of SQLSTATE $err");
1474 * Ping the server and try to reconnect if it there is no connection
1475 * The connection may be closed and reopened while this happens
1476 * @return bool whether the connection exists
1478 public function ping() {
1479 // db2_ping() doesn't exist
1482 if ($this->mCataloged
== null) {
1485 else if ($this->mCataloged
) {
1486 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1488 else if (!$this->mCataloged
) {
1489 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1493 ######################################
1494 # Unimplemented and not applicable
1495 ######################################
1501 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1511 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1516 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1519 * @return string $sql
1522 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1525 * Only useful with fake prepare like in base Database class
1528 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1530 ######################################
1532 ######################################
1535 * Query whether a given column exists in the mediawiki schema
1536 * @param string $table name of the table
1537 * @param string $field name of the column
1538 * @param string $fname function name for logging and profiling
1540 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1541 $table = $this->tableName( $table );
1542 $schema = $this->mSchema
;
1543 $etable = preg_replace("/'/", "''", $table);
1544 $eschema = preg_replace("/'/", "''", $schema);
1545 $ecol = preg_replace("/'/", "''", $field);
1547 SELECT 1 as fieldexists
1548 FROM sysibm.syscolumns sc
1549 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1551 $res = $this->query( $sql, $fname );
1552 $count = $res ?
$this->numRows($res) : 0;
1554 $this->freeResult( $res );
1559 * Returns information about an index
1560 * If errors are explicitly ignored, returns NULL on failure
1561 * @param string $table table name
1562 * @param string $index index name
1564 * @return object query row in object form
1566 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1567 $table = $this->tableName( $table );
1569 SELECT name as indexname
1570 FROM sysibm.sysindexes si
1571 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1573 $res = $this->query( $sql, $fname );
1577 $row = $this->fetchObject( $res );
1578 if ($row != null) return $row;
1583 * Returns an information object on a table column
1584 * @param string $table table name
1585 * @param string $field column name
1586 * @return IBM_DB2Field
1588 public function fieldInfo( $table, $field ) {
1589 return IBM_DB2Field
::fromText($this, $table, $field);
1593 * db2_field_type() wrapper
1594 * @param object $res Result of executed statement
1595 * @param mixed $index number or name of the column
1596 * @return string column type
1598 public function fieldType( $res, $index ) {
1599 if ( $res instanceof ResultWrapper
) {
1600 $res = $res->result
;
1602 return db2_field_type( $res, $index );
1606 * Verifies that an index was created as unique
1607 * @param string $table table name
1608 * @param string $index index name
1609 * @param string $fnam function name for profiling
1612 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1613 $table = $this->tableName( $table );
1615 SELECT si.name as indexname
1616 FROM sysibm.sysindexes si
1617 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1618 AND si.uniquerule IN ('U', 'P')
1620 $res = $this->query( $sql, $fname );
1624 if ($this->fetchObject( $res )) {
1632 * Returns the size of a text field, or -1 for "unlimited"
1633 * @param string $table table name
1634 * @param string $field column name
1635 * @return int length or -1 for unlimited
1637 public function textFieldSize( $table, $field ) {
1638 $table = $this->tableName( $table );
1640 SELECT length as size
1641 FROM sysibm.syscolumns sc
1642 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1644 $res = $this->query($sql);
1645 $row = $this->fetchObject($res);
1647 $this->freeResult( $res );
1652 * DELETE where the condition is a join
1653 * @param string $delTable deleting from this table
1654 * @param string $joinTable using data from this table
1655 * @param string $delVar variable in deleteable table
1656 * @param string $joinVar variable in data table
1657 * @param array $conds conditionals for join table
1658 * @param string $fname function name for profiling
1660 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1662 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1665 $delTable = $this->tableName( $delTable );
1666 $joinTable = $this->tableName( $joinTable );
1667 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1668 if ( $conds != '*' ) {
1669 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1673 $this->query( $sql, $fname );
1677 * Description is left as an exercise for the reader
1678 * @param mixed $b data to be encoded
1679 * @return IBM_DB2Blob
1681 public function encodeBlob($b) {
1682 return new IBM_DB2Blob($b);
1686 * Description is left as an exercise for the reader
1687 * @param IBM_DB2Blob $b data to be decoded
1690 public function decodeBlob($b) {
1691 return $b->getData();
1695 * Convert into a list of string being concatenated
1696 * @param array $stringList strings that need to be joined together by the SQL engine
1697 * @return string joined by the concatenation operator
1699 public function buildConcat( $stringList ) {
1700 // || is equivalent to CONCAT
1701 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1702 return implode( ' || ', $stringList );
1706 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1707 * @param string $column name of timestamp column
1708 * @return string SQL code
1710 public function extractUnixEpoch( $column ) {
1712 // see SpecialAncientpages
1715 ######################################
1716 # Prepared statements
1717 ######################################
1720 * Intended to be compatible with the PEAR::DB wrapper functions.
1721 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1723 * ? = scalar value, quoted as necessary
1724 * ! = raw SQL bit (a function for instance)
1725 * & = filename; reads the file and inserts as a blob
1726 * (we don't use this though...)
1727 * @param string $sql SQL statement with appropriate markers
1728 * @return resource a prepared DB2 SQL statement
1730 public function prepare( $sql, $func = 'DB2::prepare' ) {
1731 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1736 * Frees resources associated with a prepared statement
1737 * @return bool success or failure
1739 public function freePrepared( $prepared ) {
1740 return db2_free_stmt($prepared);
1744 * Execute a prepared query with the various arguments
1745 * @param string $prepared the prepared sql
1746 * @param mixed $args Either an array here, or put scalars as varargs
1747 * @return resource Results object
1749 public function execute( $prepared, $args = null ) {
1750 if( !is_array( $args ) ) {
1752 $args = func_get_args();
1753 array_shift( $args );
1755 $res = db2_execute($prepared, $args);
1760 * Prepare & execute an SQL statement, quoting and inserting arguments
1761 * in the appropriate places.
1762 * @param $query String
1765 public function safeQuery( $query, $args = null ) {
1766 // copied verbatim from Database.php
1767 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1768 if( !is_array( $args ) ) {
1770 $args = func_get_args();
1771 array_shift( $args );
1773 $retval = $this->execute( $prepared, $args );
1774 $this->freePrepared( $prepared );
1779 * For faking prepared SQL statements on DBs that don't support
1781 * @param resource $preparedQuery String: a 'preparable' SQL statement
1782 * @param array $args Array of arguments to fill it with
1783 * @return string executable statement
1785 public function fillPrepared( $preparedQuery, $args ) {
1787 $this->preparedArgs
=& $args;
1789 foreach ($args as $i => $arg) {
1790 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1793 return $preparedQuery;
1797 * Switches module between regular and install modes
1799 public function setMode($mode) {
1800 $old = $this->mMode
;
1801 $this->mMode
= $mode;
1806 * Bitwise negation of a column or value in SQL
1807 * Same as (~field) in C
1808 * @param string $field
1811 function bitNot($field) {
1812 //expecting bit-fields smaller than 4bytes
1813 return 'BITNOT('.$bitField.')';
1817 * Bitwise AND of two columns or values in SQL
1818 * Same as (fieldLeft & fieldRight) in C
1819 * @param string $fieldLeft
1820 * @param string $fieldRight
1823 function bitAnd($fieldLeft, $fieldRight) {
1824 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1828 * Bitwise OR of two columns or values in SQL
1829 * Same as (fieldLeft | fieldRight) in C
1830 * @param string $fieldLeft
1831 * @param string $fieldRight
1834 function bitOr($fieldLeft, $fieldRight) {
1835 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';