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 $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;
125 /// Server port for uncataloged connections
126 protected $mPort = null;
127 /// Whether connection is cataloged
128 protected $mCataloged = null;
129 /// Schema for tables, stored procedures, triggers
130 protected $mSchema = null;
131 /// Whether the schema has been applied in this session
132 protected $mSchemaSet = false;
133 /// Result of last query
134 protected $mLastResult = null;
135 /// Number of rows affected by last INSERT/UPDATE/DELETE
136 protected $mAffectedRows = null;
137 /// Number of rows returned by last SELECT
138 protected $mNumRows = null;
140 /// Connection config options - see constructor
141 public $mConnOptions = array();
142 /// Statement config options -- see constructor
143 public $mStmtOptions = array();
146 const CATALOGED
= "cataloged";
147 const UNCATALOGED
= "uncataloged";
148 const USE_GLOBAL
= "get from global";
150 const NONE_OPTION
= 0x00;
151 const CONN_OPTION
= 0x01;
152 const STMT_OPTION
= 0x02;
154 const REGULAR_MODE
= 'regular';
155 const INSTALL_MODE
= 'install';
157 // Whether this is regular operation or the initial installation
158 protected $mMode = self
::REGULAR_MODE
;
160 /// Last sequence value used for a primary key
161 protected $mInsertId = null;
164 * These can be safely inherited
166 * Getter/Setter: (18)
186 * Administrative: (8)
188 * installErrorHandler
189 * restoreErrorHandler
190 * connectionErrorHandler
191 * reportConnectionError
205 * Prepared Statement: 6
222 * tableNamesWithUseIndexOrJOIN
238 * These have been implemented
240 * Administrative: 7 / 7
243 * openCataloged [Done]
245 * newFromParams [Done]
246 * openUncataloged [Done]
247 * setup_database [Done]
249 * Getter/Setter: 13 / 13
250 * cascadingDeletes [Done]
251 * cleanupTriggers [Done]
253 * realTimestamps [Done]
254 * impliciGroupby [Done]
255 * implicitOrderby [Done]
256 * searchableIPs [Done]
257 * functionalIndexes [Done]
260 * getServerVersion [Done]
261 * getSoftwareLink [Done]
262 * getSearchEngine [Done]
264 * Database driver wrapper: 23 / 23
277 * affectedRows [Done]
290 * Slave/master: 2 / 2
291 * setFakeSlaveLag [Done]
292 * setFakeMaster [Done]
299 * textFieldSize [Done]
301 * Generation: 16 / 16
305 * makeSelectOptions [Done]
306 * estimateRowCount [Done]
307 * nextSequenceValue [Done]
308 * useIndexClause [Done]
311 * lowPriorityOption [Done]
313 * limitResultForUpdate [Done]
320 ######################################
321 # Getters and Setters
322 ######################################
325 * Returns true if this database supports (and uses) cascading deletes
327 function cascadingDeletes() {
332 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
334 function cleanupTriggers() {
339 * Returns true if this database is strict about what can be put into an IP field.
340 * Specifically, it uses a NULL value instead of an empty string.
342 function strictIPs() {
347 * Returns true if this database uses timestamps rather than integers
349 function realTimestamps() {
354 * Returns true if this database does an implicit sort when doing GROUP BY
356 function implicitGroupby() {
361 * Returns true if this database does an implicit order by when the column has an index
362 * For example: SELECT page_title FROM page LIMIT 1
364 function implicitOrderby() {
369 * Returns true if this database can do a native search on IP columns
370 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
372 function searchableIPs() {
377 * Returns true if this database can use functional indexes
379 function functionalIndexes() {
384 * Returns a unique string representing the wiki on the server
386 function getWikiID() {
387 if( $this->mSchema
) {
388 return "{$this->mDBname}-{$this->mSchema}";
390 return $this->mDBname
;
398 ######################################
400 ######################################
405 * @param $server String: hostname of database server
406 * @param $user String: username
407 * @param $password String: password
408 * @param $dbName String: database name on the server
409 * @param $failFunction Callback (optional)
410 * @param $flags Integer: database behaviour flags (optional, unused)
411 * @param $schema String
413 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
414 $dbName = false, $failFunction = false, $flags = 0,
415 $schema = self
::USE_GLOBAL
)
418 global $wgOut, $wgDBmwschema;
419 # Can't get a reference if it hasn't been set yet
420 if ( !isset( $wgOut ) ) {
423 $this->mOut
=& $wgOut;
424 $this->mFailFunction
= $failFunction;
425 $this->mFlags
= DBO_TRX |
$flags;
427 if ( $schema == self
::USE_GLOBAL
) {
428 $this->mSchema
= $wgDBmwschema;
431 $this->mSchema
= $schema;
434 // configure the connection and statement objects
435 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
436 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
437 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
439 $this->open( $server, $user, $password, $dbName);
443 * Enables options only if the ibm_db2 extension version supports them
444 * @param $name String: name of the option in the options array
445 * @param $const String: name of the constant holding the right option value
446 * @param $type Integer: whether this is a Connection or Statement otion
448 private function setDB2Option($name, $const, $type) {
449 if (defined($const)) {
450 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
451 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
454 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
459 * Outputs debug information in the appropriate place
460 * @param $string String: the relevant debug message
462 private function installPrint($string) {
464 if ($this->mMode
== self
::INSTALL_MODE
) {
465 print "<li>$string</li>";
471 * Opens a database connection and returns it
472 * Closes any existing connection
473 * @return a fresh connection
474 * @param $server String: hostname
475 * @param $user String
476 * @param $password String
477 * @param $dbName String: database name
479 public function open( $server, $user, $password, $dbName )
481 // Load the port number
482 global $wgDBport_db2, $wgDBcataloged;
483 wfProfileIn( __METHOD__
);
485 // Load IBM DB2 driver if missing
488 // Test for IBM DB2 support, to avoid suppressed fatal error
489 if ( !function_exists( 'db2_connect' ) ) {
490 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
491 $this->installPrint($error);
492 $this->reportConnectionError($error);
495 if (!strlen($user)) { // Copied from Postgres
499 // Close existing connection
502 $this->mServer
= $server;
503 $this->mPort
= $port = $wgDBport_db2;
504 $this->mUser
= $user;
505 $this->mPassword
= $password;
506 $this->mDBname
= $dbName;
507 $this->mCataloged
= $cataloged = $wgDBcataloged;
509 if ( $cataloged == self
::CATALOGED
) {
510 $this->openCataloged($dbName, $user, $password);
512 elseif ( $cataloged == self
::UNCATALOGED
) {
513 $this->openUncataloged($dbName, $user, $password, $server, $port);
515 // Apply connection config
516 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
517 // Not all MediaWiki code is transactional
518 // Rather, turn autocommit off in the begin function and turn on after a commit
519 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
521 if ( !$this->mConn
) {
522 $this->installPrint( "DB connection error\n" );
523 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
524 $this->installPrint( $this->lastError()."\n" );
528 $this->mOpened
= true;
529 $this->applySchema();
531 wfProfileOut( __METHOD__
);
536 * Opens a cataloged database connection, sets mConn
538 protected function openCataloged( $dbName, $user, $password )
540 @$this->mConn
= db2_connect($dbName, $user, $password);
544 * Opens an uncataloged database connection, sets mConn
546 protected function openUncataloged( $dbName, $user, $password, $server, $port )
548 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
549 $str .= "DATABASE=$dbName;";
550 $str .= "HOSTNAME=$server;";
551 if ($port) $str .= "PORT=$port;";
552 $str .= "PROTOCOL=TCPIP;";
553 $str .= "UID=$user;";
554 $str .= "PWD=$password;";
556 @$this->mConn
= db2_connect($str, $user, $password);
560 * Closes a database connection, if it is open
561 * Returns success, true if already closed
563 public function close() {
564 $this->mOpened
= false;
565 if ( $this->mConn
) {
566 if ($this->trxLevel() > 0) {
569 return db2_close( $this->mConn
);
577 * Returns a fresh instance of this class
579 * @param $server String: hostname of database server
580 * @param $user String: username
581 * @param $password String
582 * @param $dbName String: database name on the server
583 * @param $failFunction Callback (optional)
584 * @param $flags Integer: database behaviour flags (optional, unused)
585 * @return DatabaseIbm_db2 object
587 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
589 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
593 * Retrieves the most current database error
594 * Forces a database rollback
596 public function lastError() {
597 $connerr = db2_conn_errormsg();
602 $stmterr = db2_stmt_errormsg();
612 * Get the last error number
613 * Return 0 if no error
616 public function lastErrno() {
617 $connerr = db2_conn_error();
618 if ($connerr) return $connerr;
619 $stmterr = db2_stmt_error();
620 if ($stmterr) return $stmterr;
625 * Is a database connection open?
628 public function isOpen() { return $this->mOpened
; }
631 * The DBMS-dependent part of query()
632 * @param $sql String: SQL query.
633 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
637 public function doQuery( $sql ) {
638 //print "<li><pre>$sql</pre></li>";
639 // Switch into the correct namespace
640 $this->applySchema();
642 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
647 $error = db2_stmt_errormsg();
648 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
650 $this->mLastResult
= $ret;
651 $this->mAffectedRows
= null; // Not calculated until asked for
656 * @return string Version information from the database
658 public function getServerVersion() {
659 $info = db2_server_info( $this->mConn
);
660 return $info->DBMS_VER
;
664 * Queries whether a given table exists
667 public function tableExists( $table ) {
668 $schema = $this->mSchema
;
670 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
671 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
673 $res = $this->query( $sql );
674 if (!$res) return false;
676 // If the table exists, there should be one of it
677 @$row = $this->fetchRow($res);
679 if ($count == '1' or $count == 1) {
687 * Fetch the next row from the given result object, in object form.
688 * Fields can be retrieved with $row->fieldname, with fields acting like
691 * @param $res SQL result object as returned from Database::query(), etc.
692 * @return DB2 row object
693 * @throws DBUnexpectedError Thrown if the database returns an error
695 public function fetchObject( $res ) {
696 if ( $res instanceof ResultWrapper
) {
699 @$row = db2_fetch_object( $res );
700 if( $this->lastErrno() ) {
701 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
707 * Fetch the next row from the given result object, in associative array
708 * form. Fields are retrieved with $row['fieldname'].
710 * @param $res SQL result object as returned from Database::query(), etc.
711 * @return DB2 row object
712 * @throws DBUnexpectedError Thrown if the database returns an error
714 public function fetchRow( $res ) {
715 if ( $res instanceof ResultWrapper
) {
718 @$row = db2_fetch_array( $res );
719 if ( $this->lastErrno() ) {
720 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
726 * Override if introduced to base Database class
728 public function initial_setup() {
733 * Create tables, stored procedures, and so on
735 public function setup_database() {
736 // Timeout was being changed earlier due to mysterious crashes
737 // Changing it now may cause more problems than not changing it
738 //set_time_limit(240);
740 // TODO: switch to root login if available
742 // Switch into the correct namespace
743 $this->applySchema();
746 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
748 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
754 // TODO: populate interwiki links
756 if ($this->lastError()) {
757 print "<li>Errors encountered during table creation -- rolled back</li>\n";
758 print "<li>Please install again</li>\n";
765 catch (MWException
$mwe)
767 print "<br><pre>$mwe</pre><br>";
773 * Doesn't escape numbers
774 * @param $s String: string to escape
775 * @return escaped string
777 public function addQuotes( $s ) {
778 //$this->installPrint("DB2::addQuotes($s)\n");
779 if ( is_null( $s ) ) {
781 } else if ($s instanceof Blob
) {
782 return "'".$s->fetch($s)."'";
783 } else if ($s instanceof IBM_DB2Blob
) {
784 return "'".$this->decodeBlob($s)."'";
786 $s = $this->strencode($s);
787 if ( is_numeric($s) ) {
796 * Verifies that a DB2 column/field type is numeric
797 * @return bool true if numeric
798 * @param $type String: DB2 column type
800 public function is_numeric_type( $type ) {
801 switch (strtoupper($type)) {
816 * Alias for addQuotes()
817 * @param $s String: string to escape
818 * @return escaped string
820 public function strencode( $s ) {
821 // Bloody useless function
822 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
823 // But also necessary
824 $s = db2_escape_string($s);
825 // Wide characters are evil -- some of them look like '
826 $s = utf8_encode($s);
828 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
829 $to = array("\\", "''", "\n", "\t", '"', "\r");
830 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
835 * Switch into the database schema
837 protected function applySchema() {
838 if ( !($this->mSchemaSet
) ) {
839 $this->mSchemaSet
= true;
841 $this->doQuery("SET SCHEMA = $this->mSchema");
847 * Start a transaction (mandatory)
849 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
850 // turn off auto-commit
851 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
852 $this->mTrxLevel
= 1;
857 * Must have a preceding begin()
859 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
860 db2_commit($this->mConn
);
861 // turn auto-commit back on
862 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
863 $this->mTrxLevel
= 0;
867 * Cancel a transaction
869 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
870 db2_rollback($this->mConn
);
871 // turn auto-commit back on
872 // not sure if this is appropriate
873 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
874 $this->mTrxLevel
= 0;
878 * Makes an encoded list of strings from an array
880 * LIST_COMMA - comma separated, no field names
881 * LIST_AND - ANDed WHERE clause (without the WHERE)
882 * LIST_OR - ORed WHERE clause (without the WHERE)
883 * LIST_SET - comma separated with field names, like a SET clause
884 * LIST_NAMES - comma separated field names
886 public function makeList( $a, $mode = LIST_COMMA
) {
887 if ( !is_array( $a ) ) {
888 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
893 foreach ( $a as $field => $value ) {
895 if ( $mode == LIST_AND
) {
897 } elseif($mode == LIST_OR
) {
905 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
907 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
909 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
910 if( count( $value ) == 0 ) {
911 throw new MWException( __METHOD__
.': empty input' );
912 } elseif( count( $value ) == 1 ) {
913 // Special-case single values, as IN isn't terribly efficient
914 // Don't necessarily assume the single key is 0; we don't
915 // enforce linear numeric ordering on other arrays here.
916 $value = array_values( $value );
917 $list .= $field." = ".$this->addQuotes( $value[0] );
919 $list .= $field." IN (".$this->makeList($value).") ";
921 } elseif( is_null($value) ) {
922 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
923 $list .= "$field IS ";
924 } elseif ( $mode == LIST_SET
) {
925 $list .= "$field = ";
929 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
930 $list .= "$field = ";
932 if ( $mode == LIST_NAMES
) {
935 // Leo: Can't insert quoted numbers into numeric columns
936 // (?) Might cause other problems. May have to check column type before insertion.
937 else if ( is_numeric($value) ) {
941 $list .= $this->addQuotes( $value );
949 * Construct a LIMIT query with optional offset
950 * This is used for query pages
951 * @param $sql string SQL query we will append the limit too
952 * @param $limit integer the SQL limit
953 * @param $offset integer the SQL offset (default false)
955 public function limitResult($sql, $limit, $offset=false) {
956 if( !is_numeric($limit) ) {
957 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
960 $this->installPrint("Offset parameter not supported in limitResult()\n");
962 // TODO implement proper offset handling
963 // idea: get all the rows between 0 and offset, advance cursor to offset
964 return "$sql FETCH FIRST $limit ROWS ONLY ";
968 * Handle reserved keyword replacement in table names
970 * @param $name Object
972 public function tableName( $name ) {
973 # Replace reserved words with better ones
978 // return 'pagecontent';
982 // we want maximum compatibility with MySQL schema
987 * Generates a timestamp in an insertable format
988 * @return string timestamp value
989 * @param $ts timestamp
991 public function timestamp( $ts=0 ) {
992 // TS_MW cannot be easily distinguished from an integer
993 return wfTimestamp(TS_DB2
,$ts);
997 * Return the next in a sequence, save the value for retrieval via insertId()
998 * @param $seqName String: name of a defined sequence in the database
999 * @return next value in that sequence
1001 public function nextSequenceValue( $seqName ) {
1002 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1003 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1005 $safeseq = preg_replace( "/'/", "''", $seqName );
1006 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1007 $row = $this->fetchRow( $res );
1008 $this->mInsertId = $row[0];
1009 $this->freeResult( $res );
1010 return $this->mInsertId;
1016 * This must be called after nextSequenceVal
1017 * @return Last sequence value used as a primary key
1019 public function insertId() {
1020 return $this->mInsertId
;
1024 * Updates the mInsertId property with the value of the last insert into a generated column
1025 * @param $table String: sanitized table name
1026 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
1027 * @param $stmt Resource: prepared statement resource
1028 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1030 private function calcInsertId($table, $primaryKey, $stmt) {
1032 $id_row = $this->fetchRow($stmt);
1033 $this->mInsertId
= $id_row[0];
1038 * INSERT wrapper, inserts an array into a table
1040 * $args may be a single associative array, or an array of these with numeric keys,
1041 * for multi-row insert
1043 * @param $table String: Name of the table to insert to.
1044 * @param $args Array: Items to insert into the table.
1045 * @param $fname String: Name of the function, for profiling
1046 * @param $options String or Array. Valid options: IGNORE
1048 * @return bool Success of insert operation. IGNORE always returns true.
1050 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1051 if ( !count( $args ) ) {
1054 // get database-specific table name (not used)
1055 $table = $this->tableName( $table );
1056 // format options as an array
1057 if ( !is_array( $options ) ) $options = array( $options );
1058 // format args as an array of arrays
1059 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1060 $args = array($args);
1062 // prevent insertion of NULL into primary key columns
1063 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1064 // if there's only one primary key
1065 // we'll be able to read its value after insertion
1066 $primaryKey = false;
1067 if (count($primaryKeys) == 1) {
1068 $primaryKey = $primaryKeys[0];
1072 $keys = array_keys( $args[0] );
1073 $key_count = count($keys);
1075 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1076 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1080 // If we are not in a transaction, we need to be for savepoint trickery
1082 if (! $this->mTrxLevel
) {
1087 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1088 switch($key_count) {
1094 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1096 // add logic to read back the new primary key value
1098 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1100 $stmt = $this->prepare($sql);
1102 // start a transaction/enter transaction mode
1107 foreach ( $args as $row ) {
1108 // insert each row into the database
1109 $res = $res & $this->execute($stmt, $row);
1110 // get the last inserted value into a generated column
1111 $this->calcInsertId($table, $primaryKey, $stmt);
1115 $olde = error_reporting( 0 );
1116 // For future use, we may want to track the number of actual inserts
1117 // Right now, insert (all writes) simply return true/false
1118 $numrowsinserted = 0;
1120 // always return true
1123 foreach ( $args as $row ) {
1124 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1125 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1127 $res2 = $this->execute($stmt, $row);
1128 // get the last inserted value into a generated column
1129 $this->calcInsertId($table, $primaryKey, $stmt);
1131 $errNum = $this->lastErrno();
1133 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1136 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1141 $olde = error_reporting( $olde );
1142 // Set the affected row count for the whole operation
1143 $this->mAffectedRows
= $numrowsinserted;
1145 // commit either way
1152 * Given a table name and a hash of columns with values
1153 * Removes primary key columns from the hash where the value is NULL
1155 * @param $table String: name of the table
1156 * @param $args Array of hashes of column names with values
1157 * @return Array: tuple containing filtered array of columns, array of primary keys
1159 private function removeNullPrimaryKeys($table, $args) {
1160 $schema = $this->mSchema
;
1161 // find out the primary keys
1162 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1164 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1165 $keys[] = strtolower($row->column_name
);
1167 // remove primary keys
1168 foreach ($args as $ai => $row) {
1169 foreach ($keys as $ki => $key) {
1170 if ($row[$key] == null) {
1176 // return modified hash
1177 return array($args, $keys);
1181 * UPDATE wrapper, takes a condition array and a SET array
1183 * @param $table String: The table to UPDATE
1184 * @param $values An array of values to SET
1185 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1186 * @param $fname String: The Class::Function calling this function
1188 * @param $options An array of UPDATE options, can be one or
1189 * more of IGNORE, LOW_PRIORITY
1192 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1193 $table = $this->tableName( $table );
1194 $opts = $this->makeUpdateOptions( $options );
1195 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1196 if ( $conds != '*' ) {
1197 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1199 return $this->query( $sql, $fname );
1203 * DELETE query wrapper
1205 * Use $conds == "*" to delete all rows
1207 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1209 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1211 $table = $this->tableName( $table );
1212 $sql = "DELETE FROM $table";
1213 if ( $conds != '*' ) {
1214 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1216 return $this->query( $sql, $fname );
1220 * Returns the number of rows affected by the last query or 0
1221 * @return Integer: the number of rows affected by the last query
1223 public function affectedRows() {
1224 if ( !is_null( $this->mAffectedRows
) ) {
1225 // Forced result for simulated queries
1226 return $this->mAffectedRows
;
1228 if( empty( $this->mLastResult
) )
1230 return db2_num_rows( $this->mLastResult
);
1234 * Simulates REPLACE with a DELETE followed by INSERT
1235 * @param $table Object
1236 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1237 * @param $rows Array: rows to insert
1238 * @param $fname String: name of the function for profiling
1241 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1242 $table = $this->tableName( $table );
1244 if (count($rows)==0) {
1249 if ( !is_array( reset( $rows ) ) ) {
1250 $rows = array( $rows );
1253 foreach( $rows as $row ) {
1254 # Delete rows which collide
1255 if ( $uniqueIndexes ) {
1256 $sql = "DELETE FROM $table WHERE ";
1258 foreach ( $uniqueIndexes as $index ) {
1265 if ( is_array( $index ) ) {
1267 foreach ( $index as $col ) {
1273 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1276 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1280 $this->query( $sql, $fname );
1283 # Now insert the row
1284 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1285 $this->makeList( $row, LIST_COMMA
) . ')';
1286 $this->query( $sql, $fname );
1291 * Returns the number of rows in the result set
1292 * Has to be called right after the corresponding select query
1293 * @param $res Object result set
1294 * @return Integer: number of rows
1296 public function numRows( $res ) {
1297 if ( $res instanceof ResultWrapper
) {
1298 $res = $res->result
;
1300 if ( $this->mNumRows
) {
1301 return $this->mNumRows
;
1309 * Moves the row pointer of the result set
1310 * @param $res Object: result set
1311 * @param $row Integer: row number
1312 * @return success or failure
1314 public function dataSeek( $res, $row ) {
1315 if ( $res instanceof ResultWrapper
) {
1316 $res = $res->result
;
1318 return db2_fetch_row( $res, $row );
1322 # Fix notices in Block.php
1326 * Frees memory associated with a statement resource
1327 * @param $res Object: statement resource to free
1328 * @return Boolean success or failure
1330 public function freeResult( $res ) {
1331 if ( $res instanceof ResultWrapper
) {
1332 $res = $res->result
;
1334 if ( !@db2_free_result
( $res ) ) {
1335 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1340 * Returns the number of columns in a resource
1341 * @param $res Object: statement resource
1342 * @return Number of fields/columns in resource
1344 public function numFields( $res ) {
1345 if ( $res instanceof ResultWrapper
) {
1346 $res = $res->result
;
1348 return db2_num_fields( $res );
1352 * Returns the nth column name
1353 * @param $res Object: statement resource
1354 * @param $n Integer: Index of field or column
1355 * @return String name of nth column
1357 public function fieldName( $res, $n ) {
1358 if ( $res instanceof ResultWrapper
) {
1359 $res = $res->result
;
1361 return db2_field_name( $res, $n );
1367 * @param $table Array or string, table name(s) (prefix auto-added)
1368 * @param $vars Array or string, field name(s) to be retrieved
1369 * @param $conds Array or string, condition(s) for WHERE
1370 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1371 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1372 * see Database::makeSelectOptions code for list of supported stuff
1373 * @param $join_conds Associative array of table join conditions (optional)
1374 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1375 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1377 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1379 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1381 // We must adjust for offset
1382 if ( isset( $options['LIMIT'] ) ) {
1383 if ( isset ($options['OFFSET'] ) ) {
1384 $limit = $options['LIMIT'];
1385 $offset = $options['OFFSET'];
1390 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1391 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1394 // we want the count
1395 $vars2 = array('count(*) as num_rows');
1396 // respecting just the limit option
1397 $options2 = array();
1398 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1399 // but don't try to emulate for GROUP BY
1400 if ( isset( $options['GROUP BY'] ) ) return $res;
1402 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1403 $obj = $this->fetchObject($res2);
1404 $this->mNumRows
= $obj->num_rows
;
1411 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1412 * Has limited support for per-column options (colnum => 'DISTINCT')
1416 * @param $options Associative array of options to be turned into
1417 * an SQL query, valid keys are listed in the function.
1420 function makeSelectOptions( $options ) {
1421 $preLimitTail = $postLimitTail = '';
1424 $noKeyOptions = array();
1425 foreach ( $options as $key => $option ) {
1426 if ( is_numeric( $key ) ) {
1427 $noKeyOptions[$option] = true;
1431 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1432 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1433 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1435 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1437 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1441 * Returns link to IBM DB2 free download
1442 * @return string wikitext of a link to the server software's web site
1444 public function getSoftwareLink() {
1445 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1449 * Get search engine class. All subclasses of this
1450 * need to implement this if they wish to use searching.
1454 public function getSearchEngine() {
1455 return "SearchIBM_DB2";
1459 * Did the last database access fail because of deadlock?
1462 public function wasDeadlock() {
1464 $err = $this->lastErrno();
1466 case '40001': // sql0911n, Deadlock or timeout, rollback
1467 case '57011': // sql0904n, Resource unavailable, no rollback
1468 case '57033': // sql0913n, Deadlock or timeout, no rollback
1469 $this->installPrint("In a deadlock because of SQLSTATE $err");
1476 * Ping the server and try to reconnect if it there is no connection
1477 * The connection may be closed and reopened while this happens
1478 * @return Boolean: whether the connection exists
1480 public function ping() {
1481 // db2_ping() doesn't exist
1484 if ($this->mCataloged
== null) {
1487 else if ($this->mCataloged
) {
1488 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1490 else if (!$this->mCataloged
) {
1491 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1495 ######################################
1496 # Unimplemented and not applicable
1497 ######################################
1503 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1513 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1518 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1521 * @return string $sql
1524 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1527 * Only useful with fake prepare like in base Database class
1530 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1532 ######################################
1534 ######################################
1537 * Returns information about an index
1538 * If errors are explicitly ignored, returns NULL on failure
1539 * @param $table String: table name
1540 * @param $index String: index name
1541 * @param $fname String: function name for logging and profiling
1542 * @return Object query row in object form
1544 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1545 $table = $this->tableName( $table );
1547 SELECT name as indexname
1548 FROM sysibm.sysindexes si
1549 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1551 $res = $this->query( $sql, $fname );
1555 $row = $this->fetchObject( $res );
1556 if ($row != null) return $row;
1561 * Returns an information object on a table column
1562 * @param $table String: table name
1563 * @param $field String: column name
1564 * @return IBM_DB2Field
1566 public function fieldInfo( $table, $field ) {
1567 return IBM_DB2Field
::fromText($this, $table, $field);
1571 * db2_field_type() wrapper
1572 * @param $res Object: result of executed statement
1573 * @param $index Mixed: number or name of the column
1574 * @return String column type
1576 public function fieldType( $res, $index ) {
1577 if ( $res instanceof ResultWrapper
) {
1578 $res = $res->result
;
1580 return db2_field_type( $res, $index );
1584 * Verifies that an index was created as unique
1585 * @param $table String: table name
1586 * @param $index String: index name
1587 * @param $fname function name for profiling
1590 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1591 $table = $this->tableName( $table );
1593 SELECT si.name as indexname
1594 FROM sysibm.sysindexes si
1595 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1596 AND si.uniquerule IN ('U', 'P')
1598 $res = $this->query( $sql, $fname );
1602 if ($this->fetchObject( $res )) {
1610 * Returns the size of a text field, or -1 for "unlimited"
1611 * @param $table String: table name
1612 * @param $field String: column name
1613 * @return Integer: length or -1 for unlimited
1615 public function textFieldSize( $table, $field ) {
1616 $table = $this->tableName( $table );
1618 SELECT length as size
1619 FROM sysibm.syscolumns sc
1620 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1622 $res = $this->query($sql);
1623 $row = $this->fetchObject($res);
1625 $this->freeResult( $res );
1630 * DELETE where the condition is a join
1631 * @param $delTable String: deleting from this table
1632 * @param $joinTable String: using data from this table
1633 * @param $delVar String: variable in deleteable table
1634 * @param $joinVar String: variable in data table
1635 * @param $conds Array: conditionals for join table
1636 * @param $fname String: function name for profiling
1638 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1640 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1643 $delTable = $this->tableName( $delTable );
1644 $joinTable = $this->tableName( $joinTable );
1645 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1646 if ( $conds != '*' ) {
1647 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1651 $this->query( $sql, $fname );
1655 * Description is left as an exercise for the reader
1656 * @param $b Mixed: data to be encoded
1657 * @return IBM_DB2Blob
1659 public function encodeBlob($b) {
1660 return new IBM_DB2Blob($b);
1664 * Description is left as an exercise for the reader
1665 * @param $b IBM_DB2Blob: data to be decoded
1668 public function decodeBlob($b) {
1669 return $b->getData();
1673 * Convert into a list of string being concatenated
1674 * @param $stringList Array: strings that need to be joined together by the SQL engine
1675 * @return String: joined by the concatenation operator
1677 public function buildConcat( $stringList ) {
1678 // || is equivalent to CONCAT
1679 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1680 return implode( ' || ', $stringList );
1684 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1685 * @param $column String: name of timestamp column
1686 * @return String: SQL code
1688 public function extractUnixEpoch( $column ) {
1690 // see SpecialAncientpages
1693 ######################################
1694 # Prepared statements
1695 ######################################
1698 * Intended to be compatible with the PEAR::DB wrapper functions.
1699 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1701 * ? = scalar value, quoted as necessary
1702 * ! = raw SQL bit (a function for instance)
1703 * & = filename; reads the file and inserts as a blob
1704 * (we don't use this though...)
1705 * @param $sql String: SQL statement with appropriate markers
1706 * @param $func String: Name of the function, for profiling
1707 * @return resource a prepared DB2 SQL statement
1709 public function prepare( $sql, $func = 'DB2::prepare' ) {
1710 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1715 * Frees resources associated with a prepared statement
1716 * @return Boolean success or failure
1718 public function freePrepared( $prepared ) {
1719 return db2_free_stmt($prepared);
1723 * Execute a prepared query with the various arguments
1724 * @param $prepared String: the prepared sql
1725 * @param $args Mixed: either an array here, or put scalars as varargs
1726 * @return Resource: results object
1728 public function execute( $prepared, $args = null ) {
1729 if( !is_array( $args ) ) {
1731 $args = func_get_args();
1732 array_shift( $args );
1734 $res = db2_execute($prepared, $args);
1739 * Prepare & execute an SQL statement, quoting and inserting arguments
1740 * in the appropriate places.
1741 * @param $query String
1744 public function safeQuery( $query, $args = null ) {
1745 // copied verbatim from Database.php
1746 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1747 if( !is_array( $args ) ) {
1749 $args = func_get_args();
1750 array_shift( $args );
1752 $retval = $this->execute( $prepared, $args );
1753 $this->freePrepared( $prepared );
1758 * For faking prepared SQL statements on DBs that don't support
1760 * @param $preparedQuery String: a 'preparable' SQL statement
1761 * @param $args Array of arguments to fill it with
1762 * @return String: executable statement
1764 public function fillPrepared( $preparedQuery, $args ) {
1766 $this->preparedArgs
=& $args;
1768 foreach ($args as $i => $arg) {
1769 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1772 return $preparedQuery;
1776 * Switches module between regular and install modes
1778 public function setMode($mode) {
1779 $old = $this->mMode
;
1780 $this->mMode
= $mode;
1785 * Bitwise negation of a column or value in SQL
1786 * Same as (~field) in C
1787 * @param $field String
1790 function bitNot($field) {
1791 //expecting bit-fields smaller than 4bytes
1792 return 'BITNOT('.$bitField.')';
1796 * Bitwise AND of two columns or values in SQL
1797 * Same as (fieldLeft & fieldRight) in C
1798 * @param $fieldLeft String
1799 * @param $fieldRight String
1802 function bitAnd($fieldLeft, $fieldRight) {
1803 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1807 * Bitwise OR of two columns or values in SQL
1808 * Same as (fieldLeft | fieldRight) in C
1809 * @param $fieldLeft String
1810 * @param $fieldRight String
1813 function bitOr($fieldLeft, $fieldRight) {
1814 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';