3 * This is the IBM DB2 database abstraction layer.
4 * 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 $db DatabaseIbm_db2: Database interface
25 * @param $table String: table name
26 * @param $field String: 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;
126 protected $mPort = null;
127 /// Schema for tables, stored procedures, triggers
128 protected $mSchema = null;
129 /// Whether the schema has been applied in this session
130 protected $mSchemaSet = false;
131 /// Result of last query
132 protected $mLastResult = null;
133 /// Number of rows affected by last INSERT/UPDATE/DELETE
134 protected $mAffectedRows = null;
135 /// Number of rows returned by last SELECT
136 protected $mNumRows = null;
138 /// Connection config options - see constructor
139 public $mConnOptions = array();
140 /// Statement config options -- see constructor
141 public $mStmtOptions = array();
144 const USE_GLOBAL
= "get from global";
146 const NONE_OPTION
= 0x00;
147 const CONN_OPTION
= 0x01;
148 const STMT_OPTION
= 0x02;
150 const REGULAR_MODE
= 'regular';
151 const INSTALL_MODE
= 'install';
153 // Whether this is regular operation or the initial installation
154 protected $mMode = self
::REGULAR_MODE
;
156 /// Last sequence value used for a primary key
157 protected $mInsertId = null;
160 * These can be safely inherited
162 * Getter/Setter: (18)
181 * Administrative: (8)
183 * installErrorHandler
184 * restoreErrorHandler
185 * connectionErrorHandler
186 * reportConnectionError
200 * Prepared Statement: 6
218 * tableNamesWithUseIndexOrJOIN
234 * These have been implemented
236 * Administrative: 7 / 7
239 * openCataloged [Done]
241 * newFromParams [Done]
242 * openUncataloged [Done]
243 * setup_database [Done]
245 * Getter/Setter: 13 / 13
246 * cascadingDeletes [Done]
247 * cleanupTriggers [Done]
249 * realTimestamps [Done]
250 * impliciGroupby [Done]
251 * implicitOrderby [Done]
252 * searchableIPs [Done]
253 * functionalIndexes [Done]
256 * getServerVersion [Done]
257 * getSoftwareLink [Done]
258 * getSearchEngine [Done]
260 * Database driver wrapper: 23 / 23
273 * affectedRows [Done]
286 * Slave/master: 2 / 2
287 * setFakeSlaveLag [Done] - Where??
294 * textFieldSize [Done]
296 * Generation: 16 / 16
300 * makeSelectOptions [Done]
301 * estimateRowCount [Done]
302 * nextSequenceValue [Done]
303 * useIndexClause [Done]
306 * lowPriorityOption [Done]
308 * limitResultForUpdate [Done]
315 ######################################
316 # Getters and Setters
317 ######################################
320 * Returns true if this database supports (and uses) cascading deletes
322 function cascadingDeletes() {
327 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
329 function cleanupTriggers() {
334 * Returns true if this database is strict about what can be put into an IP field.
335 * Specifically, it uses a NULL value instead of an empty string.
337 function strictIPs() {
342 * Returns true if this database uses timestamps rather than integers
344 function realTimestamps() {
349 * Returns true if this database does an implicit sort when doing GROUP BY
351 function implicitGroupby() {
356 * Returns true if this database does an implicit order by when the column has an index
357 * For example: SELECT page_title FROM page LIMIT 1
359 function implicitOrderby() {
364 * Returns true if this database can do a native search on IP columns
365 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
367 function searchableIPs() {
372 * Returns true if this database can use functional indexes
374 function functionalIndexes() {
379 * Returns a unique string representing the wiki on the server
381 function getWikiID() {
382 if( $this->mSchema
) {
383 return "{$this->mDBname}-{$this->mSchema}";
385 return $this->mDBname
;
393 ######################################
395 ######################################
400 * @param $server String: hostname of database server
401 * @param $user String: username
402 * @param $password String: password
403 * @param $dbName String: database name on the server
404 * @param $failFunction Callback (optional)
405 * @param $flags Integer: database behaviour flags (optional, unused)
406 * @param $schema String
408 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
409 $dbName = false, $failFunction = false, $flags = 0,
410 $schema = self
::USE_GLOBAL
)
413 global $wgOut, $wgDBmwschema;
414 # Can't get a reference if it hasn't been set yet
415 if ( !isset( $wgOut ) ) {
418 $this->mOut
=& $wgOut;
419 $this->mFailFunction
= $failFunction;
420 $this->mFlags
= DBO_TRX |
$flags;
422 if ( $schema == self
::USE_GLOBAL
) {
423 $this->mSchema
= $wgDBmwschema;
426 $this->mSchema
= $schema;
429 // configure the connection and statement objects
430 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
431 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
432 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
434 $this->open( $server, $user, $password, $dbName);
438 * Enables options only if the ibm_db2 extension version supports them
439 * @param $name String: name of the option in the options array
440 * @param $const String: name of the constant holding the right option value
441 * @param $type Integer: whether this is a Connection or Statement otion
443 private function setDB2Option($name, $const, $type) {
444 if (defined($const)) {
445 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
446 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
449 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
454 * Outputs debug information in the appropriate place
455 * @param $string String: the relevant debug message
457 private function installPrint($string) {
458 wfDebug("$string\n");
459 if ($this->mMode
== self
::INSTALL_MODE
) {
460 print "<li><pre>$string</pre></li>";
466 * Opens a database connection and returns it
467 * Closes any existing connection
468 * @return a fresh connection
469 * @param $server String: hostname
470 * @param $user String
471 * @param $password String
472 * @param $dbName String: database name
474 public function open( $server, $user, $password, $dbName )
476 // Load the port number
478 wfProfileIn( __METHOD__
);
480 // Load IBM DB2 driver if missing
483 // Test for IBM DB2 support, to avoid suppressed fatal error
484 if ( !function_exists( 'db2_connect' ) ) {
485 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
486 $this->installPrint($error);
487 $this->reportConnectionError($error);
490 if (!strlen($user)) { // Copied from Postgres
494 // Close existing connection
497 $this->mServer
= $server;
498 $this->mPort
= $port = $wgDBport;
499 $this->mUser
= $user;
500 $this->mPassword
= $password;
501 $this->mDBname
= $dbName;
503 $this->openUncataloged($dbName, $user, $password, $server, $port);
505 // Apply connection config
506 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
507 // Not all MediaWiki code is transactional
508 // Rather, turn autocommit off in the begin function and turn on after a commit
509 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
511 if ( !$this->mConn
) {
512 $this->installPrint( "DB connection error\n" );
513 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
514 $this->installPrint( $this->lastError()."\n" );
518 $this->mOpened
= true;
519 $this->applySchema();
521 wfProfileOut( __METHOD__
);
526 * Opens a cataloged database connection, sets mConn
528 protected function openCataloged( $dbName, $user, $password )
530 @$this->mConn
= db2_pconnect($dbName, $user, $password);
534 * Opens an uncataloged database connection, sets mConn
536 protected function openUncataloged( $dbName, $user, $password, $server, $port )
538 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
539 $str .= "DATABASE=$dbName;";
540 $str .= "HOSTNAME=$server;";
541 if ($port) $str .= "PORT=$port;";
542 $str .= "PROTOCOL=TCPIP;";
543 $str .= "UID=$user;";
544 $str .= "PWD=$password;";
546 @$this->mConn
= db2_pconnect($str, $user, $password);
550 * Closes a database connection, if it is open
551 * Returns success, true if already closed
553 public function close() {
554 $this->mOpened
= false;
555 if ( $this->mConn
) {
556 if ($this->trxLevel() > 0) {
559 return db2_close( $this->mConn
);
567 * Returns a fresh instance of this class
569 * @param $server String: hostname of database server
570 * @param $user String: username
571 * @param $password String
572 * @param $dbName String: database name on the server
573 * @param $failFunction Callback (optional)
574 * @param $flags Integer: database behaviour flags (optional, unused)
575 * @return DatabaseIbm_db2 object
577 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
579 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
583 * Retrieves the most current database error
584 * Forces a database rollback
586 public function lastError() {
587 $connerr = db2_conn_errormsg();
592 $stmterr = db2_stmt_errormsg();
602 * Get the last error number
603 * Return 0 if no error
606 public function lastErrno() {
607 $connerr = db2_conn_error();
608 if ($connerr) return $connerr;
609 $stmterr = db2_stmt_error();
610 if ($stmterr) return $stmterr;
615 * Is a database connection open?
618 public function isOpen() { return $this->mOpened
; }
621 * The DBMS-dependent part of query()
622 * @param $sql String: SQL query.
623 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
627 public function doQuery( $sql ) {
628 $this->applySchema();
630 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
631 if( $ret == FALSE ) {
632 $error = db2_stmt_errormsg();
633 $this->installPrint("<pre>$sql</pre>");
634 $this->installPrint($error);
635 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
637 $this->mLastResult
= $ret;
638 $this->mAffectedRows
= null; // Not calculated until asked for
643 * @return string Version information from the database
645 public function getServerVersion() {
646 $info = db2_server_info( $this->mConn
);
647 return $info->DBMS_VER
;
651 * Queries whether a given table exists
654 public function tableExists( $table ) {
655 $schema = $this->mSchema
;
657 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
658 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
660 $res = $this->query( $sql );
661 if (!$res) return false;
663 // If the table exists, there should be one of it
664 @$row = $this->fetchRow($res);
666 if ($count == '1' or $count == 1) {
674 * Fetch the next row from the given result object, in object form.
675 * Fields can be retrieved with $row->fieldname, with fields acting like
678 * @param $res SQL result object as returned from Database::query(), etc.
679 * @return DB2 row object
680 * @throws DBUnexpectedError Thrown if the database returns an error
682 public function fetchObject( $res ) {
683 if ( $res instanceof ResultWrapper
) {
686 @$row = db2_fetch_object( $res );
687 if( $this->lastErrno() ) {
688 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
694 * Fetch the next row from the given result object, in associative array
695 * form. Fields are retrieved with $row['fieldname'].
697 * @param $res SQL result object as returned from Database::query(), etc.
698 * @return DB2 row object
699 * @throws DBUnexpectedError Thrown if the database returns an error
701 public function fetchRow( $res ) {
702 if ( $res instanceof ResultWrapper
) {
705 @$row = db2_fetch_array( $res );
706 if ( $this->lastErrno() ) {
707 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
713 * Override if introduced to base Database class
715 public function initial_setup() {
720 * Create tables, stored procedures, and so on
722 public function setup_database() {
723 // Timeout was being changed earlier due to mysterious crashes
724 // Changing it now may cause more problems than not changing it
725 //set_time_limit(240);
727 // TODO: switch to root login if available
729 // Switch into the correct namespace
730 $this->applySchema();
733 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
735 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
739 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
741 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
743 print "<li>Foreign keys done</li>";
747 // TODO: populate interwiki links
749 if ($this->lastError()) {
750 print "<li>Errors encountered during table creation -- rolled back</li>\n";
751 print "<li>Please install again</li>\n";
758 catch (MWException
$mwe)
760 print "<br><pre>$mwe</pre><br>";
766 * Doesn't escape numbers
767 * @param $s String: string to escape
768 * @return escaped string
770 public function addQuotes( $s ) {
771 //$this->installPrint("DB2::addQuotes($s)\n");
772 if ( is_null( $s ) ) {
774 } else if ($s instanceof Blob
) {
775 return "'".$s->fetch($s)."'";
776 } else if ($s instanceof IBM_DB2Blob
) {
777 return "'".$this->decodeBlob($s)."'";
779 $s = $this->strencode($s);
780 if ( is_numeric($s) ) {
789 * Verifies that a DB2 column/field type is numeric
790 * @return bool true if numeric
791 * @param $type String: DB2 column type
793 public function is_numeric_type( $type ) {
794 switch (strtoupper($type)) {
809 * Alias for addQuotes()
810 * @param $s String: string to escape
811 * @return escaped string
813 public function strencode( $s ) {
814 // Bloody useless function
815 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
816 // But also necessary
817 $s = db2_escape_string($s);
818 // Wide characters are evil -- some of them look like '
819 $s = utf8_encode($s);
821 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
822 $to = array("\\", "''", "\n", "\t", '"', "\r");
823 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
828 * Switch into the database schema
830 protected function applySchema() {
831 if ( !($this->mSchemaSet
) ) {
832 $this->mSchemaSet
= true;
834 $this->doQuery("SET SCHEMA = $this->mSchema");
840 * Start a transaction (mandatory)
842 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
843 // turn off auto-commit
844 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
845 $this->mTrxLevel
= 1;
850 * Must have a preceding begin()
852 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
853 db2_commit($this->mConn
);
854 // turn auto-commit back on
855 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
856 $this->mTrxLevel
= 0;
860 * Cancel a transaction
862 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
863 db2_rollback($this->mConn
);
864 // turn auto-commit back on
865 // not sure if this is appropriate
866 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
867 $this->mTrxLevel
= 0;
871 * Makes an encoded list of strings from an array
873 * LIST_COMMA - comma separated, no field names
874 * LIST_AND - ANDed WHERE clause (without the WHERE)
875 * LIST_OR - ORed WHERE clause (without the WHERE)
876 * LIST_SET - comma separated with field names, like a SET clause
877 * LIST_NAMES - comma separated field names
878 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
880 function makeList( $a, $mode = LIST_COMMA
) {
881 if ( !is_array( $a ) ) {
882 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
885 // if this is for a prepared UPDATE statement
886 // (this should be promoted to the parent class
887 // once other databases use prepared statements)
888 if ($mode == LIST_SET_PREPARED
) {
891 foreach ( $a as $field => $value ) {
893 $list .= ", $field = ?";
896 $list .= "$field = ?";
905 // otherwise, call the usual function
906 return parent
::makeList( $a, $mode );
910 * Construct a LIMIT query with optional offset
911 * This is used for query pages
912 * @param $sql string SQL query we will append the limit too
913 * @param $limit integer the SQL limit
914 * @param $offset integer the SQL offset (default false)
916 public function limitResult($sql, $limit, $offset=false) {
917 if( !is_numeric($limit) ) {
918 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
921 //$this->installPrint("Offset parameter not supported in limitResult()\n");
922 if ( stripos($sql, 'where') === false ) {
923 return "$sql AND (ROWNUM BETWEEN $offset AND $offset+$limit)";
926 return "$sql WHERE (ROWNUM BETWEEN $offset AND $offset+$limit)";
929 return "$sql FETCH FIRST $limit ROWS ONLY ";
933 * Handle reserved keyword replacement in table names
935 * @param $name Object
937 public function tableName( $name ) {
938 # Replace reserved words with better ones
943 // return 'pagecontent';
947 // we want maximum compatibility with MySQL schema
952 * Generates a timestamp in an insertable format
953 * @return string timestamp value
954 * @param $ts timestamp
956 public function timestamp( $ts=0 ) {
957 // TS_MW cannot be easily distinguished from an integer
958 return wfTimestamp(TS_DB2
,$ts);
962 * Return the next in a sequence, save the value for retrieval via insertId()
963 * @param $seqName String: name of a defined sequence in the database
964 * @return next value in that sequence
966 public function nextSequenceValue( $seqName ) {
967 // Not using sequences in the primary schema to allow for easy third-party migration scripts
968 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
970 $safeseq = preg_replace( "/'/", "''", $seqName );
971 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
972 $row = $this->fetchRow( $res );
973 $this->mInsertId = $row[0];
974 return $this->mInsertId;
980 * This must be called after nextSequenceVal
981 * @return Last sequence value used as a primary key
983 public function insertId() {
984 return $this->mInsertId
;
988 * Updates the mInsertId property with the value of the last insert into a generated column
989 * @param $table String: sanitized table name
990 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
991 * @param $stmt Resource: prepared statement resource
992 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
994 private function calcInsertId($table, $primaryKey, $stmt) {
996 $this->mInsertId
= db2_last_insert_id($this->mConn
);
997 //$this->installPrint("Last $primaryKey for $table was $this->mInsertId");
1002 * INSERT wrapper, inserts an array into a table
1004 * $args may be a single associative array, or an array of these with numeric keys,
1005 * for multi-row insert
1007 * @param $table String: Name of the table to insert to.
1008 * @param $args Array: Items to insert into the table.
1009 * @param $fname String: Name of the function, for profiling
1010 * @param $options String or Array. Valid options: IGNORE
1012 * @return bool Success of insert operation. IGNORE always returns true.
1014 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1015 if ( !count( $args ) ) {
1018 // get database-specific table name (not used)
1019 $table = $this->tableName( $table );
1020 // format options as an array
1021 $options = IBM_DB2Helper
::makeArray($options);
1022 // format args as an array of arrays
1023 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1024 $args = array($args);
1027 // prevent insertion of NULL into primary key columns
1028 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1029 // if there's only one primary key
1030 // we'll be able to read its value after insertion
1031 $primaryKey = false;
1032 if (count($primaryKeys) == 1) {
1033 $primaryKey = $primaryKeys[0];
1037 $keys = array_keys( $args[0] );
1038 $key_count = count($keys);
1040 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1041 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1045 // If we are not in a transaction, we need to be for savepoint trickery
1046 if (! $this->mTrxLevel
) {
1050 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1051 if ($key_count == 1) {
1054 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1056 //$this->installPrint("Preparing the following SQL:");
1057 //$this->installPrint("$sql");
1058 //$this->installPrint(print_r($args, true));
1059 $stmt = $this->prepare($sql);
1061 // start a transaction/enter transaction mode
1066 foreach ( $args as $row ) {
1067 //$this->installPrint("Inserting " . print_r($row, true));
1068 // insert each row into the database
1069 $res = $res & $this->execute($stmt, $row);
1071 $this->installPrint("Last error:");
1072 $this->installPrint($this->lastError());
1074 // get the last inserted value into a generated column
1075 $this->calcInsertId($table, $primaryKey, $stmt);
1079 $olde = error_reporting( 0 );
1080 // For future use, we may want to track the number of actual inserts
1081 // Right now, insert (all writes) simply return true/false
1082 $numrowsinserted = 0;
1084 // always return true
1087 foreach ( $args as $row ) {
1088 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1089 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1090 //$this->installPrint("Inserting " . print_r($row, true));
1092 $this->execute($stmt, $row);
1093 //$this->installPrint(wfGetAllCallers());
1095 $this->installPrint("Last error:");
1096 $this->installPrint($this->lastError());
1098 // get the last inserted value into a generated column
1099 $this->calcInsertId($table, $primaryKey, $stmt);
1101 $errNum = $this->lastErrno();
1103 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1106 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1111 $olde = error_reporting( $olde );
1112 // Set the affected row count for the whole operation
1113 $this->mAffectedRows
= $numrowsinserted;
1115 // commit either way
1117 $this->freePrepared($stmt);
1123 * Given a table name and a hash of columns with values
1124 * Removes primary key columns from the hash where the value is NULL
1126 * @param $table String: name of the table
1127 * @param $args Array of hashes of column names with values
1128 * @return Array: tuple containing filtered array of columns, array of primary keys
1130 private function removeNullPrimaryKeys($table, $args) {
1131 $schema = $this->mSchema
;
1132 // find out the primary keys
1133 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1135 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1136 $keys[] = strtolower($row->column_name
);
1138 // remove primary keys
1139 foreach ($args as $ai => $row) {
1140 foreach ($keys as $ki => $key) {
1141 if ($row[$key] == null) {
1147 // return modified hash
1148 return array($args, $keys);
1152 * UPDATE wrapper, takes a condition array and a SET array
1154 * @param $table String: The table to UPDATE
1155 * @param $values An array of values to SET
1156 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1157 * @param $fname String: The Class::Function calling this function
1159 * @param $options An array of UPDATE options, can be one or
1160 * more of IGNORE, LOW_PRIORITY
1163 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1164 $table = $this->tableName( $table );
1165 $opts = $this->makeUpdateOptions( $options );
1166 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET_PREPARED
);
1167 if ( $conds != '*' ) {
1168 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1170 $stmt = $this->prepare( $sql );
1171 $this->installPrint("UPDATE: " . print_r($values, TRUE));
1172 // assuming for now that an array with string keys will work
1173 // if not, convert to simple array first
1174 $result = $this->execute( $stmt, $values );
1175 $this->freePrepared( $stmt );
1176 //$result = $this->query( $sql, $fname );
1177 // commit regardless of state
1183 * DELETE query wrapper
1185 * Use $conds == "*" to delete all rows
1187 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1189 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1191 $table = $this->tableName( $table );
1192 $sql = "DELETE FROM $table";
1193 if ( $conds != '*' ) {
1194 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1196 $result = $this->query( $sql, $fname );
1197 // commit regardless
1203 * Returns the number of rows affected by the last query or 0
1204 * @return Integer: the number of rows affected by the last query
1206 public function affectedRows() {
1207 if ( !is_null( $this->mAffectedRows
) ) {
1208 // Forced result for simulated queries
1209 return $this->mAffectedRows
;
1211 if( empty( $this->mLastResult
) )
1213 return db2_num_rows( $this->mLastResult
);
1217 * Simulates REPLACE with a DELETE followed by INSERT
1218 * @param $table Object
1219 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1220 * @param $rows Array: rows to insert
1221 * @param $fname String: name of the function for profiling
1224 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1225 $table = $this->tableName( $table );
1227 if (count($rows)==0) {
1232 if ( !is_array( reset( $rows ) ) ) {
1233 $rows = array( $rows );
1236 foreach( $rows as $row ) {
1237 # Delete rows which collide
1238 if ( $uniqueIndexes ) {
1239 $sql = "DELETE FROM $table WHERE ";
1241 foreach ( $uniqueIndexes as $index ) {
1248 if ( is_array( $index ) ) {
1250 foreach ( $index as $col ) {
1256 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1259 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1263 $this->query( $sql, $fname );
1266 # Now insert the row
1267 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1268 $this->makeList( $row, LIST_COMMA
) . ')';
1269 $this->query( $sql, $fname );
1274 * Returns the number of rows in the result set
1275 * Has to be called right after the corresponding select query
1276 * @param $res Object result set
1277 * @return Integer: number of rows
1279 public function numRows( $res ) {
1280 if ( $res instanceof ResultWrapper
) {
1281 $res = $res->result
;
1283 if ( $this->mNumRows
) {
1284 return $this->mNumRows
;
1292 * Moves the row pointer of the result set
1293 * @param $res Object: result set
1294 * @param $row Integer: row number
1295 * @return success or failure
1297 public function dataSeek( $res, $row ) {
1298 if ( $res instanceof ResultWrapper
) {
1299 $res = $res->result
;
1301 return db2_fetch_row( $res, $row );
1305 # Fix notices in Block.php
1309 * Frees memory associated with a statement resource
1310 * @param $res Object: statement resource to free
1311 * @return Boolean success or failure
1313 public function freeResult( $res ) {
1314 if ( $res instanceof ResultWrapper
) {
1315 $res = $res->result
;
1317 if ( !@db2_free_result
( $res ) ) {
1318 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1323 * Returns the number of columns in a resource
1324 * @param $res Object: statement resource
1325 * @return Number of fields/columns in resource
1327 public function numFields( $res ) {
1328 if ( $res instanceof ResultWrapper
) {
1329 $res = $res->result
;
1331 return db2_num_fields( $res );
1335 * Returns the nth column name
1336 * @param $res Object: statement resource
1337 * @param $n Integer: Index of field or column
1338 * @return String name of nth column
1340 public function fieldName( $res, $n ) {
1341 if ( $res instanceof ResultWrapper
) {
1342 $res = $res->result
;
1344 return db2_field_name( $res, $n );
1350 * @param $table Array or string, table name(s) (prefix auto-added)
1351 * @param $vars Array or string, field name(s) to be retrieved
1352 * @param $conds Array or string, condition(s) for WHERE
1353 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1354 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1355 * see Database::makeSelectOptions code for list of supported stuff
1356 * @param $join_conds Associative array of table join conditions (optional)
1357 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1358 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1360 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1362 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1364 // We must adjust for offset
1365 if ( isset( $options['LIMIT'] ) ) {
1366 if ( isset ($options['OFFSET'] ) ) {
1367 $limit = $options['LIMIT'];
1368 $offset = $options['OFFSET'];
1373 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1374 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1377 // we want the count
1378 $vars2 = array('count(*) as num_rows');
1379 // respecting just the limit option
1380 $options2 = array();
1381 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1382 // but don't try to emulate for GROUP BY
1383 if ( isset( $options['GROUP BY'] ) ) return $res;
1385 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1386 $obj = $this->fetchObject($res2);
1387 $this->mNumRows
= $obj->num_rows
;
1394 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1395 * Has limited support for per-column options (colnum => 'DISTINCT')
1399 * @param $options Associative array of options to be turned into
1400 * an SQL query, valid keys are listed in the function.
1403 function makeSelectOptions( $options ) {
1404 $preLimitTail = $postLimitTail = '';
1407 $noKeyOptions = array();
1408 foreach ( $options as $key => $option ) {
1409 if ( is_numeric( $key ) ) {
1410 $noKeyOptions[$option] = true;
1414 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1415 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1416 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1418 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1420 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1424 * Returns link to IBM DB2 free download
1425 * @return string wikitext of a link to the server software's web site
1427 public static function getSoftwareLink() {
1428 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1432 * Get search engine class. All subclasses of this
1433 * need to implement this if they wish to use searching.
1437 public function getSearchEngine() {
1438 return "SearchIBM_DB2";
1442 * Did the last database access fail because of deadlock?
1445 public function wasDeadlock() {
1447 $err = $this->lastErrno();
1449 case '40001': // sql0911n, Deadlock or timeout, rollback
1450 case '57011': // sql0904n, Resource unavailable, no rollback
1451 case '57033': // sql0913n, Deadlock or timeout, no rollback
1452 $this->installPrint("In a deadlock because of SQLSTATE $err");
1459 * Ping the server and try to reconnect if it there is no connection
1460 * The connection may be closed and reopened while this happens
1461 * @return Boolean: whether the connection exists
1463 public function ping() {
1464 // db2_ping() doesn't exist
1467 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1471 ######################################
1472 # Unimplemented and not applicable
1473 ######################################
1478 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1481 * @return string $sql
1483 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1486 * Only useful with fake prepare like in base Database class
1489 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1491 ######################################
1493 ######################################
1496 * Returns information about an index
1497 * If errors are explicitly ignored, returns NULL on failure
1498 * @param $table String: table name
1499 * @param $index String: index name
1500 * @param $fname String: function name for logging and profiling
1501 * @return Object query row in object form
1503 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1504 $table = $this->tableName( $table );
1506 SELECT name as indexname
1507 FROM sysibm.sysindexes si
1508 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1510 $res = $this->query( $sql, $fname );
1514 $row = $this->fetchObject( $res );
1515 if ($row != null) return $row;
1520 * Returns an information object on a table column
1521 * @param $table String: table name
1522 * @param $field String: column name
1523 * @return IBM_DB2Field
1525 public function fieldInfo( $table, $field ) {
1526 return IBM_DB2Field
::fromText($this, $table, $field);
1530 * db2_field_type() wrapper
1531 * @param $res Object: result of executed statement
1532 * @param $index Mixed: number or name of the column
1533 * @return String column type
1535 public function fieldType( $res, $index ) {
1536 if ( $res instanceof ResultWrapper
) {
1537 $res = $res->result
;
1539 return db2_field_type( $res, $index );
1543 * Verifies that an index was created as unique
1544 * @param $table String: table name
1545 * @param $index String: index name
1546 * @param $fname function name for profiling
1549 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1550 $table = $this->tableName( $table );
1552 SELECT si.name as indexname
1553 FROM sysibm.sysindexes si
1554 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1555 AND si.uniquerule IN ('U', 'P')
1557 $res = $this->query( $sql, $fname );
1561 if ($this->fetchObject( $res )) {
1569 * Returns the size of a text field, or -1 for "unlimited"
1570 * @param $table String: table name
1571 * @param $field String: column name
1572 * @return Integer: length or -1 for unlimited
1574 public function textFieldSize( $table, $field ) {
1575 $table = $this->tableName( $table );
1577 SELECT length as size
1578 FROM sysibm.syscolumns sc
1579 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1581 $res = $this->query($sql);
1582 $row = $this->fetchObject($res);
1588 * DELETE where the condition is a join
1589 * @param $delTable String: deleting from this table
1590 * @param $joinTable String: using data from this table
1591 * @param $delVar String: variable in deleteable table
1592 * @param $joinVar String: variable in data table
1593 * @param $conds Array: conditionals for join table
1594 * @param $fname String: function name for profiling
1596 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1598 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1601 $delTable = $this->tableName( $delTable );
1602 $joinTable = $this->tableName( $joinTable );
1603 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1604 if ( $conds != '*' ) {
1605 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1609 $this->query( $sql, $fname );
1613 * Description is left as an exercise for the reader
1614 * @param $b Mixed: data to be encoded
1615 * @return IBM_DB2Blob
1617 public function encodeBlob($b) {
1618 return new IBM_DB2Blob($b);
1622 * Description is left as an exercise for the reader
1623 * @param $b IBM_DB2Blob: data to be decoded
1626 public function decodeBlob($b) {
1631 * Convert into a list of string being concatenated
1632 * @param $stringList Array: strings that need to be joined together by the SQL engine
1633 * @return String: joined by the concatenation operator
1635 public function buildConcat( $stringList ) {
1636 // || is equivalent to CONCAT
1637 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1638 return implode( ' || ', $stringList );
1642 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1643 * @param $column String: name of timestamp column
1644 * @return String: SQL code
1646 public function extractUnixEpoch( $column ) {
1648 // see SpecialAncientpages
1651 ######################################
1652 # Prepared statements
1653 ######################################
1656 * Intended to be compatible with the PEAR::DB wrapper functions.
1657 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1659 * ? = scalar value, quoted as necessary
1660 * ! = raw SQL bit (a function for instance)
1661 * & = filename; reads the file and inserts as a blob
1662 * (we don't use this though...)
1663 * @param $sql String: SQL statement with appropriate markers
1664 * @param $func String: Name of the function, for profiling
1665 * @return resource a prepared DB2 SQL statement
1667 public function prepare( $sql, $func = 'DB2::prepare' ) {
1668 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1673 * Frees resources associated with a prepared statement
1674 * @return Boolean success or failure
1676 public function freePrepared( $prepared ) {
1677 return db2_free_stmt($prepared);
1681 * Execute a prepared query with the various arguments
1682 * @param $prepared String: the prepared sql
1683 * @param $args Mixed: either an array here, or put scalars as varargs
1684 * @return Resource: results object
1686 public function execute( $prepared, $args = null ) {
1687 if( !is_array( $args ) ) {
1689 $args = func_get_args();
1690 array_shift( $args );
1692 $res = db2_execute($prepared, $args);
1694 $this->installPrint(db2_stmt_errormsg());
1700 * Prepare & execute an SQL statement, quoting and inserting arguments
1701 * in the appropriate places.
1702 * @param $query String
1705 public function safeQuery( $query, $args = null ) {
1706 // copied verbatim from Database.php
1707 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1708 if( !is_array( $args ) ) {
1710 $args = func_get_args();
1711 array_shift( $args );
1713 $retval = $this->execute( $prepared, $args );
1714 $this->freePrepared( $prepared );
1719 * For faking prepared SQL statements on DBs that don't support
1721 * @param $preparedQuery String: a 'preparable' SQL statement
1722 * @param $args Array of arguments to fill it with
1723 * @return String: executable statement
1725 public function fillPrepared( $preparedQuery, $args ) {
1727 $this->preparedArgs
=& $args;
1729 foreach ($args as $i => $arg) {
1730 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1733 return $preparedQuery;
1737 * Switches module between regular and install modes
1739 public function setMode($mode) {
1740 $old = $this->mMode
;
1741 $this->mMode
= $mode;
1746 * Bitwise negation of a column or value in SQL
1747 * Same as (~field) in C
1748 * @param $field String
1751 function bitNot($field) {
1752 //expecting bit-fields smaller than 4bytes
1753 return 'BITNOT('.$field.')';
1757 * Bitwise AND of two columns or values in SQL
1758 * Same as (fieldLeft & fieldRight) in C
1759 * @param $fieldLeft String
1760 * @param $fieldRight String
1763 function bitAnd($fieldLeft, $fieldRight) {
1764 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1768 * Bitwise OR of two columns or values in SQL
1769 * Same as (fieldLeft | fieldRight) in C
1770 * @param $fieldLeft String
1771 * @param $fieldRight String
1774 function bitOr($fieldLeft, $fieldRight) {
1775 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1779 class IBM_DB2Helper
{
1780 public static function makeArray($maybeArray) {
1781 if ( !is_array( $maybeArray ) ) $maybeArray = array( $maybeArray );