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 function __construct($data) {
98 * Primary database interface
101 class DatabaseIbm_db2
extends DatabaseBase
{
104 protected $mLastQuery = '';
105 protected $mPHPError = false;
107 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
108 protected $mOut, $mOpened = false;
110 protected $mFailFunction;
111 protected $mTablePrefix;
113 protected $mTrxLevel = 0;
114 protected $mErrorCount = 0;
115 protected $mLBInfo = array();
116 protected $mFakeSlaveLag = null, $mFakeMaster = false;
120 /// Server port for uncataloged connections
121 protected $mPort = NULL;
122 /// Whether connection is cataloged
123 protected $mCataloged = NULL;
124 /// Schema for tables, stored procedures, triggers
125 protected $mSchema = NULL;
126 /// Whether the schema has been applied in this session
127 protected $mSchemaSet = false;
128 /// Result of last query
129 protected $mLastResult = NULL;
130 /// Number of rows affected by last INSERT/UPDATE/DELETE
131 protected $mAffectedRows = NULL;
132 /// Number of rows returned by last SELECT
133 protected $mNumRows = NULL;
135 /// Connection config options - see constructor
136 public $mConnOptions = array();
137 /// Statement config options -- see constructor
138 public $mStmtOptions = array();
141 const CATALOGED
= "cataloged";
142 const UNCATALOGED
= "uncataloged";
143 const USE_GLOBAL
= "get from global";
145 const NONE_OPTION
= 0x00;
146 const CONN_OPTION
= 0x01;
147 const STMT_OPTION
= 0x02;
149 const REGULAR_MODE
= 'regular';
150 const INSTALL_MODE
= 'install';
152 // Whether this is regular operation or the initial installation
153 protected $mMode = self
::REGULAR_MODE
;
155 /// Last sequence value used for a primary key
156 protected $mInsertId = NULL;
159 * These can be safely inherited
161 * Getter/Setter: (18)
181 * Administrative: (8)
183 * installErrorHandler
184 * restoreErrorHandler
185 * connectionErrorHandler
186 * reportConnectionError
200 * Prepared Statement: 6
217 * tableNamesWithUseIndexOrJOIN
233 * These have been implemented
235 * Administrative: 7 / 7
238 * openCataloged [Done]
240 * newFromParams [Done]
241 * openUncataloged [Done]
242 * setup_database [Done]
244 * Getter/Setter: 13 / 13
245 * cascadingDeletes [Done]
246 * cleanupTriggers [Done]
248 * realTimestamps [Done]
249 * impliciGroupby [Done]
250 * implicitOrderby [Done]
251 * searchableIPs [Done]
252 * functionalIndexes [Done]
255 * getServerVersion [Done]
256 * getSoftwareLink [Done]
257 * getSearchEngine [Done]
259 * Database driver wrapper: 23 / 23
272 * affectedRows [Done]
285 * Slave/master: 2 / 2
286 * setFakeSlaveLag [Done]
287 * setFakeMaster [Done]
295 * textFieldSize [Done]
297 * Generation: 16 / 16
301 * makeSelectOptions [Done]
302 * estimateRowCount [Done]
303 * nextSequenceValue [Done]
304 * useIndexClause [Done]
307 * lowPriorityOption [Done]
309 * limitResultForUpdate [Done]
316 ######################################
317 # Getters and Setters
318 ######################################
321 * Returns true if this database supports (and uses) cascading deletes
323 function cascadingDeletes() {
328 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
330 function cleanupTriggers() {
335 * Returns true if this database is strict about what can be put into an IP field.
336 * Specifically, it uses a NULL value instead of an empty string.
338 function strictIPs() {
343 * Returns true if this database uses timestamps rather than integers
345 function realTimestamps() {
350 * Returns true if this database does an implicit sort when doing GROUP BY
352 function implicitGroupby() {
357 * Returns true if this database does an implicit order by when the column has an index
358 * For example: SELECT page_title FROM page LIMIT 1
360 function implicitOrderby() {
365 * Returns true if this database can do a native search on IP columns
366 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
368 function searchableIPs() {
373 * Returns true if this database can use functional indexes
375 function functionalIndexes() {
380 * Returns a unique string representing the wiki on the server
382 function getWikiID() {
383 if( $this->mSchema
) {
384 return "{$this->mDBname}-{$this->mSchema}";
386 return $this->mDBname
;
391 ######################################
393 ######################################
398 * @param string $server hostname of database server
399 * @param string $user username
400 * @param string $password
401 * @param string $dbName database name on the server
402 * @param function $failFunction (optional)
403 * @param integer $flags database behaviour flags (optional, unused)
405 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
406 $dbName = false, $failFunction = false, $flags = 0,
407 $schema = self
::USE_GLOBAL
)
410 global $wgOut, $wgDBmwschema;
411 # Can't get a reference if it hasn't been set yet
412 if ( !isset( $wgOut ) ) {
415 $this->mOut
=& $wgOut;
416 $this->mFailFunction
= $failFunction;
417 $this->mFlags
= DBO_TRX |
$flags;
419 if ( $schema == self
::USE_GLOBAL
) {
420 $this->mSchema
= $wgDBmwschema;
423 $this->mSchema
= $schema;
426 // configure the connection and statement objects
427 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
428 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
429 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
431 $this->open( $server, $user, $password, $dbName);
435 * Enables options only if the ibm_db2 extension version supports them
436 * @param string $name Name of the option in the options array
437 * @param string $const Name of the constant holding the right option value
438 * @param int $type Whether this is a Connection or Statement otion
440 private function setDB2Option($name, $const, $type) {
441 if (defined($const)) {
442 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
443 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
446 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
451 * Outputs debug information in the appropriate place
452 * @param string $string The relevant debug message
454 private function installPrint($string) {
456 if ($this->mMode
== self
::INSTALL_MODE
) {
457 print "<li>$string</li>";
463 * Opens a database connection and returns it
464 * Closes any existing connection
465 * @return a fresh connection
466 * @param string $server hostname
467 * @param string $user
468 * @param string $password
469 * @param string $dbName database name
471 public function open( $server, $user, $password, $dbName )
473 // Load the port number
474 global $wgDBport_db2, $wgDBcataloged;
475 wfProfileIn( __METHOD__
);
477 // Load IBM DB2 driver if missing
478 if (!@extension_loaded
('ibm_db2')) {
481 // Test for IBM DB2 support, to avoid suppressed fatal error
482 if ( !function_exists( 'db2_connect' ) ) {
483 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
484 $this->installPrint($error);
485 $this->reportConnectionError($error);
488 if (!strlen($user)) { // Copied from Postgres
492 // Close existing connection
495 $this->mServer
= $server;
496 $this->mPort
= $port = $wgDBport_db2;
497 $this->mUser
= $user;
498 $this->mPassword
= $password;
499 $this->mDBname
= $dbName;
500 $this->mCataloged
= $cataloged = $wgDBcataloged;
502 if ( $cataloged == self
::CATALOGED
) {
503 $this->openCataloged($dbName, $user, $password);
505 elseif ( $cataloged == self
::UNCATALOGED
) {
506 $this->openUncataloged($dbName, $user, $password, $server, $port);
508 // Apply connection config
509 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
510 // Not all MediaWiki code is transactional
511 // Rather, turn autocommit off in the begin function and turn on after a commit
512 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
514 if ( $this->mConn
== false ) {
515 $this->installPrint( "DB connection error\n" );
516 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
517 $this->installPrint( $this->lastError()."\n" );
521 $this->mOpened
= true;
522 $this->applySchema();
524 wfProfileOut( __METHOD__
);
529 * Opens a cataloged database connection, sets mConn
531 protected function openCataloged( $dbName, $user, $password )
533 @$this->mConn
= db2_connect($dbName, $user, $password);
537 * Opens an uncataloged database connection, sets mConn
539 protected function openUncataloged( $dbName, $user, $password, $server, $port )
541 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
542 $str .= "DATABASE=$dbName;";
543 $str .= "HOSTNAME=$server;";
544 if ($port) $str .= "PORT=$port;";
545 $str .= "PROTOCOL=TCPIP;";
546 $str .= "UID=$user;";
547 $str .= "PWD=$password;";
549 @$this->mConn
= db2_connect($str, $user, $password);
553 * Closes a database connection, if it is open
554 * Returns success, true if already closed
556 public function close() {
557 $this->mOpened
= false;
558 if ( $this->mConn
) {
559 if ($this->trxLevel() > 0) {
562 return db2_close( $this->mConn
);
570 * Returns a fresh instance of this class
573 * @param string $server hostname of database server
574 * @param string $user username
575 * @param string $password
576 * @param string $dbName database name on the server
577 * @param function $failFunction (optional)
578 * @param integer $flags database behaviour flags (optional, unused)
580 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
582 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
586 * Retrieves the most current database error
587 * Forces a database rollback
589 public function lastError() {
590 $connerr = db2_conn_errormsg();
595 $stmterr = db2_stmt_errormsg();
605 * Get the last error number
606 * Return 0 if no error
609 public function lastErrno() {
610 $connerr = db2_conn_error();
611 if ($connerr) return $connerr;
612 $stmterr = db2_stmt_error();
613 if ($stmterr) return $stmterr;
618 * Is a database connection open?
621 public function isOpen() { return $this->mOpened
; }
624 * The DBMS-dependent part of query()
625 * @param $sql String: SQL query.
626 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
630 public function doQuery( $sql ) {
631 //print "<li><pre>$sql</pre></li>";
632 // Switch into the correct namespace
633 $this->applySchema();
635 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
640 $error = db2_stmt_errormsg();
641 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
643 $this->mLastResult
= $ret;
644 $this->mAffectedRows
= NULL; // Not calculated until asked for
649 * @return string Version information from the database
651 public function getServerVersion() {
652 $info = db2_server_info( $this->mConn
);
653 return $info->DBMS_VER
;
657 * Queries whether a given table exists
660 public function tableExists( $table ) {
661 $schema = $this->mSchema
;
663 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
664 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
666 $res = $this->query( $sql );
667 if (!$res) return false;
669 // If the table exists, there should be one of it
670 @$row = $this->fetchRow($res);
672 if ($count == '1' or $count == 1) {
680 * Fetch the next row from the given result object, in object form.
681 * Fields can be retrieved with $row->fieldname, with fields acting like
684 * @param $res SQL result object as returned from Database::query(), etc.
685 * @return DB2 row object
686 * @throws DBUnexpectedError Thrown if the database returns an error
688 public function fetchObject( $res ) {
689 if ( $res instanceof ResultWrapper
) {
692 @$row = db2_fetch_object( $res );
693 if( $this->lastErrno() ) {
694 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
700 * Fetch the next row from the given result object, in associative array
701 * form. Fields are retrieved with $row['fieldname'].
703 * @param $res SQL result object as returned from Database::query(), etc.
704 * @return DB2 row object
705 * @throws DBUnexpectedError Thrown if the database returns an error
707 public function fetchRow( $res ) {
708 if ( $res instanceof ResultWrapper
) {
711 @$row = db2_fetch_array( $res );
712 if ( $this->lastErrno() ) {
713 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
719 * Override if introduced to base Database class
721 public function initial_setup() {
726 * Create tables, stored procedures, and so on
728 public function setup_database() {
729 // Timeout was being changed earlier due to mysterious crashes
730 // Changing it now may cause more problems than not changing it
731 //set_time_limit(240);
733 // TODO: switch to root login if available
735 // Switch into the correct namespace
736 $this->applySchema();
739 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
742 // TODO: update mediawiki_version table
744 // TODO: populate interwiki links
746 if ($this->lastError()) {
747 print "<li>Errors encountered during table creation -- rolled back</li>\n";
748 print "<li>Please install again</li>\n";
755 catch (MWException
$mwe)
757 print "<br><pre>$mwe</pre><br>";
763 * Doesn't escape numbers
764 * @param string s string to escape
765 * @return escaped string
767 public function addQuotes( $s ) {
768 //$this->installPrint("DB2::addQuotes($s)\n");
769 if ( is_null( $s ) ) {
771 } else if ($s instanceof Blob
) {
772 return "'".$s->fetch($s)."'";
774 $s = $this->strencode($s);
775 if ( is_numeric($s) ) {
784 * Verifies that a DB2 column/field type is numeric
785 * @return bool true if numeric
786 * @param string $type DB2 column type
788 public function is_numeric_type( $type ) {
789 switch (strtoupper($type)) {
804 * Alias for addQuotes()
805 * @param string s string to escape
806 * @return escaped string
808 public function strencode( $s ) {
809 // Bloody useless function
810 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
811 // But also necessary
812 $s = db2_escape_string($s);
813 // Wide characters are evil -- some of them look like '
814 $s = utf8_encode($s);
816 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
817 $to = array("\\", "''", "\n", "\t", '"', "\r");
818 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
823 * Switch into the database schema
825 protected function applySchema() {
826 if ( !($this->mSchemaSet
) ) {
827 $this->mSchemaSet
= true;
829 $this->doQuery("SET SCHEMA = $this->mSchema");
835 * Start a transaction (mandatory)
837 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
838 // turn off auto-commit
839 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
840 $this->mTrxLevel
= 1;
845 * Must have a preceding begin()
847 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
848 db2_commit($this->mConn
);
849 // turn auto-commit back on
850 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
851 $this->mTrxLevel
= 0;
855 * Cancel a transaction
857 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
858 db2_rollback($this->mConn
);
859 // turn auto-commit back on
860 // not sure if this is appropriate
861 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
862 $this->mTrxLevel
= 0;
866 * Makes an encoded list of strings from an array
868 * LIST_COMMA - comma separated, no field names
869 * LIST_AND - ANDed WHERE clause (without the WHERE)
870 * LIST_OR - ORed WHERE clause (without the WHERE)
871 * LIST_SET - comma separated with field names, like a SET clause
872 * LIST_NAMES - comma separated field names
874 public function makeList( $a, $mode = LIST_COMMA
) {
875 if ( !is_array( $a ) ) {
876 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
881 foreach ( $a as $field => $value ) {
883 if ( $mode == LIST_AND
) {
885 } elseif($mode == LIST_OR
) {
893 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
895 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
897 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
898 if( count( $value ) == 0 ) {
899 throw new MWException( __METHOD__
.': empty input' );
900 } elseif( count( $value ) == 1 ) {
901 // Special-case single values, as IN isn't terribly efficient
902 // Don't necessarily assume the single key is 0; we don't
903 // enforce linear numeric ordering on other arrays here.
904 $value = array_values( $value );
905 $list .= $field." = ".$this->addQuotes( $value[0] );
907 $list .= $field." IN (".$this->makeList($value).") ";
909 } elseif( is_null($value) ) {
910 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
911 $list .= "$field IS ";
912 } elseif ( $mode == LIST_SET
) {
913 $list .= "$field = ";
917 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
918 $list .= "$field = ";
920 if ( $mode == LIST_NAMES
) {
923 // Leo: Can't insert quoted numbers into numeric columns
924 // (?) Might cause other problems. May have to check column type before insertion.
925 else if ( is_numeric($value) ) {
929 $list .= $this->addQuotes( $value );
937 * Construct a LIMIT query with optional offset
938 * This is used for query pages
939 * $sql string SQL query we will append the limit too
940 * $limit integer the SQL limit
941 * $offset integer the SQL offset (default false)
943 public function limitResult($sql, $limit, $offset=false) {
944 if( !is_numeric($limit) ) {
945 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
948 $this->installPrint("Offset parameter not supported in limitResult()\n");
950 // TODO implement proper offset handling
951 // idea: get all the rows between 0 and offset, advance cursor to offset
952 return "$sql FETCH FIRST $limit ROWS ONLY ";
956 * Handle reserved keyword replacement in table names
958 * @param $name Object
960 public function tableName( $name ) {
961 # Replace reserved words with better ones
966 // return 'pagecontent';
970 // we want maximum compatibility with MySQL schema
975 * Generates a timestamp in an insertable format
976 * @return string timestamp value
977 * @param timestamp $ts
979 public function timestamp( $ts=0 ) {
980 // TS_MW cannot be easily distinguished from an integer
981 return wfTimestamp(TS_DB2
,$ts);
985 * Return the next in a sequence, save the value for retrieval via insertId()
986 * @param string seqName Name of a defined sequence in the database
987 * @return next value in that sequence
989 public function nextSequenceValue( $seqName ) {
990 // Not using sequences in the primary schema to allow for easy third-party migration scripts
991 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
993 $safeseq = preg_replace( "/'/", "''", $seqName );
994 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
995 $row = $this->fetchRow( $res );
996 $this->mInsertId = $row[0];
997 $this->freeResult( $res );
998 return $this->mInsertId;
1004 * This must be called after nextSequenceVal
1005 * @return Last sequence value used as a primary key
1007 public function insertId() {
1008 return $this->mInsertId
;
1012 * Updates the mInsertId property with the value of the last insert into a generated column
1013 * @param string $table Sanitized table name
1014 * @param mixed $primaryKey String name of the primary key or a bool if this call is a do-nothing
1015 * @param resource $stmt Prepared statement resource
1016 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1018 private function calcInsertId($table, $primaryKey, $stmt) {
1020 $id_row = $this->fetchRow($stmt);
1021 $this->mInsertId
= $id_row[0];
1026 * INSERT wrapper, inserts an array into a table
1028 * $args may be a single associative array, or an array of these with numeric keys,
1029 * for multi-row insert
1031 * @param array $table String: Name of the table to insert to.
1032 * @param array $args Array: Items to insert into the table.
1033 * @param array $fname String: Name of the function, for profiling
1034 * @param mixed $options String or Array. Valid options: IGNORE
1036 * @return bool Success of insert operation. IGNORE always returns true.
1038 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1039 if ( !count( $args ) ) {
1042 // get database-specific table name (not used)
1043 $table = $this->tableName( $table );
1044 // format options as an array
1045 if ( !is_array( $options ) ) $options = array( $options );
1046 // format args as an array of arrays
1047 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1048 $args = array($args);
1050 // prevent insertion of NULL into primary key columns
1051 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1052 // if there's only one primary key
1053 // we'll be able to read its value after insertion
1054 $primaryKey = false;
1055 if (count($primaryKeys) == 1) {
1056 $primaryKey = $primaryKeys[0];
1060 $keys = array_keys( $args[0] );
1061 $key_count = count($keys);
1063 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1064 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1068 // If we are not in a transaction, we need to be for savepoint trickery
1070 if (! $this->mTrxLevel
) {
1075 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1076 switch($key_count) {
1082 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1084 // add logic to read back the new primary key value
1086 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1088 $stmt = $this->prepare($sql);
1090 // start a transaction/enter transaction mode
1095 foreach ( $args as $row ) {
1096 // insert each row into the database
1097 $res = $res & $this->execute($stmt, $row);
1098 // get the last inserted value into a generated column
1099 $this->calcInsertId($table, $primaryKey, $stmt);
1103 $olde = error_reporting( 0 );
1104 // For future use, we may want to track the number of actual inserts
1105 // Right now, insert (all writes) simply return true/false
1106 $numrowsinserted = 0;
1108 // always return true
1111 foreach ( $args as $row ) {
1112 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1113 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1115 $res2 = $this->execute($stmt, $row);
1116 // get the last inserted value into a generated column
1117 $this->calcInsertId($table, $primaryKey, $stmt);
1119 $errNum = $this->lastErrno();
1121 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1124 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1129 $olde = error_reporting( $olde );
1130 // Set the affected row count for the whole operation
1131 $this->mAffectedRows
= $numrowsinserted;
1133 // commit either way
1140 * Given a table name and a hash of columns with values
1141 * Removes primary key columns from the hash where the value is NULL
1143 * @param string $table Name of the table
1144 * @param array $args Array of hashes of column names with values
1145 * @return array Tuple containing filtered array of columns, array of primary keys
1147 private function removeNullPrimaryKeys($table, $args) {
1148 $schema = $this->mSchema
;
1149 // find out the primary keys
1150 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1152 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1153 $keys[] = strtolower($row->column_name
);
1155 // remove primary keys
1156 foreach ($args as $ai => $row) {
1157 foreach ($keys as $ki => $key) {
1158 if ($row[$key] == NULL) {
1164 // return modified hash
1165 return array($args, $keys);
1169 * UPDATE wrapper, takes a condition array and a SET array
1171 * @param string $table The table to UPDATE
1172 * @param array $values An array of values to SET
1173 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1174 * @param string $fname The Class::Function calling this function
1176 * @param array $options An array of UPDATE options, can be one or
1177 * more of IGNORE, LOW_PRIORITY
1180 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1181 $table = $this->tableName( $table );
1182 $opts = $this->makeUpdateOptions( $options );
1183 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1184 if ( $conds != '*' ) {
1185 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1187 return $this->query( $sql, $fname );
1191 * DELETE query wrapper
1193 * Use $conds == "*" to delete all rows
1195 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1197 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1199 $table = $this->tableName( $table );
1200 $sql = "DELETE FROM $table";
1201 if ( $conds != '*' ) {
1202 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1204 return $this->query( $sql, $fname );
1208 * Returns the number of rows affected by the last query or 0
1209 * @return int the number of rows affected by the last query
1211 public function affectedRows() {
1212 if ( !is_null( $this->mAffectedRows
) ) {
1213 // Forced result for simulated queries
1214 return $this->mAffectedRows
;
1216 if( empty( $this->mLastResult
) )
1218 return db2_num_rows( $this->mLastResult
);
1222 * Simulates REPLACE with a DELETE followed by INSERT
1223 * @param $table Object
1224 * @param array $uniqueIndexes array consisting of indexes and arrays of indexes
1225 * @param array $rows Rows to insert
1226 * @param string $fname Name of the function for profiling
1229 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1230 $table = $this->tableName( $table );
1232 if (count($rows)==0) {
1237 if ( !is_array( reset( $rows ) ) ) {
1238 $rows = array( $rows );
1241 foreach( $rows as $row ) {
1242 # Delete rows which collide
1243 if ( $uniqueIndexes ) {
1244 $sql = "DELETE FROM $table WHERE ";
1246 foreach ( $uniqueIndexes as $index ) {
1253 if ( is_array( $index ) ) {
1255 foreach ( $index as $col ) {
1261 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1264 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1268 $this->query( $sql, $fname );
1271 # Now insert the row
1272 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1273 $this->makeList( $row, LIST_COMMA
) . ')';
1274 $this->query( $sql, $fname );
1279 * Returns the number of rows in the result set
1280 * Has to be called right after the corresponding select query
1281 * @param object $res result set
1282 * @return int number of rows
1284 public function numRows( $res ) {
1285 if ( $res instanceof ResultWrapper
) {
1286 $res = $res->result
;
1288 if ( $this->mNumRows
) {
1289 return $this->mNumRows
;
1297 * Moves the row pointer of the result set
1298 * @param object $res result set
1299 * @param int $row row number
1300 * @return success or failure
1302 public function dataSeek( $res, $row ) {
1303 if ( $res instanceof ResultWrapper
) {
1304 $res = $res->result
;
1306 return db2_fetch_row( $res, $row );
1310 # Fix notices in Block.php
1314 * Frees memory associated with a statement resource
1315 * @param object $res Statement resource to free
1316 * @return bool success or failure
1318 public function freeResult( $res ) {
1319 if ( $res instanceof ResultWrapper
) {
1320 $res = $res->result
;
1322 if ( !@db2_free_result
( $res ) ) {
1323 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1328 * Returns the number of columns in a resource
1329 * @param object $res Statement resource
1330 * @return Number of fields/columns in resource
1332 public function numFields( $res ) {
1333 if ( $res instanceof ResultWrapper
) {
1334 $res = $res->result
;
1336 return db2_num_fields( $res );
1340 * Returns the nth column name
1341 * @param object $res Statement resource
1342 * @param int $n Index of field or column
1343 * @return string name of nth column
1345 public function fieldName( $res, $n ) {
1346 if ( $res instanceof ResultWrapper
) {
1347 $res = $res->result
;
1349 return db2_field_name( $res, $n );
1355 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1356 * @param mixed $vars Array or string, field name(s) to be retrieved
1357 * @param mixed $conds Array or string, condition(s) for WHERE
1358 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1359 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1360 * see Database::makeSelectOptions code for list of supported stuff
1361 * @param array $join_conds Associative array of table join conditions (optional)
1362 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1363 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1365 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1367 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1369 // We must adjust for offset
1370 if ( isset( $options['LIMIT'] ) ) {
1371 if ( isset ($options['OFFSET'] ) ) {
1372 $limit = $options['LIMIT'];
1373 $offset = $options['OFFSET'];
1378 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1379 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1382 // we want the count
1383 $vars2 = array('count(*) as num_rows');
1384 // respecting just the limit option
1385 $options2 = array();
1386 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1387 // but don't try to emulate for GROUP BY
1388 if ( isset( $options['GROUP BY'] ) ) return $res;
1390 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1391 $obj = $this->fetchObject($res2);
1392 $this->mNumRows
= $obj->num_rows
;
1399 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1400 * Has limited support for per-column options (colnum => 'DISTINCT')
1404 * @param array $options an associative array of options to be turned into
1405 * an SQL query, valid keys are listed in the function.
1408 function makeSelectOptions( $options ) {
1409 $preLimitTail = $postLimitTail = '';
1412 $noKeyOptions = array();
1413 foreach ( $options as $key => $option ) {
1414 if ( is_numeric( $key ) ) {
1415 $noKeyOptions[$option] = true;
1419 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1420 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1421 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1423 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1425 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1429 * Returns link to IBM DB2 free download
1430 * @return string wikitext of a link to the server software's web site
1432 public function getSoftwareLink() {
1433 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1437 * Get search engine class. All subclasses of this
1438 * need to implement this if they wish to use searching.
1442 public function getSearchEngine() {
1443 return "SearchIBM_DB2";
1447 * Did the last database access fail because of deadlock?
1450 public function wasDeadlock() {
1452 $err = $this->lastErrno();
1454 case '40001': // sql0911n, Deadlock or timeout, rollback
1455 case '57011': // sql0904n, Resource unavailable, no rollback
1456 case '57033': // sql0913n, Deadlock or timeout, no rollback
1457 $this->installPrint("In a deadlock because of SQLSTATE $err");
1464 * Ping the server and try to reconnect if it there is no connection
1465 * The connection may be closed and reopened while this happens
1466 * @return bool whether the connection exists
1468 public function ping() {
1469 // db2_ping() doesn't exist
1472 if ($this->mCataloged
== NULL) {
1475 else if ($this->mCataloged
) {
1476 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1478 else if (!$this->mCataloged
) {
1479 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1483 ######################################
1484 # Unimplemented and not applicable
1485 ######################################
1491 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1501 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1506 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1509 * @return string $sql
1512 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1515 * Only useful with fake prepare like in base Database class
1518 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1520 ######################################
1522 ######################################
1525 * Query whether a given column exists in the mediawiki schema
1526 * @param string $table name of the table
1527 * @param string $field name of the column
1528 * @param string $fname function name for logging and profiling
1530 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1531 $table = $this->tableName( $table );
1532 $schema = $this->mSchema
;
1533 $etable = preg_replace("/'/", "''", $table);
1534 $eschema = preg_replace("/'/", "''", $schema);
1535 $ecol = preg_replace("/'/", "''", $field);
1537 SELECT 1 as fieldexists
1538 FROM sysibm.syscolumns sc
1539 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1541 $res = $this->query( $sql, $fname );
1542 $count = $res ?
$this->numRows($res) : 0;
1544 $this->freeResult( $res );
1549 * Returns information about an index
1550 * If errors are explicitly ignored, returns NULL on failure
1551 * @param string $table table name
1552 * @param string $index index name
1554 * @return object query row in object form
1556 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1557 $table = $this->tableName( $table );
1559 SELECT name as indexname
1560 FROM sysibm.sysindexes si
1561 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1563 $res = $this->query( $sql, $fname );
1567 $row = $this->fetchObject( $res );
1568 if ($row != NULL) return $row;
1573 * Returns an information object on a table column
1574 * @param string $table table name
1575 * @param string $field column name
1576 * @return IBM_DB2Field
1578 public function fieldInfo( $table, $field ) {
1579 return IBM_DB2Field
::fromText($this, $table, $field);
1583 * db2_field_type() wrapper
1584 * @param object $res Result of executed statement
1585 * @param mixed $index number or name of the column
1586 * @return string column type
1588 public function fieldType( $res, $index ) {
1589 if ( $res instanceof ResultWrapper
) {
1590 $res = $res->result
;
1592 return db2_field_type( $res, $index );
1596 * Verifies that an index was created as unique
1597 * @param string $table table name
1598 * @param string $index index name
1599 * @param string $fnam function name for profiling
1602 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1603 $table = $this->tableName( $table );
1605 SELECT si.name as indexname
1606 FROM sysibm.sysindexes si
1607 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1608 AND si.uniquerule IN ('U', 'P')
1610 $res = $this->query( $sql, $fname );
1614 if ($this->fetchObject( $res )) {
1622 * Returns the size of a text field, or -1 for "unlimited"
1623 * @param string $table table name
1624 * @param string $field column name
1625 * @return int length or -1 for unlimited
1627 public function textFieldSize( $table, $field ) {
1628 $table = $this->tableName( $table );
1630 SELECT length as size
1631 FROM sysibm.syscolumns sc
1632 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1634 $res = $this->query($sql);
1635 $row = $this->fetchObject($res);
1637 $this->freeResult( $res );
1642 * DELETE where the condition is a join
1643 * @param string $delTable deleting from this table
1644 * @param string $joinTable using data from this table
1645 * @param string $delVar variable in deleteable table
1646 * @param string $joinVar variable in data table
1647 * @param array $conds conditionals for join table
1648 * @param string $fname function name for profiling
1650 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1652 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1655 $delTable = $this->tableName( $delTable );
1656 $joinTable = $this->tableName( $joinTable );
1657 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1658 if ( $conds != '*' ) {
1659 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1663 $this->query( $sql, $fname );
1667 * Description is left as an exercise for the reader
1668 * @param mixed $b data to be encoded
1669 * @return IBM_DB2Blob
1671 public function encodeBlob($b) {
1672 return new IBM_DB2Blob($b);
1676 * Description is left as an exercise for the reader
1677 * @param IBM_DB2Blob $b data to be decoded
1680 public function decodeBlob($b) {
1681 return $b->getData();
1685 * Convert into a list of string being concatenated
1686 * @param array $stringList strings that need to be joined together by the SQL engine
1687 * @return string joined by the concatenation operator
1689 public function buildConcat( $stringList ) {
1690 // || is equivalent to CONCAT
1691 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1692 return implode( ' || ', $stringList );
1696 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1697 * @param string $column name of timestamp column
1698 * @return string SQL code
1700 public function extractUnixEpoch( $column ) {
1702 // see SpecialAncientpages
1705 ######################################
1706 # Prepared statements
1707 ######################################
1710 * Intended to be compatible with the PEAR::DB wrapper functions.
1711 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1713 * ? = scalar value, quoted as necessary
1714 * ! = raw SQL bit (a function for instance)
1715 * & = filename; reads the file and inserts as a blob
1716 * (we don't use this though...)
1717 * @param string $sql SQL statement with appropriate markers
1718 * @return resource a prepared DB2 SQL statement
1720 public function prepare( $sql, $func = 'DB2::prepare' ) {
1721 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1726 * Frees resources associated with a prepared statement
1727 * @return bool success or failure
1729 public function freePrepared( $prepared ) {
1730 return db2_free_stmt($prepared);
1734 * Execute a prepared query with the various arguments
1735 * @param string $prepared the prepared sql
1736 * @param mixed $args Either an array here, or put scalars as varargs
1737 * @return resource Results object
1739 public function execute( $prepared, $args = null ) {
1740 if( !is_array( $args ) ) {
1742 $args = func_get_args();
1743 array_shift( $args );
1745 $res = db2_execute($prepared, $args);
1750 * Prepare & execute an SQL statement, quoting and inserting arguments
1751 * in the appropriate places.
1752 * @param $query String
1755 public function safeQuery( $query, $args = null ) {
1756 // copied verbatim from Database.php
1757 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1758 if( !is_array( $args ) ) {
1760 $args = func_get_args();
1761 array_shift( $args );
1763 $retval = $this->execute( $prepared, $args );
1764 $this->freePrepared( $prepared );
1769 * For faking prepared SQL statements on DBs that don't support
1771 * @param resource $preparedQuery String: a 'preparable' SQL statement
1772 * @param array $args Array of arguments to fill it with
1773 * @return string executable statement
1775 public function fillPrepared( $preparedQuery, $args ) {
1777 $this->preparedArgs
=& $args;
1779 foreach ($args as $i => $arg) {
1780 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1783 return $preparedQuery;
1787 * Switches module between regular and install modes
1789 public function setMode($mode) {
1790 $old = $this->mMode
;
1791 $this->mMode
= $mode;
1796 * Bitwise negation of a column or value in SQL
1797 * Same as (~field) in C
1798 * @param string $field
1801 function bitNot($field) {
1802 //expecting bit-fields smaller than 4bytes
1803 return 'BITNOT('.$bitField.')';
1807 * Bitwise AND of two columns or values in SQL
1808 * Same as (fieldLeft & fieldRight) in C
1809 * @param string $fieldLeft
1810 * @param string $fieldRight
1813 function bitAnd($fieldLeft, $fieldRight) {
1814 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1818 * Bitwise OR of two columns or values in SQL
1819 * Same as (fieldLeft | fieldRight) in C
1820 * @param string $fieldLeft
1821 * @param string $fieldRight
1824 function bitOr($fieldLeft, $fieldRight) {
1825 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';