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 $mTablePrefix;
117 protected $mTrxLevel = 0;
118 protected $mErrorCount = 0;
119 protected $mLBInfo = array();
120 protected $mFakeSlaveLag = null, $mFakeMaster = false;
124 /// Server port for uncataloged connections
125 protected $mPort = null;
126 /// Whether connection is cataloged
127 protected $mCataloged = null;
128 /// Schema for tables, stored procedures, triggers
129 protected $mSchema = null;
130 /// Whether the schema has been applied in this session
131 protected $mSchemaSet = false;
132 /// Result of last query
133 protected $mLastResult = null;
134 /// Number of rows affected by last INSERT/UPDATE/DELETE
135 protected $mAffectedRows = null;
136 /// Number of rows returned by last SELECT
137 protected $mNumRows = null;
139 /// Connection config options - see constructor
140 public $mConnOptions = array();
141 /// Statement config options -- see constructor
142 public $mStmtOptions = array();
145 const CATALOGED
= "cataloged";
146 const UNCATALOGED
= "uncataloged";
147 const USE_GLOBAL
= "get from global";
149 const NONE_OPTION
= 0x00;
150 const CONN_OPTION
= 0x01;
151 const STMT_OPTION
= 0x02;
153 const REGULAR_MODE
= 'regular';
154 const INSTALL_MODE
= 'install';
156 // Whether this is regular operation or the initial installation
157 protected $mMode = self
::REGULAR_MODE
;
159 /// Last sequence value used for a primary key
160 protected $mInsertId = null;
163 * These can be safely inherited
165 * Getter/Setter: (18)
183 * Administrative: (8)
185 * installErrorHandler
186 * restoreErrorHandler
187 * connectionErrorHandler
188 * reportConnectionError
202 * Prepared Statement: 6
220 * tableNamesWithUseIndexOrJOIN
236 * These have been implemented
238 * Administrative: 7 / 7
241 * openCataloged [Done]
243 * newFromParams [Done]
244 * openUncataloged [Done]
245 * setup_database [Done]
247 * Getter/Setter: 13 / 13
248 * cascadingDeletes [Done]
249 * cleanupTriggers [Done]
251 * realTimestamps [Done]
252 * impliciGroupby [Done]
253 * implicitOrderby [Done]
254 * searchableIPs [Done]
255 * functionalIndexes [Done]
258 * getServerVersion [Done]
259 * getSoftwareLink [Done]
260 * getSearchEngine [Done]
262 * Database driver wrapper: 23 / 23
275 * affectedRows [Done]
288 * Slave/master: 2 / 2
289 * setFakeSlaveLag [Done] - Where??
296 * textFieldSize [Done]
298 * Generation: 16 / 16
302 * makeSelectOptions [Done]
303 * estimateRowCount [Done]
304 * nextSequenceValue [Done]
305 * useIndexClause [Done]
308 * lowPriorityOption [Done]
310 * limitResultForUpdate [Done]
317 ######################################
318 # Getters and Setters
319 ######################################
322 * Returns true if this database supports (and uses) cascading deletes
324 function cascadingDeletes() {
329 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
331 function cleanupTriggers() {
336 * Returns true if this database is strict about what can be put into an IP field.
337 * Specifically, it uses a NULL value instead of an empty string.
339 function strictIPs() {
344 * Returns true if this database uses timestamps rather than integers
346 function realTimestamps() {
351 * Returns true if this database does an implicit sort when doing GROUP BY
353 function implicitGroupby() {
358 * Returns true if this database does an implicit order by when the column has an index
359 * For example: SELECT page_title FROM page LIMIT 1
361 function implicitOrderby() {
366 * Returns true if this database can do a native search on IP columns
367 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
369 function searchableIPs() {
374 * Returns true if this database can use functional indexes
376 function functionalIndexes() {
381 * Returns a unique string representing the wiki on the server
383 function getWikiID() {
384 if( $this->mSchema
) {
385 return "{$this->mDBname}-{$this->mSchema}";
387 return $this->mDBname
;
395 ######################################
397 ######################################
402 * @param $server String: hostname of database server
403 * @param $user String: username
404 * @param $password String: password
405 * @param $dbName String: database name on the server
406 * @param $flags Integer: database behaviour flags (optional, unused)
407 * @param $schema String
409 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
410 $dbName = false, $flags = 0,
411 $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->mFlags
= DBO_TRX |
$flags;
421 if ( $schema == self
::USE_GLOBAL
) {
422 $this->mSchema
= $wgDBmwschema;
425 $this->mSchema
= $schema;
428 // configure the connection and statement objects
429 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
430 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
431 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
433 $this->open( $server, $user, $password, $dbName);
437 * Enables options only if the ibm_db2 extension version supports them
438 * @param $name String: name of the option in the options array
439 * @param $const String: name of the constant holding the right option value
440 * @param $type Integer: whether this is a Connection or Statement otion
442 private function setDB2Option($name, $const, $type) {
443 if (defined($const)) {
444 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
445 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
448 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
453 * Outputs debug information in the appropriate place
454 * @param $string String: the relevant debug message
456 private function installPrint($string) {
458 if ($this->mMode
== self
::INSTALL_MODE
) {
459 print "<li>$string</li>";
465 * Opens a database connection and returns it
466 * Closes any existing connection
467 * @return a fresh connection
468 * @param $server String: hostname
469 * @param $user String
470 * @param $password String
471 * @param $dbName String: database name
473 public function open( $server, $user, $password, $dbName )
475 // Load the port number
476 global $wgDBport, $wgDBcataloged;
477 wfProfileIn( __METHOD__
);
479 // Load IBM DB2 driver if missing
482 // Test for IBM DB2 support, to avoid suppressed fatal error
483 if ( !function_exists( 'db2_connect' ) ) {
484 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
485 $this->installPrint($error);
486 $this->reportConnectionError($error);
489 if (!strlen($user)) { // Copied from Postgres
493 // Close existing connection
496 $this->mServer
= $server;
497 $this->mPort
= $port = $wgDBport;
498 $this->mUser
= $user;
499 $this->mPassword
= $password;
500 $this->mDBname
= $dbName;
501 $this->mCataloged
= $cataloged = $wgDBcataloged;
503 if ( $cataloged == self
::CATALOGED
) {
504 $this->openCataloged($dbName, $user, $password);
506 elseif ( $cataloged == self
::UNCATALOGED
) {
507 $this->openUncataloged($dbName, $user, $password, $server, $port);
509 // Apply connection config
510 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
511 // Not all MediaWiki code is transactional
512 // Rather, turn autocommit off in the begin function and turn on after a commit
513 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
515 if ( !$this->mConn
) {
516 $this->installPrint( "DB connection error\n" );
517 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
518 $this->installPrint( $this->lastError()."\n" );
522 $this->mOpened
= true;
523 $this->applySchema();
525 wfProfileOut( __METHOD__
);
530 * Opens a cataloged database connection, sets mConn
532 protected function openCataloged( $dbName, $user, $password )
534 @$this->mConn
= db2_connect($dbName, $user, $password);
538 * Opens an uncataloged database connection, sets mConn
540 protected function openUncataloged( $dbName, $user, $password, $server, $port )
542 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
543 $str .= "DATABASE=$dbName;";
544 $str .= "HOSTNAME=$server;";
545 if ($port) $str .= "PORT=$port;";
546 $str .= "PROTOCOL=TCPIP;";
547 $str .= "UID=$user;";
548 $str .= "PWD=$password;";
550 @$this->mConn
= db2_connect($str, $user, $password);
554 * Closes a database connection, if it is open
555 * Returns success, true if already closed
557 public function close() {
558 $this->mOpened
= false;
559 if ( $this->mConn
) {
560 if ($this->trxLevel() > 0) {
563 return db2_close( $this->mConn
);
571 * Returns a fresh instance of this class
573 * @param $server String: hostname of database server
574 * @param $user String: username
575 * @param $password String
576 * @param $dbName String: database name on the server
577 * @param $flags Integer: database behaviour flags (optional, unused)
578 * @return DatabaseIbm_db2 object
580 static function newFromParams( $server, $user, $password, $dbName, $flags = 0) {
581 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $flags );
585 * Retrieves the most current database error
586 * Forces a database rollback
588 public function lastError() {
589 $connerr = db2_conn_errormsg();
594 $stmterr = db2_stmt_errormsg();
604 * Get the last error number
605 * Return 0 if no error
608 public function lastErrno() {
609 $connerr = db2_conn_error();
610 if ($connerr) return $connerr;
611 $stmterr = db2_stmt_error();
612 if ($stmterr) return $stmterr;
617 * Is a database connection open?
620 public function isOpen() { return $this->mOpened
; }
623 * The DBMS-dependent part of query()
624 * @param $sql String: SQL query.
625 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
629 public function doQuery( $sql ) {
630 //print "<li><pre>$sql</pre></li>";
631 // Switch into the correct namespace
632 $this->applySchema();
634 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
639 $error = db2_stmt_errormsg();
640 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
642 $this->mLastResult
= $ret;
643 $this->mAffectedRows
= null; // Not calculated until asked for
648 * @return string Version information from the database
650 public function getServerVersion() {
651 $info = db2_server_info( $this->mConn
);
652 return $info->DBMS_VER
;
656 * Queries whether a given table exists
659 public function tableExists( $table ) {
660 $schema = $this->mSchema
;
662 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
663 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
665 $res = $this->query( $sql );
666 if (!$res) return false;
668 // If the table exists, there should be one of it
669 @$row = $this->fetchRow($res);
671 if ($count == '1' or $count == 1) {
679 * Fetch the next row from the given result object, in object form.
680 * Fields can be retrieved with $row->fieldname, with fields acting like
683 * @param $res SQL result object as returned from Database::query(), etc.
684 * @return DB2 row object
685 * @throws DBUnexpectedError Thrown if the database returns an error
687 public function fetchObject( $res ) {
688 if ( $res instanceof ResultWrapper
) {
691 @$row = db2_fetch_object( $res );
692 if( $this->lastErrno() ) {
693 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
699 * Fetch the next row from the given result object, in associative array
700 * form. Fields are retrieved with $row['fieldname'].
702 * @param $res SQL result object as returned from Database::query(), etc.
703 * @return DB2 row object
704 * @throws DBUnexpectedError Thrown if the database returns an error
706 public function fetchRow( $res ) {
707 if ( $res instanceof ResultWrapper
) {
710 @$row = db2_fetch_array( $res );
711 if ( $this->lastErrno() ) {
712 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
718 * Override if introduced to base Database class
720 public function initial_setup() {
725 * Create tables, stored procedures, and so on
727 public function setup_database() {
728 // Timeout was being changed earlier due to mysterious crashes
729 // Changing it now may cause more problems than not changing it
730 //set_time_limit(240);
732 // TODO: switch to root login if available
734 // Switch into the correct namespace
735 $this->applySchema();
738 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
740 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
746 // TODO: populate interwiki links
748 if ($this->lastError()) {
749 print "<li>Errors encountered during table creation -- rolled back</li>\n";
750 print "<li>Please install again</li>\n";
757 catch (MWException
$mwe)
759 print "<br><pre>$mwe</pre><br>";
765 * Doesn't escape numbers
766 * @param $s String: string to escape
767 * @return escaped string
769 public function addQuotes( $s ) {
770 //$this->installPrint("DB2::addQuotes($s)\n");
771 if ( is_null( $s ) ) {
773 } else if ($s instanceof Blob
) {
774 return "'".$s->fetch($s)."'";
775 } else if ($s instanceof IBM_DB2Blob
) {
776 return "'".$this->decodeBlob($s)."'";
778 $s = $this->strencode($s);
779 if ( is_numeric($s) ) {
788 * Verifies that a DB2 column/field type is numeric
789 * @return bool true if numeric
790 * @param $type String: DB2 column type
792 public function is_numeric_type( $type ) {
793 switch (strtoupper($type)) {
808 * Alias for addQuotes()
809 * @param $s String: string to escape
810 * @return escaped string
812 public function strencode( $s ) {
813 // Bloody useless function
814 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
815 // But also necessary
816 $s = db2_escape_string($s);
817 // Wide characters are evil -- some of them look like '
818 $s = utf8_encode($s);
820 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
821 $to = array("\\", "''", "\n", "\t", '"', "\r");
822 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
827 * Switch into the database schema
829 protected function applySchema() {
830 if ( !($this->mSchemaSet
) ) {
831 $this->mSchemaSet
= true;
833 $this->doQuery("SET SCHEMA = $this->mSchema");
839 * Start a transaction (mandatory)
841 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
842 // turn off auto-commit
843 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
844 $this->mTrxLevel
= 1;
849 * Must have a preceding begin()
851 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
852 db2_commit($this->mConn
);
853 // turn auto-commit back on
854 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
855 $this->mTrxLevel
= 0;
859 * Cancel a transaction
861 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
862 db2_rollback($this->mConn
);
863 // turn auto-commit back on
864 // not sure if this is appropriate
865 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
866 $this->mTrxLevel
= 0;
870 * Makes an encoded list of strings from an array
872 * LIST_COMMA - comma separated, no field names
873 * LIST_AND - ANDed WHERE clause (without the WHERE)
874 * LIST_OR - ORed WHERE clause (without the WHERE)
875 * LIST_SET - comma separated with field names, like a SET clause
876 * LIST_NAMES - comma separated field names
878 public function makeList( $a, $mode = LIST_COMMA
) {
879 if ( !is_array( $a ) ) {
880 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
885 foreach ( $a as $field => $value ) {
887 if ( $mode == LIST_AND
) {
889 } elseif($mode == LIST_OR
) {
897 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
899 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
901 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
902 if( count( $value ) == 0 ) {
903 throw new MWException( __METHOD__
.': empty input' );
904 } elseif( count( $value ) == 1 ) {
905 // Special-case single values, as IN isn't terribly efficient
906 // Don't necessarily assume the single key is 0; we don't
907 // enforce linear numeric ordering on other arrays here.
908 $value = array_values( $value );
909 $list .= $field." = ".$this->addQuotes( $value[0] );
911 $list .= $field." IN (".$this->makeList($value).") ";
913 } elseif( is_null($value) ) {
914 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
915 $list .= "$field IS ";
916 } elseif ( $mode == LIST_SET
) {
917 $list .= "$field = ";
921 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
922 $list .= "$field = ";
924 if ( $mode == LIST_NAMES
) {
927 // Leo: Can't insert quoted numbers into numeric columns
928 // (?) Might cause other problems. May have to check column type before insertion.
929 else if ( is_numeric($value) ) {
933 $list .= $this->addQuotes( $value );
941 * Construct a LIMIT query with optional offset
942 * This is used for query pages
943 * @param $sql string SQL query we will append the limit too
944 * @param $limit integer the SQL limit
945 * @param $offset integer the SQL offset (default false)
947 public function limitResult($sql, $limit, $offset=false) {
948 if( !is_numeric($limit) ) {
949 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
952 $this->installPrint("Offset parameter not supported in limitResult()\n");
954 // TODO implement proper offset handling
955 // idea: get all the rows between 0 and offset, advance cursor to offset
956 return "$sql FETCH FIRST $limit ROWS ONLY ";
960 * Handle reserved keyword replacement in table names
962 * @param $name Object
964 public function tableName( $name ) {
965 # Replace reserved words with better ones
970 // return 'pagecontent';
974 // we want maximum compatibility with MySQL schema
979 * Generates a timestamp in an insertable format
980 * @return string timestamp value
981 * @param $ts timestamp
983 public function timestamp( $ts=0 ) {
984 // TS_MW cannot be easily distinguished from an integer
985 return wfTimestamp(TS_DB2
,$ts);
989 * Return the next in a sequence, save the value for retrieval via insertId()
990 * @param $seqName String: name of a defined sequence in the database
991 * @return next value in that sequence
993 public function nextSequenceValue( $seqName ) {
994 // Not using sequences in the primary schema to allow for easy third-party migration scripts
995 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
997 $safeseq = preg_replace( "/'/", "''", $seqName );
998 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
999 $row = $this->fetchRow( $res );
1000 $this->mInsertId = $row[0];
1001 return $this->mInsertId;
1007 * This must be called after nextSequenceVal
1008 * @return Last sequence value used as a primary key
1010 public function insertId() {
1011 return $this->mInsertId
;
1015 * Updates the mInsertId property with the value of the last insert into a generated column
1016 * @param $table String: sanitized table name
1017 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
1018 * @param $stmt Resource: prepared statement resource
1019 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1021 private function calcInsertId($table, $primaryKey, $stmt) {
1023 $id_row = $this->fetchRow($stmt);
1024 $this->mInsertId
= $id_row[0];
1029 * INSERT wrapper, inserts an array into a table
1031 * $args may be a single associative array, or an array of these with numeric keys,
1032 * for multi-row insert
1034 * @param $table String: Name of the table to insert to.
1035 * @param $args Array: Items to insert into the table.
1036 * @param $fname String: Name of the function, for profiling
1037 * @param $options String or Array. Valid options: IGNORE
1039 * @return bool Success of insert operation. IGNORE always returns true.
1041 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1042 if ( !count( $args ) ) {
1045 // get database-specific table name (not used)
1046 $table = $this->tableName( $table );
1047 // format options as an array
1048 if ( !is_array( $options ) ) $options = array( $options );
1049 // format args as an array of arrays
1050 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1051 $args = array($args);
1053 // prevent insertion of NULL into primary key columns
1054 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1055 // if there's only one primary key
1056 // we'll be able to read its value after insertion
1057 $primaryKey = false;
1058 if (count($primaryKeys) == 1) {
1059 $primaryKey = $primaryKeys[0];
1063 $keys = array_keys( $args[0] );
1064 $key_count = count($keys);
1066 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1067 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1071 // If we are not in a transaction, we need to be for savepoint trickery
1073 if (! $this->mTrxLevel
) {
1078 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1079 switch($key_count) {
1085 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1087 // add logic to read back the new primary key value
1089 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1091 $stmt = $this->prepare($sql);
1093 // start a transaction/enter transaction mode
1097 foreach ( $args as $row ) {
1098 // insert each row into the database
1099 $res = $res & $this->execute($stmt, $row);
1100 // get the last inserted value into a generated column
1101 $this->calcInsertId($table, $primaryKey, $stmt);
1105 $olde = error_reporting( 0 );
1106 // For future use, we may want to track the number of actual inserts
1107 // Right now, insert (all writes) simply return true/false
1108 $numrowsinserted = 0;
1110 // always return true
1113 foreach ( $args as $row ) {
1114 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1115 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1117 $this->execute($stmt, $row);
1118 // get the last inserted value into a generated column
1119 $this->calcInsertId($table, $primaryKey, $stmt);
1121 $errNum = $this->lastErrno();
1123 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1126 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1131 $olde = error_reporting( $olde );
1132 // Set the affected row count for the whole operation
1133 $this->mAffectedRows
= $numrowsinserted;
1135 // commit either way
1142 * Given a table name and a hash of columns with values
1143 * Removes primary key columns from the hash where the value is NULL
1145 * @param $table String: name of the table
1146 * @param $args Array of hashes of column names with values
1147 * @return Array: tuple containing filtered array of columns, array of primary keys
1149 private function removeNullPrimaryKeys($table, $args) {
1150 $schema = $this->mSchema
;
1151 // find out the primary keys
1152 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1154 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1155 $keys[] = strtolower($row->column_name
);
1157 // remove primary keys
1158 foreach ($args as $ai => $row) {
1159 foreach ($keys as $ki => $key) {
1160 if ($row[$key] == null) {
1166 // return modified hash
1167 return array($args, $keys);
1171 * UPDATE wrapper, takes a condition array and a SET array
1173 * @param $table String: The table to UPDATE
1174 * @param $values An array of values to SET
1175 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1176 * @param $fname String: The Class::Function calling this function
1178 * @param $options An array of UPDATE options, can be one or
1179 * more of IGNORE, LOW_PRIORITY
1182 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1183 $table = $this->tableName( $table );
1184 $opts = $this->makeUpdateOptions( $options );
1185 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1186 if ( $conds != '*' ) {
1187 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1189 return $this->query( $sql, $fname );
1193 * DELETE query wrapper
1195 * Use $conds == "*" to delete all rows
1197 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1199 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1201 $table = $this->tableName( $table );
1202 $sql = "DELETE FROM $table";
1203 if ( $conds != '*' ) {
1204 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1206 return $this->query( $sql, $fname );
1210 * Returns the number of rows affected by the last query or 0
1211 * @return Integer: the number of rows affected by the last query
1213 public function affectedRows() {
1214 if ( !is_null( $this->mAffectedRows
) ) {
1215 // Forced result for simulated queries
1216 return $this->mAffectedRows
;
1218 if( empty( $this->mLastResult
) )
1220 return db2_num_rows( $this->mLastResult
);
1224 * Simulates REPLACE with a DELETE followed by INSERT
1225 * @param $table Object
1226 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1227 * @param $rows Array: rows to insert
1228 * @param $fname String: name of the function for profiling
1231 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1232 $table = $this->tableName( $table );
1234 if (count($rows)==0) {
1239 if ( !is_array( reset( $rows ) ) ) {
1240 $rows = array( $rows );
1243 foreach( $rows as $row ) {
1244 # Delete rows which collide
1245 if ( $uniqueIndexes ) {
1246 $sql = "DELETE FROM $table WHERE ";
1248 foreach ( $uniqueIndexes as $index ) {
1255 if ( is_array( $index ) ) {
1257 foreach ( $index as $col ) {
1263 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1266 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1270 $this->query( $sql, $fname );
1273 # Now insert the row
1274 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1275 $this->makeList( $row, LIST_COMMA
) . ')';
1276 $this->query( $sql, $fname );
1281 * Returns the number of rows in the result set
1282 * Has to be called right after the corresponding select query
1283 * @param $res Object result set
1284 * @return Integer: number of rows
1286 public function numRows( $res ) {
1287 if ( $res instanceof ResultWrapper
) {
1288 $res = $res->result
;
1290 if ( $this->mNumRows
) {
1291 return $this->mNumRows
;
1299 * Moves the row pointer of the result set
1300 * @param $res Object: result set
1301 * @param $row Integer: row number
1302 * @return success or failure
1304 public function dataSeek( $res, $row ) {
1305 if ( $res instanceof ResultWrapper
) {
1306 $res = $res->result
;
1308 return db2_fetch_row( $res, $row );
1312 # Fix notices in Block.php
1316 * Frees memory associated with a statement resource
1317 * @param $res Object: statement resource to free
1318 * @return Boolean success or failure
1320 public function freeResult( $res ) {
1321 if ( $res instanceof ResultWrapper
) {
1322 $res = $res->result
;
1324 if ( !@db2_free_result
( $res ) ) {
1325 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1330 * Returns the number of columns in a resource
1331 * @param $res Object: statement resource
1332 * @return Number of fields/columns in resource
1334 public function numFields( $res ) {
1335 if ( $res instanceof ResultWrapper
) {
1336 $res = $res->result
;
1338 return db2_num_fields( $res );
1342 * Returns the nth column name
1343 * @param $res Object: statement resource
1344 * @param $n Integer: Index of field or column
1345 * @return String name of nth column
1347 public function fieldName( $res, $n ) {
1348 if ( $res instanceof ResultWrapper
) {
1349 $res = $res->result
;
1351 return db2_field_name( $res, $n );
1357 * @param $table Array or string, table name(s) (prefix auto-added)
1358 * @param $vars Array or string, field name(s) to be retrieved
1359 * @param $conds Array or string, condition(s) for WHERE
1360 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1361 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1362 * see Database::makeSelectOptions code for list of supported stuff
1363 * @param $join_conds Associative array of table join conditions (optional)
1364 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1365 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1367 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1369 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1371 // We must adjust for offset
1372 if ( isset( $options['LIMIT'] ) ) {
1373 if ( isset ($options['OFFSET'] ) ) {
1374 $limit = $options['LIMIT'];
1375 $offset = $options['OFFSET'];
1380 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1381 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1384 // we want the count
1385 $vars2 = array('count(*) as num_rows');
1386 // respecting just the limit option
1387 $options2 = array();
1388 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1389 // but don't try to emulate for GROUP BY
1390 if ( isset( $options['GROUP BY'] ) ) return $res;
1392 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1393 $obj = $this->fetchObject($res2);
1394 $this->mNumRows
= $obj->num_rows
;
1401 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1402 * Has limited support for per-column options (colnum => 'DISTINCT')
1406 * @param $options Associative array of options to be turned into
1407 * an SQL query, valid keys are listed in the function.
1410 function makeSelectOptions( $options ) {
1411 $preLimitTail = $postLimitTail = '';
1414 $noKeyOptions = array();
1415 foreach ( $options as $key => $option ) {
1416 if ( is_numeric( $key ) ) {
1417 $noKeyOptions[$option] = true;
1421 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1422 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1423 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1425 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1427 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1431 * Returns link to IBM DB2 free download
1432 * @return string wikitext of a link to the server software's web site
1434 public function getSoftwareLink() {
1435 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1439 * Get search engine class. All subclasses of this
1440 * need to implement this if they wish to use searching.
1444 public function getSearchEngine() {
1445 return "SearchIBM_DB2";
1449 * Did the last database access fail because of deadlock?
1452 public function wasDeadlock() {
1454 $err = $this->lastErrno();
1456 case '40001': // sql0911n, Deadlock or timeout, rollback
1457 case '57011': // sql0904n, Resource unavailable, no rollback
1458 case '57033': // sql0913n, Deadlock or timeout, no rollback
1459 $this->installPrint("In a deadlock because of SQLSTATE $err");
1466 * Ping the server and try to reconnect if it there is no connection
1467 * The connection may be closed and reopened while this happens
1468 * @return Boolean: whether the connection exists
1470 public function ping() {
1471 // db2_ping() doesn't exist
1474 if ($this->mCataloged
== null) {
1477 else if ($this->mCataloged
) {
1478 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1480 else if (!$this->mCataloged
) {
1481 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1485 ######################################
1486 # Unimplemented and not applicable
1487 ######################################
1492 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1495 * @return string $sql
1497 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1500 * Only useful with fake prepare like in base Database class
1503 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1505 ######################################
1507 ######################################
1510 * Returns information about an index
1511 * If errors are explicitly ignored, returns NULL on failure
1512 * @param $table String: table name
1513 * @param $index String: index name
1514 * @param $fname String: function name for logging and profiling
1515 * @return Object query row in object form
1517 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1518 $table = $this->tableName( $table );
1520 SELECT name as indexname
1521 FROM sysibm.sysindexes si
1522 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1524 $res = $this->query( $sql, $fname );
1528 $row = $this->fetchObject( $res );
1529 if ($row != null) return $row;
1534 * Returns an information object on a table column
1535 * @param $table String: table name
1536 * @param $field String: column name
1537 * @return IBM_DB2Field
1539 public function fieldInfo( $table, $field ) {
1540 return IBM_DB2Field
::fromText($this, $table, $field);
1544 * db2_field_type() wrapper
1545 * @param $res Object: result of executed statement
1546 * @param $index Mixed: number or name of the column
1547 * @return String column type
1549 public function fieldType( $res, $index ) {
1550 if ( $res instanceof ResultWrapper
) {
1551 $res = $res->result
;
1553 return db2_field_type( $res, $index );
1557 * Verifies that an index was created as unique
1558 * @param $table String: table name
1559 * @param $index String: index name
1560 * @param $fname function name for profiling
1563 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1564 $table = $this->tableName( $table );
1566 SELECT si.name as indexname
1567 FROM sysibm.sysindexes si
1568 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1569 AND si.uniquerule IN ('U', 'P')
1571 $res = $this->query( $sql, $fname );
1575 if ($this->fetchObject( $res )) {
1583 * Returns the size of a text field, or -1 for "unlimited"
1584 * @param $table String: table name
1585 * @param $field String: column name
1586 * @return Integer: length or -1 for unlimited
1588 public function textFieldSize( $table, $field ) {
1589 $table = $this->tableName( $table );
1591 SELECT length as size
1592 FROM sysibm.syscolumns sc
1593 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1595 $res = $this->query($sql);
1596 $row = $this->fetchObject($res);
1602 * DELETE where the condition is a join
1603 * @param $delTable String: deleting from this table
1604 * @param $joinTable String: using data from this table
1605 * @param $delVar String: variable in deleteable table
1606 * @param $joinVar String: variable in data table
1607 * @param $conds Array: conditionals for join table
1608 * @param $fname String: function name for profiling
1610 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1612 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1615 $delTable = $this->tableName( $delTable );
1616 $joinTable = $this->tableName( $joinTable );
1617 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1618 if ( $conds != '*' ) {
1619 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1623 $this->query( $sql, $fname );
1627 * Description is left as an exercise for the reader
1628 * @param $b Mixed: data to be encoded
1629 * @return IBM_DB2Blob
1631 public function encodeBlob($b) {
1632 return new IBM_DB2Blob($b);
1636 * Description is left as an exercise for the reader
1637 * @param $b IBM_DB2Blob: data to be decoded
1640 public function decodeBlob($b) {
1641 return $b->getData();
1645 * Convert into a list of string being concatenated
1646 * @param $stringList Array: strings that need to be joined together by the SQL engine
1647 * @return String: joined by the concatenation operator
1649 public function buildConcat( $stringList ) {
1650 // || is equivalent to CONCAT
1651 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1652 return implode( ' || ', $stringList );
1656 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1657 * @param $column String: name of timestamp column
1658 * @return String: SQL code
1660 public function extractUnixEpoch( $column ) {
1662 // see SpecialAncientpages
1665 ######################################
1666 # Prepared statements
1667 ######################################
1670 * Intended to be compatible with the PEAR::DB wrapper functions.
1671 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1673 * ? = scalar value, quoted as necessary
1674 * ! = raw SQL bit (a function for instance)
1675 * & = filename; reads the file and inserts as a blob
1676 * (we don't use this though...)
1677 * @param $sql String: SQL statement with appropriate markers
1678 * @param $func String: Name of the function, for profiling
1679 * @return resource a prepared DB2 SQL statement
1681 public function prepare( $sql, $func = 'DB2::prepare' ) {
1682 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1687 * Frees resources associated with a prepared statement
1688 * @return Boolean success or failure
1690 public function freePrepared( $prepared ) {
1691 return db2_free_stmt($prepared);
1695 * Execute a prepared query with the various arguments
1696 * @param $prepared String: the prepared sql
1697 * @param $args Mixed: either an array here, or put scalars as varargs
1698 * @return Resource: results object
1700 public function execute( $prepared, $args = null ) {
1701 if( !is_array( $args ) ) {
1703 $args = func_get_args();
1704 array_shift( $args );
1706 $res = db2_execute($prepared, $args);
1711 * Prepare & execute an SQL statement, quoting and inserting arguments
1712 * in the appropriate places.
1713 * @param $query String
1716 public function safeQuery( $query, $args = null ) {
1717 // copied verbatim from Database.php
1718 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1719 if( !is_array( $args ) ) {
1721 $args = func_get_args();
1722 array_shift( $args );
1724 $retval = $this->execute( $prepared, $args );
1725 $this->freePrepared( $prepared );
1730 * For faking prepared SQL statements on DBs that don't support
1732 * @param $preparedQuery String: a 'preparable' SQL statement
1733 * @param $args Array of arguments to fill it with
1734 * @return String: executable statement
1736 public function fillPrepared( $preparedQuery, $args ) {
1738 $this->preparedArgs
=& $args;
1740 foreach ($args as $i => $arg) {
1741 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1744 return $preparedQuery;
1748 * Switches module between regular and install modes
1750 public function setMode($mode) {
1751 $old = $this->mMode
;
1752 $this->mMode
= $mode;
1757 * Bitwise negation of a column or value in SQL
1758 * Same as (~field) in C
1759 * @param $field String
1762 function bitNot($field) {
1763 //expecting bit-fields smaller than 4bytes
1764 return 'BITNOT('.$field.')';
1768 * Bitwise AND of two columns or values in SQL
1769 * Same as (fieldLeft & fieldRight) in C
1770 * @param $fieldLeft String
1771 * @param $fieldRight String
1774 function bitAnd($fieldLeft, $fieldRight) {
1775 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1779 * Bitwise OR of two columns or values in SQL
1780 * Same as (fieldLeft | fieldRight) in C
1781 * @param $fieldLeft String
1782 * @param $fieldRight String
1785 function bitOr($fieldLeft, $fieldRight) {
1786 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';