c91dc868334e32efffc741bab3f619e0fad11212
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;
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)
185 * Administrative: (8)
187 * installErrorHandler
188 * restoreErrorHandler
189 * connectionErrorHandler
190 * reportConnectionError
204 * 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] - Where??
298 * textFieldSize [Done]
300 * Generation: 16 / 16
304 * makeSelectOptions [Done]
305 * estimateRowCount [Done]
306 * nextSequenceValue [Done]
307 * useIndexClause [Done]
310 * lowPriorityOption [Done]
312 * limitResultForUpdate [Done]
319 ######################################
320 # Getters and Setters
321 ######################################
324 * Returns true if this database supports (and uses) cascading deletes
326 function cascadingDeletes() {
331 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
333 function cleanupTriggers() {
338 * Returns true if this database is strict about what can be put into an IP field.
339 * Specifically, it uses a NULL value instead of an empty string.
341 function strictIPs() {
346 * Returns true if this database uses timestamps rather than integers
348 function realTimestamps() {
353 * Returns true if this database does an implicit sort when doing GROUP BY
355 function implicitGroupby() {
360 * Returns true if this database does an implicit order by when the column has an index
361 * For example: SELECT page_title FROM page LIMIT 1
363 function implicitOrderby() {
368 * Returns true if this database can do a native search on IP columns
369 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
371 function searchableIPs() {
376 * Returns true if this database can use functional indexes
378 function functionalIndexes() {
383 * Returns a unique string representing the wiki on the server
385 function getWikiID() {
386 if( $this->mSchema
) {
387 return "{$this->mDBname}-{$this->mSchema}";
389 return $this->mDBname
;
397 ######################################
399 ######################################
404 * @param $server String: hostname of database server
405 * @param $user String: username
406 * @param $password String: password
407 * @param $dbName String: database name on the server
408 * @param $failFunction Callback (optional)
409 * @param $flags Integer: database behaviour flags (optional, unused)
410 * @param $schema String
412 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
413 $dbName = false, $failFunction = false, $flags = 0,
414 $schema = self
::USE_GLOBAL
)
417 global $wgOut, $wgDBmwschema;
418 # Can't get a reference if it hasn't been set yet
419 if ( !isset( $wgOut ) ) {
422 $this->mOut
=& $wgOut;
423 $this->mFailFunction
= $failFunction;
424 $this->mFlags
= DBO_TRX |
$flags;
426 if ( $schema == self
::USE_GLOBAL
) {
427 $this->mSchema
= $wgDBmwschema;
430 $this->mSchema
= $schema;
433 // configure the connection and statement objects
434 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self
::CONN_OPTION | self
::STMT_OPTION
);
435 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self
::STMT_OPTION
);
436 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self
::STMT_OPTION
);
438 $this->open( $server, $user, $password, $dbName);
442 * Enables options only if the ibm_db2 extension version supports them
443 * @param $name String: name of the option in the options array
444 * @param $const String: name of the constant holding the right option value
445 * @param $type Integer: whether this is a Connection or Statement otion
447 private function setDB2Option($name, $const, $type) {
448 if (defined($const)) {
449 if ($type & self
::CONN_OPTION
) $this->mConnOptions
[$name] = constant($const);
450 if ($type & self
::STMT_OPTION
) $this->mStmtOptions
[$name] = constant($const);
453 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
458 * Outputs debug information in the appropriate place
459 * @param $string String: the relevant debug message
461 private function installPrint($string) {
463 if ($this->mMode
== self
::INSTALL_MODE
) {
464 print "<li>$string</li>";
470 * Opens a database connection and returns it
471 * Closes any existing connection
472 * @return a fresh connection
473 * @param $server String: hostname
474 * @param $user String
475 * @param $password String
476 * @param $dbName String: database name
478 public function open( $server, $user, $password, $dbName )
480 // Load the port number
481 global $wgDBport, $wgDBcataloged;
482 wfProfileIn( __METHOD__
);
484 // Load IBM DB2 driver if missing
487 // Test for IBM DB2 support, to avoid suppressed fatal error
488 if ( !function_exists( 'db2_connect' ) ) {
489 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
490 $this->installPrint($error);
491 $this->reportConnectionError($error);
494 if (!strlen($user)) { // Copied from Postgres
498 // Close existing connection
501 $this->mServer
= $server;
502 $this->mPort
= $port = $wgDBport;
503 $this->mUser
= $user;
504 $this->mPassword
= $password;
505 $this->mDBname
= $dbName;
506 $this->mCataloged
= $cataloged = $wgDBcataloged;
508 if ( $cataloged == self
::CATALOGED
) {
509 $this->openCataloged($dbName, $user, $password);
511 elseif ( $cataloged == self
::UNCATALOGED
) {
512 $this->openUncataloged($dbName, $user, $password, $server, $port);
514 // Apply connection config
515 db2_set_option($this->mConn
, $this->mConnOptions
, 1);
516 // Not all MediaWiki code is transactional
517 // Rather, turn autocommit off in the begin function and turn on after a commit
518 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
520 if ( !$this->mConn
) {
521 $this->installPrint( "DB connection error\n" );
522 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
523 $this->installPrint( $this->lastError()."\n" );
527 $this->mOpened
= true;
528 $this->applySchema();
530 wfProfileOut( __METHOD__
);
535 * Opens a cataloged database connection, sets mConn
537 protected function openCataloged( $dbName, $user, $password )
539 @$this->mConn
= db2_connect($dbName, $user, $password);
543 * Opens an uncataloged database connection, sets mConn
545 protected function openUncataloged( $dbName, $user, $password, $server, $port )
547 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
548 $str .= "DATABASE=$dbName;";
549 $str .= "HOSTNAME=$server;";
550 if ($port) $str .= "PORT=$port;";
551 $str .= "PROTOCOL=TCPIP;";
552 $str .= "UID=$user;";
553 $str .= "PWD=$password;";
555 @$this->mConn
= db2_connect($str, $user, $password);
559 * Closes a database connection, if it is open
560 * Returns success, true if already closed
562 public function close() {
563 $this->mOpened
= false;
564 if ( $this->mConn
) {
565 if ($this->trxLevel() > 0) {
568 return db2_close( $this->mConn
);
576 * Returns a fresh instance of this class
578 * @param $server String: hostname of database server
579 * @param $user String: username
580 * @param $password String
581 * @param $dbName String: database name on the server
582 * @param $failFunction Callback (optional)
583 * @param $flags Integer: database behaviour flags (optional, unused)
584 * @return DatabaseIbm_db2 object
586 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
588 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
592 * Retrieves the most current database error
593 * Forces a database rollback
595 public function lastError() {
596 $connerr = db2_conn_errormsg();
601 $stmterr = db2_stmt_errormsg();
611 * Get the last error number
612 * Return 0 if no error
615 public function lastErrno() {
616 $connerr = db2_conn_error();
617 if ($connerr) return $connerr;
618 $stmterr = db2_stmt_error();
619 if ($stmterr) return $stmterr;
624 * Is a database connection open?
627 public function isOpen() { return $this->mOpened
; }
630 * The DBMS-dependent part of query()
631 * @param $sql String: SQL query.
632 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
636 public function doQuery( $sql ) {
637 //print "<li><pre>$sql</pre></li>";
638 // Switch into the correct namespace
639 $this->applySchema();
641 $ret = db2_exec( $this->mConn
, $sql, $this->mStmtOptions
);
646 $error = db2_stmt_errormsg();
647 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
649 $this->mLastResult
= $ret;
650 $this->mAffectedRows
= null; // Not calculated until asked for
655 * @return string Version information from the database
657 public function getServerVersion() {
658 $info = db2_server_info( $this->mConn
);
659 return $info->DBMS_VER
;
663 * Queries whether a given table exists
666 public function tableExists( $table ) {
667 $schema = $this->mSchema
;
669 SELECT
COUNT(*) FROM SYSIBM
.SYSTABLES ST
670 WHERE ST
.NAME
= '$table' AND ST
.CREATOR
= '$schema'
672 $res = $this->query( $sql );
673 if (!$res) return false;
675 // If the table exists, there should be one of it
676 @$row = $this->fetchRow($res);
678 if ($count == '1' or $count == 1) {
686 * Fetch the next row from the given result object, in object form.
687 * Fields can be retrieved with $row->fieldname, with fields acting like
690 * @param $res SQL result object as returned from Database::query(), etc.
691 * @return DB2 row object
692 * @throws DBUnexpectedError Thrown if the database returns an error
694 public function fetchObject( $res ) {
695 if ( $res instanceof ResultWrapper
) {
698 @$row = db2_fetch_object( $res );
699 if( $this->lastErrno() ) {
700 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
706 * Fetch the next row from the given result object, in associative array
707 * form. Fields are retrieved with $row['fieldname'].
709 * @param $res SQL result object as returned from Database::query(), etc.
710 * @return DB2 row object
711 * @throws DBUnexpectedError Thrown if the database returns an error
713 public function fetchRow( $res ) {
714 if ( $res instanceof ResultWrapper
) {
717 @$row = db2_fetch_array( $res );
718 if ( $this->lastErrno() ) {
719 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
725 * Override if introduced to base Database class
727 public function initial_setup() {
732 * Create tables, stored procedures, and so on
734 public function setup_database() {
735 // Timeout was being changed earlier due to mysterious crashes
736 // Changing it now may cause more problems than not changing it
737 //set_time_limit(240);
739 // TODO: switch to root login if available
741 // Switch into the correct namespace
742 $this->applySchema();
745 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
747 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
753 // TODO: populate interwiki links
755 if ($this->lastError()) {
756 print "<li>Errors encountered during table creation -- rolled back</li>\n";
757 print "<li>Please install again</li>\n";
764 catch (MWException
$mwe)
766 print "<br><pre>$mwe</pre><br>";
772 * Doesn't escape numbers
773 * @param $s String: string to escape
774 * @return escaped string
776 public function addQuotes( $s ) {
777 //$this->installPrint("DB2::addQuotes($s)\n");
778 if ( is_null( $s ) ) {
780 } else if ($s instanceof Blob
) {
781 return "'".$s->fetch($s)."'";
782 } else if ($s instanceof IBM_DB2Blob
) {
783 return "'".$this->decodeBlob($s)."'";
785 $s = $this->strencode($s);
786 if ( is_numeric($s) ) {
795 * Verifies that a DB2 column/field type is numeric
796 * @return bool true if numeric
797 * @param $type String: DB2 column type
799 public function is_numeric_type( $type ) {
800 switch (strtoupper($type)) {
815 * Alias for addQuotes()
816 * @param $s String: string to escape
817 * @return escaped string
819 public function strencode( $s ) {
820 // Bloody useless function
821 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
822 // But also necessary
823 $s = db2_escape_string($s);
824 // Wide characters are evil -- some of them look like '
825 $s = utf8_encode($s);
827 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
828 $to = array("\\", "''", "\n", "\t", '"', "\r");
829 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
834 * Switch into the database schema
836 protected function applySchema() {
837 if ( !($this->mSchemaSet
) ) {
838 $this->mSchemaSet
= true;
840 $this->doQuery("SET SCHEMA = $this->mSchema");
846 * Start a transaction (mandatory)
848 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
849 // turn off auto-commit
850 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_OFF
);
851 $this->mTrxLevel
= 1;
856 * Must have a preceding begin()
858 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
859 db2_commit($this->mConn
);
860 // turn auto-commit back on
861 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
862 $this->mTrxLevel
= 0;
866 * Cancel a transaction
868 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
869 db2_rollback($this->mConn
);
870 // turn auto-commit back on
871 // not sure if this is appropriate
872 db2_autocommit($this->mConn
, DB2_AUTOCOMMIT_ON
);
873 $this->mTrxLevel
= 0;
877 * Makes an encoded list of strings from an array
879 * LIST_COMMA - comma separated, no field names
880 * LIST_AND - ANDed WHERE clause (without the WHERE)
881 * LIST_OR - ORed WHERE clause (without the WHERE)
882 * LIST_SET - comma separated with field names, like a SET clause
883 * LIST_NAMES - comma separated field names
885 public function makeList( $a, $mode = LIST_COMMA
) {
886 if ( !is_array( $a ) ) {
887 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
892 foreach ( $a as $field => $value ) {
894 if ( $mode == LIST_AND
) {
896 } elseif($mode == LIST_OR
) {
904 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
906 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
908 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
909 if( count( $value ) == 0 ) {
910 throw new MWException( __METHOD__
.': empty input' );
911 } elseif( count( $value ) == 1 ) {
912 // Special-case single values, as IN isn't terribly efficient
913 // Don't necessarily assume the single key is 0; we don't
914 // enforce linear numeric ordering on other arrays here.
915 $value = array_values( $value );
916 $list .= $field." = ".$this->addQuotes( $value[0] );
918 $list .= $field." IN (".$this->makeList($value).") ";
920 } elseif( is_null($value) ) {
921 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
922 $list .= "$field IS ";
923 } elseif ( $mode == LIST_SET
) {
924 $list .= "$field = ";
928 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
929 $list .= "$field = ";
931 if ( $mode == LIST_NAMES
) {
934 // Leo: Can't insert quoted numbers into numeric columns
935 // (?) Might cause other problems. May have to check column type before insertion.
936 else if ( is_numeric($value) ) {
940 $list .= $this->addQuotes( $value );
948 * Construct a LIMIT query with optional offset
949 * This is used for query pages
950 * @param $sql string SQL query we will append the limit too
951 * @param $limit integer the SQL limit
952 * @param $offset integer the SQL offset (default false)
954 public function limitResult($sql, $limit, $offset=false) {
955 if( !is_numeric($limit) ) {
956 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
959 $this->installPrint("Offset parameter not supported in limitResult()\n");
961 // TODO implement proper offset handling
962 // idea: get all the rows between 0 and offset, advance cursor to offset
963 return "$sql FETCH FIRST $limit ROWS ONLY ";
967 * Handle reserved keyword replacement in table names
969 * @param $name Object
971 public function tableName( $name ) {
972 # Replace reserved words with better ones
977 // return 'pagecontent';
981 // we want maximum compatibility with MySQL schema
986 * Generates a timestamp in an insertable format
987 * @return string timestamp value
988 * @param $ts timestamp
990 public function timestamp( $ts=0 ) {
991 // TS_MW cannot be easily distinguished from an integer
992 return wfTimestamp(TS_DB2
,$ts);
996 * Return the next in a sequence, save the value for retrieval via insertId()
997 * @param $seqName String: name of a defined sequence in the database
998 * @return next value in that sequence
1000 public function nextSequenceValue( $seqName ) {
1001 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1002 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1004 $safeseq = preg_replace( "/'/", "''", $seqName );
1005 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1006 $row = $this->fetchRow( $res );
1007 $this->mInsertId = $row[0];
1008 return $this->mInsertId;
1014 * This must be called after nextSequenceVal
1015 * @return Last sequence value used as a primary key
1017 public function insertId() {
1018 return $this->mInsertId
;
1022 * Updates the mInsertId property with the value of the last insert into a generated column
1023 * @param $table String: sanitized table name
1024 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
1025 * @param $stmt Resource: prepared statement resource
1026 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1028 private function calcInsertId($table, $primaryKey, $stmt) {
1030 $id_row = $this->fetchRow($stmt);
1031 $this->mInsertId
= $id_row[0];
1036 * INSERT wrapper, inserts an array into a table
1038 * $args may be a single associative array, or an array of these with numeric keys,
1039 * for multi-row insert
1041 * @param $table String: Name of the table to insert to.
1042 * @param $args Array: Items to insert into the table.
1043 * @param $fname String: Name of the function, for profiling
1044 * @param $options String or Array. Valid options: IGNORE
1046 * @return bool Success of insert operation. IGNORE always returns true.
1048 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1049 if ( !count( $args ) ) {
1052 // get database-specific table name (not used)
1053 $table = $this->tableName( $table );
1054 // format options as an array
1055 if ( !is_array( $options ) ) $options = array( $options );
1056 // format args as an array of arrays
1057 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1058 $args = array($args);
1060 // prevent insertion of NULL into primary key columns
1061 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1062 // if there's only one primary key
1063 // we'll be able to read its value after insertion
1064 $primaryKey = false;
1065 if (count($primaryKeys) == 1) {
1066 $primaryKey = $primaryKeys[0];
1070 $keys = array_keys( $args[0] );
1071 $key_count = count($keys);
1073 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1074 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
1078 // If we are not in a transaction, we need to be for savepoint trickery
1080 if (! $this->mTrxLevel
) {
1085 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1086 switch($key_count) {
1092 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1094 // add logic to read back the new primary key value
1096 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1098 $stmt = $this->prepare($sql);
1100 // start a transaction/enter transaction mode
1104 foreach ( $args as $row ) {
1105 // insert each row into the database
1106 $res = $res & $this->execute($stmt, $row);
1107 // get the last inserted value into a generated column
1108 $this->calcInsertId($table, $primaryKey, $stmt);
1112 $olde = error_reporting( 0 );
1113 // For future use, we may want to track the number of actual inserts
1114 // Right now, insert (all writes) simply return true/false
1115 $numrowsinserted = 0;
1117 // always return true
1120 foreach ( $args as $row ) {
1121 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1122 db2_exec($this->mConn
, $overhead, $this->mStmtOptions
);
1124 $this->execute($stmt, $row);
1125 // get the last inserted value into a generated column
1126 $this->calcInsertId($table, $primaryKey, $stmt);
1128 $errNum = $this->lastErrno();
1130 db2_exec( $this->mConn
, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions
);
1133 db2_exec( $this->mConn
, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions
);
1138 $olde = error_reporting( $olde );
1139 // Set the affected row count for the whole operation
1140 $this->mAffectedRows
= $numrowsinserted;
1142 // commit either way
1149 * Given a table name and a hash of columns with values
1150 * Removes primary key columns from the hash where the value is NULL
1152 * @param $table String: name of the table
1153 * @param $args Array of hashes of column names with values
1154 * @return Array: tuple containing filtered array of columns, array of primary keys
1156 private function removeNullPrimaryKeys($table, $args) {
1157 $schema = $this->mSchema
;
1158 // find out the primary keys
1159 $keyres = db2_primary_keys($this->mConn
, null, strtoupper($schema), strtoupper($table));
1161 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1162 $keys[] = strtolower($row->column_name
);
1164 // remove primary keys
1165 foreach ($args as $ai => $row) {
1166 foreach ($keys as $ki => $key) {
1167 if ($row[$key] == null) {
1173 // return modified hash
1174 return array($args, $keys);
1178 * UPDATE wrapper, takes a condition array and a SET array
1180 * @param $table String: The table to UPDATE
1181 * @param $values An array of values to SET
1182 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1183 * @param $fname String: The Class::Function calling this function
1185 * @param $options An array of UPDATE options, can be one or
1186 * more of IGNORE, LOW_PRIORITY
1189 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1190 $table = $this->tableName( $table );
1191 $opts = $this->makeUpdateOptions( $options );
1192 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1193 if ( $conds != '*' ) {
1194 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1196 return $this->query( $sql, $fname );
1200 * DELETE query wrapper
1202 * Use $conds == "*" to delete all rows
1204 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1206 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1208 $table = $this->tableName( $table );
1209 $sql = "DELETE FROM $table";
1210 if ( $conds != '*' ) {
1211 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1213 return $this->query( $sql, $fname );
1217 * Returns the number of rows affected by the last query or 0
1218 * @return Integer: the number of rows affected by the last query
1220 public function affectedRows() {
1221 if ( !is_null( $this->mAffectedRows
) ) {
1222 // Forced result for simulated queries
1223 return $this->mAffectedRows
;
1225 if( empty( $this->mLastResult
) )
1227 return db2_num_rows( $this->mLastResult
);
1231 * Simulates REPLACE with a DELETE followed by INSERT
1232 * @param $table Object
1233 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1234 * @param $rows Array: rows to insert
1235 * @param $fname String: name of the function for profiling
1238 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1239 $table = $this->tableName( $table );
1241 if (count($rows)==0) {
1246 if ( !is_array( reset( $rows ) ) ) {
1247 $rows = array( $rows );
1250 foreach( $rows as $row ) {
1251 # Delete rows which collide
1252 if ( $uniqueIndexes ) {
1253 $sql = "DELETE FROM $table WHERE ";
1255 foreach ( $uniqueIndexes as $index ) {
1262 if ( is_array( $index ) ) {
1264 foreach ( $index as $col ) {
1270 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1273 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1277 $this->query( $sql, $fname );
1280 # Now insert the row
1281 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1282 $this->makeList( $row, LIST_COMMA
) . ')';
1283 $this->query( $sql, $fname );
1288 * Returns the number of rows in the result set
1289 * Has to be called right after the corresponding select query
1290 * @param $res Object result set
1291 * @return Integer: number of rows
1293 public function numRows( $res ) {
1294 if ( $res instanceof ResultWrapper
) {
1295 $res = $res->result
;
1297 if ( $this->mNumRows
) {
1298 return $this->mNumRows
;
1306 * Moves the row pointer of the result set
1307 * @param $res Object: result set
1308 * @param $row Integer: row number
1309 * @return success or failure
1311 public function dataSeek( $res, $row ) {
1312 if ( $res instanceof ResultWrapper
) {
1313 $res = $res->result
;
1315 return db2_fetch_row( $res, $row );
1319 # Fix notices in Block.php
1323 * Frees memory associated with a statement resource
1324 * @param $res Object: statement resource to free
1325 * @return Boolean success or failure
1327 public function freeResult( $res ) {
1328 if ( $res instanceof ResultWrapper
) {
1329 $res = $res->result
;
1331 if ( !@db2_free_result
( $res ) ) {
1332 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1337 * Returns the number of columns in a resource
1338 * @param $res Object: statement resource
1339 * @return Number of fields/columns in resource
1341 public function numFields( $res ) {
1342 if ( $res instanceof ResultWrapper
) {
1343 $res = $res->result
;
1345 return db2_num_fields( $res );
1349 * Returns the nth column name
1350 * @param $res Object: statement resource
1351 * @param $n Integer: Index of field or column
1352 * @return String name of nth column
1354 public function fieldName( $res, $n ) {
1355 if ( $res instanceof ResultWrapper
) {
1356 $res = $res->result
;
1358 return db2_field_name( $res, $n );
1364 * @param $table Array or string, table name(s) (prefix auto-added)
1365 * @param $vars Array or string, field name(s) to be retrieved
1366 * @param $conds Array or string, condition(s) for WHERE
1367 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1368 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1369 * see Database::makeSelectOptions code for list of supported stuff
1370 * @param $join_conds Associative array of table join conditions (optional)
1371 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1372 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1374 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1376 $res = parent
::select( $table, $vars, $conds, $fname, $options, $join_conds );
1378 // We must adjust for offset
1379 if ( isset( $options['LIMIT'] ) ) {
1380 if ( isset ($options['OFFSET'] ) ) {
1381 $limit = $options['LIMIT'];
1382 $offset = $options['OFFSET'];
1387 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1388 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1391 // we want the count
1392 $vars2 = array('count(*) as num_rows');
1393 // respecting just the limit option
1394 $options2 = array();
1395 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1396 // but don't try to emulate for GROUP BY
1397 if ( isset( $options['GROUP BY'] ) ) return $res;
1399 $res2 = parent
::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1400 $obj = $this->fetchObject($res2);
1401 $this->mNumRows
= $obj->num_rows
;
1408 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1409 * Has limited support for per-column options (colnum => 'DISTINCT')
1413 * @param $options Associative array of options to be turned into
1414 * an SQL query, valid keys are listed in the function.
1417 function makeSelectOptions( $options ) {
1418 $preLimitTail = $postLimitTail = '';
1421 $noKeyOptions = array();
1422 foreach ( $options as $key => $option ) {
1423 if ( is_numeric( $key ) ) {
1424 $noKeyOptions[$option] = true;
1428 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1429 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1430 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1432 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1434 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1438 * Returns link to IBM DB2 free download
1439 * @return string wikitext of a link to the server software's web site
1441 public function getSoftwareLink() {
1442 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1446 * Get search engine class. All subclasses of this
1447 * need to implement this if they wish to use searching.
1451 public function getSearchEngine() {
1452 return "SearchIBM_DB2";
1456 * Did the last database access fail because of deadlock?
1459 public function wasDeadlock() {
1461 $err = $this->lastErrno();
1463 case '40001': // sql0911n, Deadlock or timeout, rollback
1464 case '57011': // sql0904n, Resource unavailable, no rollback
1465 case '57033': // sql0913n, Deadlock or timeout, no rollback
1466 $this->installPrint("In a deadlock because of SQLSTATE $err");
1473 * Ping the server and try to reconnect if it there is no connection
1474 * The connection may be closed and reopened while this happens
1475 * @return Boolean: whether the connection exists
1477 public function ping() {
1478 // db2_ping() doesn't exist
1481 if ($this->mCataloged
== null) {
1484 else if ($this->mCataloged
) {
1485 $this->mConn
= $this->openCataloged($this->mDBName
, $this->mUser
, $this->mPassword
);
1487 else if (!$this->mCataloged
) {
1488 $this->mConn
= $this->openUncataloged($this->mDBName
, $this->mUser
, $this->mPassword
, $this->mServer
, $this->mPort
);
1492 ######################################
1493 # Unimplemented and not applicable
1494 ######################################
1499 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1502 * @return string $sql
1504 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1507 * Only useful with fake prepare like in base Database class
1510 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1512 ######################################
1514 ######################################
1517 * Returns information about an index
1518 * If errors are explicitly ignored, returns NULL on failure
1519 * @param $table String: table name
1520 * @param $index String: index name
1521 * @param $fname String: function name for logging and profiling
1522 * @return Object query row in object form
1524 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1525 $table = $this->tableName( $table );
1527 SELECT name as indexname
1528 FROM sysibm.sysindexes si
1529 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1531 $res = $this->query( $sql, $fname );
1535 $row = $this->fetchObject( $res );
1536 if ($row != null) return $row;
1541 * Returns an information object on a table column
1542 * @param $table String: table name
1543 * @param $field String: column name
1544 * @return IBM_DB2Field
1546 public function fieldInfo( $table, $field ) {
1547 return IBM_DB2Field
::fromText($this, $table, $field);
1551 * db2_field_type() wrapper
1552 * @param $res Object: result of executed statement
1553 * @param $index Mixed: number or name of the column
1554 * @return String column type
1556 public function fieldType( $res, $index ) {
1557 if ( $res instanceof ResultWrapper
) {
1558 $res = $res->result
;
1560 return db2_field_type( $res, $index );
1564 * Verifies that an index was created as unique
1565 * @param $table String: table name
1566 * @param $index String: index name
1567 * @param $fname function name for profiling
1570 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1571 $table = $this->tableName( $table );
1573 SELECT si.name as indexname
1574 FROM sysibm.sysindexes si
1575 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1576 AND si.uniquerule IN ('U', 'P')
1578 $res = $this->query( $sql, $fname );
1582 if ($this->fetchObject( $res )) {
1590 * Returns the size of a text field, or -1 for "unlimited"
1591 * @param $table String: table name
1592 * @param $field String: column name
1593 * @return Integer: length or -1 for unlimited
1595 public function textFieldSize( $table, $field ) {
1596 $table = $this->tableName( $table );
1598 SELECT length as size
1599 FROM sysibm.syscolumns sc
1600 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1602 $res = $this->query($sql);
1603 $row = $this->fetchObject($res);
1609 * DELETE where the condition is a join
1610 * @param $delTable String: deleting from this table
1611 * @param $joinTable String: using data from this table
1612 * @param $delVar String: variable in deleteable table
1613 * @param $joinVar String: variable in data table
1614 * @param $conds Array: conditionals for join table
1615 * @param $fname String: function name for profiling
1617 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1619 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1622 $delTable = $this->tableName( $delTable );
1623 $joinTable = $this->tableName( $joinTable );
1624 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1625 if ( $conds != '*' ) {
1626 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1630 $this->query( $sql, $fname );
1634 * Description is left as an exercise for the reader
1635 * @param $b Mixed: data to be encoded
1636 * @return IBM_DB2Blob
1638 public function encodeBlob($b) {
1639 return new IBM_DB2Blob($b);
1643 * Description is left as an exercise for the reader
1644 * @param $b IBM_DB2Blob: data to be decoded
1647 public function decodeBlob($b) {
1648 return $b->getData();
1652 * Convert into a list of string being concatenated
1653 * @param $stringList Array: strings that need to be joined together by the SQL engine
1654 * @return String: joined by the concatenation operator
1656 public function buildConcat( $stringList ) {
1657 // || is equivalent to CONCAT
1658 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1659 return implode( ' || ', $stringList );
1663 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1664 * @param $column String: name of timestamp column
1665 * @return String: SQL code
1667 public function extractUnixEpoch( $column ) {
1669 // see SpecialAncientpages
1672 ######################################
1673 # Prepared statements
1674 ######################################
1677 * Intended to be compatible with the PEAR::DB wrapper functions.
1678 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1680 * ? = scalar value, quoted as necessary
1681 * ! = raw SQL bit (a function for instance)
1682 * & = filename; reads the file and inserts as a blob
1683 * (we don't use this though...)
1684 * @param $sql String: SQL statement with appropriate markers
1685 * @param $func String: Name of the function, for profiling
1686 * @return resource a prepared DB2 SQL statement
1688 public function prepare( $sql, $func = 'DB2::prepare' ) {
1689 $stmt = db2_prepare($this->mConn
, $sql, $this->mStmtOptions
);
1694 * Frees resources associated with a prepared statement
1695 * @return Boolean success or failure
1697 public function freePrepared( $prepared ) {
1698 return db2_free_stmt($prepared);
1702 * Execute a prepared query with the various arguments
1703 * @param $prepared String: the prepared sql
1704 * @param $args Mixed: either an array here, or put scalars as varargs
1705 * @return Resource: results object
1707 public function execute( $prepared, $args = null ) {
1708 if( !is_array( $args ) ) {
1710 $args = func_get_args();
1711 array_shift( $args );
1713 $res = db2_execute($prepared, $args);
1718 * Prepare & execute an SQL statement, quoting and inserting arguments
1719 * in the appropriate places.
1720 * @param $query String
1723 public function safeQuery( $query, $args = null ) {
1724 // copied verbatim from Database.php
1725 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1726 if( !is_array( $args ) ) {
1728 $args = func_get_args();
1729 array_shift( $args );
1731 $retval = $this->execute( $prepared, $args );
1732 $this->freePrepared( $prepared );
1737 * For faking prepared SQL statements on DBs that don't support
1739 * @param $preparedQuery String: a 'preparable' SQL statement
1740 * @param $args Array of arguments to fill it with
1741 * @return String: executable statement
1743 public function fillPrepared( $preparedQuery, $args ) {
1745 $this->preparedArgs
=& $args;
1747 foreach ($args as $i => $arg) {
1748 db2_bind_param($preparedQuery, $i+
1, $args[$i]);
1751 return $preparedQuery;
1755 * Switches module between regular and install modes
1757 public function setMode($mode) {
1758 $old = $this->mMode
;
1759 $this->mMode
= $mode;
1764 * Bitwise negation of a column or value in SQL
1765 * Same as (~field) in C
1766 * @param $field String
1769 function bitNot($field) {
1770 //expecting bit-fields smaller than 4bytes
1771 return 'BITNOT('.$field.')';
1775 * Bitwise AND of two columns or values in SQL
1776 * Same as (fieldLeft & fieldRight) in C
1777 * @param $fieldLeft String
1778 * @param $fieldRight String
1781 function bitAnd($fieldLeft, $fieldRight) {
1782 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1786 * Bitwise OR of two columns or values in SQL
1787 * Same as (fieldLeft | fieldRight) in C
1788 * @param $fieldLeft String
1789 * @param $fieldRight String
1792 function bitOr($fieldLeft, $fieldRight) {
1793 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';