Bug 23733 - Add IDs to messages used on CSS/JS pages
[mediawiki.git] / includes / db / DatabaseIbm_db2.php
blobe53c0283e3ca531229e0d6da3a0a60cf9e29892d
1 <?php
2 /**
3 * This script is the IBM DB2 database abstraction layer
5 * See maintenance/ibm_db2/README for development notes and other specific information
6 * @ingroup Database
7 * @file
8 * @author leo.petr+mediawiki@gmail.com
9 */
11 /**
12 * This represents a column in a DB2 database
13 * @ingroup Database
15 class IBM_DB2Field {
16 private $name = '';
17 private $tablename = '';
18 private $type = '';
19 private $nullable = false;
20 private $max_length = 0;
22 /**
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) {
30 global $wgDBmwschema;
32 $q = <<<SQL
33 SELECT
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;
38 SQL;
39 $res = $db->query(sprintf($q,
40 $db->addQuotes($wgDBmwschema),
41 $db->addQuotes($table),
42 $db->addQuotes($field)));
43 $row = $db->fetchObject($res);
44 if (!$row)
45 return null;
46 $n = new IBM_DB2Field;
47 $n->type = $row->typname;
48 $n->nullable = ($row->attnotnull == 'N');
49 $n->name = $field;
50 $n->tablename = $table;
51 $n->max_length = $row->attlen;
52 return $n;
54 /**
55 * Get column name
56 * @return string column name
58 function name() { return $this->name; }
59 /**
60 * Get table name
61 * @return string table name
63 function tableName() { return $this->tablename; }
64 /**
65 * Get column type
66 * @return string column type
68 function type() { return $this->type; }
69 /**
70 * Can column be null?
71 * @return bool true or false
73 function nullable() { return $this->nullable; }
74 /**
75 * How much can you fit in the column per row?
76 * @return int length
78 function maxLength() { return $this->max_length; }
81 /**
82 * Wrapper around binary large objects
83 * @ingroup Database
85 class IBM_DB2Blob {
86 private $mData;
88 public function __construct($data) {
89 $this->mData = $data;
92 public function getData() {
93 return $this->mData;
96 public function __toString()
98 return $this->mData;
103 * Primary database interface
104 * @ingroup Database
106 class DatabaseIbm_db2 extends DatabaseBase {
108 * Inherited members
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;
117 protected $mFlags;
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)
167 * failFunction
168 * setOutputPage
169 * bufferResults
170 * ignoreErrors
171 * trxLevel
172 * errorCount
173 * getLBInfo
174 * setLBInfo
175 * lastQuery
176 * isOpen
177 * setFlag
178 * clearFlag
179 * getFlag
180 * getProperty
181 * getDBname
182 * getServer
183 * tableNameCallback
184 * tablePrefix
186 * Administrative: (8)
187 * debug
188 * installErrorHandler
189 * restoreErrorHandler
190 * connectionErrorHandler
191 * reportConnectionError
192 * sourceFile
193 * sourceStream
194 * replaceVars
196 * Database: (5)
197 * query
198 * set
199 * selectField
200 * generalizeSQL
201 * update
202 * strreplace
203 * deadlockLoop
205 * Prepared Statement: 6
206 * prepare
207 * freePrepared
208 * execute
209 * safeQuery
210 * fillPrepared
211 * fillPreparedArg
213 * Slave/Master: (4)
214 * masterPosWait
215 * getSlavePos
216 * getMasterPos
217 * getLag
219 * Generation: (9)
220 * tableNames
221 * tableNamesN
222 * tableNamesWithUseIndexOrJOIN
223 * escapeLike
224 * delete
225 * insertSelect
226 * timestampOrNull
227 * resultObject
228 * aggregateValue
229 * selectSQLText
230 * selectRow
231 * makeUpdateOptions
233 * Reflection: (1)
234 * indexExists
238 * These have been implemented
240 * Administrative: 7 / 7
241 * constructor [Done]
242 * open [Done]
243 * openCataloged [Done]
244 * close [Done]
245 * newFromParams [Done]
246 * openUncataloged [Done]
247 * setup_database [Done]
249 * Getter/Setter: 13 / 13
250 * cascadingDeletes [Done]
251 * cleanupTriggers [Done]
252 * strictIPs [Done]
253 * realTimestamps [Done]
254 * impliciGroupby [Done]
255 * implicitOrderby [Done]
256 * searchableIPs [Done]
257 * functionalIndexes [Done]
258 * getWikiID [Done]
259 * isOpen [Done]
260 * getServerVersion [Done]
261 * getSoftwareLink [Done]
262 * getSearchEngine [Done]
264 * Database driver wrapper: 23 / 23
265 * lastError [Done]
266 * lastErrno [Done]
267 * doQuery [Done]
268 * tableExists [Done]
269 * fetchObject [Done]
270 * fetchRow [Done]
271 * freeResult [Done]
272 * numRows [Done]
273 * numFields [Done]
274 * fieldName [Done]
275 * insertId [Done]
276 * dataSeek [Done]
277 * affectedRows [Done]
278 * selectDB [Done]
279 * strencode [Done]
280 * conditional [Done]
281 * wasDeadlock [Done]
282 * ping [Done]
283 * getStatus [Done]
284 * setTimeout [Done]
285 * lock [Done]
286 * unlock [Done]
287 * insert [Done]
288 * select [Done]
290 * Slave/master: 2 / 2
291 * setFakeSlaveLag [Done]
292 * setFakeMaster [Done]
294 * Reflection: 6 / 6
295 * fieldExists [Done]
296 * indexInfo [Done]
297 * fieldInfo [Done]
298 * fieldType [Done]
299 * indexUnique [Done]
300 * textFieldSize [Done]
302 * Generation: 16 / 16
303 * tableName [Done]
304 * addQuotes [Done]
305 * makeList [Done]
306 * makeSelectOptions [Done]
307 * estimateRowCount [Done]
308 * nextSequenceValue [Done]
309 * useIndexClause [Done]
310 * replace [Done]
311 * deleteJoin [Done]
312 * lowPriorityOption [Done]
313 * limitResult [Done]
314 * limitResultForUpdate [Done]
315 * timestamp [Done]
316 * encodeBlob [Done]
317 * decodeBlob [Done]
318 * buildConcat [Done]
321 ######################################
322 # Getters and Setters
323 ######################################
326 * Returns true if this database supports (and uses) cascading deletes
328 function cascadingDeletes() {
329 return true;
333 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
335 function cleanupTriggers() {
336 return true;
340 * Returns true if this database is strict about what can be put into an IP field.
341 * Specifically, it uses a NULL value instead of an empty string.
343 function strictIPs() {
344 return true;
348 * Returns true if this database uses timestamps rather than integers
350 function realTimestamps() {
351 return true;
355 * Returns true if this database does an implicit sort when doing GROUP BY
357 function implicitGroupby() {
358 return false;
362 * Returns true if this database does an implicit order by when the column has an index
363 * For example: SELECT page_title FROM page LIMIT 1
365 function implicitOrderby() {
366 return false;
370 * Returns true if this database can do a native search on IP columns
371 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
373 function searchableIPs() {
374 return true;
378 * Returns true if this database can use functional indexes
380 function functionalIndexes() {
381 return true;
385 * Returns a unique string representing the wiki on the server
387 function getWikiID() {
388 if( $this->mSchema ) {
389 return "{$this->mDBname}-{$this->mSchema}";
390 } else {
391 return $this->mDBname;
395 function getType() {
396 return 'ibm_db2';
399 ######################################
400 # Setup
401 ######################################
406 * @param $server String: hostname of database server
407 * @param $user String: username
408 * @param $password String: password
409 * @param $dbName String: database name on the server
410 * @param $failFunction Callback (optional)
411 * @param $flags Integer: database behaviour flags (optional, unused)
412 * @param $schema String
414 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
415 $dbName = false, $failFunction = false, $flags = 0,
416 $schema = self::USE_GLOBAL )
419 global $wgOut, $wgDBmwschema;
420 # Can't get a reference if it hasn't been set yet
421 if ( !isset( $wgOut ) ) {
422 $wgOut = null;
424 $this->mOut =& $wgOut;
425 $this->mFailFunction = $failFunction;
426 $this->mFlags = DBO_TRX | $flags;
428 if ( $schema == self::USE_GLOBAL ) {
429 $this->mSchema = $wgDBmwschema;
431 else {
432 $this->mSchema = $schema;
435 // configure the connection and statement objects
436 $this->setDB2Option('db2_attr_case', 'DB2_CASE_LOWER', self::CONN_OPTION | self::STMT_OPTION);
437 $this->setDB2Option('deferred_prepare', 'DB2_DEFERRED_PREPARE_ON', self::STMT_OPTION);
438 $this->setDB2Option('rowcount', 'DB2_ROWCOUNT_PREFETCH_ON', self::STMT_OPTION);
440 $this->open( $server, $user, $password, $dbName);
444 * Enables options only if the ibm_db2 extension version supports them
445 * @param $name String: name of the option in the options array
446 * @param $const String: name of the constant holding the right option value
447 * @param $type Integer: whether this is a Connection or Statement otion
449 private function setDB2Option($name, $const, $type) {
450 if (defined($const)) {
451 if ($type & self::CONN_OPTION) $this->mConnOptions[$name] = constant($const);
452 if ($type & self::STMT_OPTION) $this->mStmtOptions[$name] = constant($const);
454 else {
455 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
460 * Outputs debug information in the appropriate place
461 * @param $string String: the relevant debug message
463 private function installPrint($string) {
464 wfDebug("$string");
465 if ($this->mMode == self::INSTALL_MODE) {
466 print "<li>$string</li>";
467 flush();
472 * Opens a database connection and returns it
473 * Closes any existing connection
474 * @return a fresh connection
475 * @param $server String: hostname
476 * @param $user String
477 * @param $password String
478 * @param $dbName String: database name
480 public function open( $server, $user, $password, $dbName )
482 // Load the port number
483 global $wgDBport_db2, $wgDBcataloged;
484 wfProfileIn( __METHOD__ );
486 // Load IBM DB2 driver if missing
487 if (!@extension_loaded('ibm_db2')) {
488 @dl('ibm_db2.so');
490 // Test for IBM DB2 support, to avoid suppressed fatal error
491 if ( !function_exists( 'db2_connect' ) ) {
492 $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
493 $this->installPrint($error);
494 $this->reportConnectionError($error);
497 if (!strlen($user)) { // Copied from Postgres
498 return null;
501 // Close existing connection
502 $this->close();
503 // Cache conn info
504 $this->mServer = $server;
505 $this->mPort = $port = $wgDBport_db2;
506 $this->mUser = $user;
507 $this->mPassword = $password;
508 $this->mDBname = $dbName;
509 $this->mCataloged = $cataloged = $wgDBcataloged;
511 if ( $cataloged == self::CATALOGED ) {
512 $this->openCataloged($dbName, $user, $password);
514 elseif ( $cataloged == self::UNCATALOGED ) {
515 $this->openUncataloged($dbName, $user, $password, $server, $port);
517 // Apply connection config
518 db2_set_option($this->mConn, $this->mConnOptions, 1);
519 // Not all MediaWiki code is transactional
520 // Rather, turn autocommit off in the begin function and turn on after a commit
521 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
523 if ( $this->mConn == false ) {
524 $this->installPrint( "DB connection error\n" );
525 $this->installPrint( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
526 $this->installPrint( $this->lastError()."\n" );
527 return null;
530 $this->mOpened = true;
531 $this->applySchema();
533 wfProfileOut( __METHOD__ );
534 return $this->mConn;
538 * Opens a cataloged database connection, sets mConn
540 protected function openCataloged( $dbName, $user, $password )
542 @$this->mConn = db2_connect($dbName, $user, $password);
546 * Opens an uncataloged database connection, sets mConn
548 protected function openUncataloged( $dbName, $user, $password, $server, $port )
550 $str = "DRIVER={IBM DB2 ODBC DRIVER};";
551 $str .= "DATABASE=$dbName;";
552 $str .= "HOSTNAME=$server;";
553 if ($port) $str .= "PORT=$port;";
554 $str .= "PROTOCOL=TCPIP;";
555 $str .= "UID=$user;";
556 $str .= "PWD=$password;";
558 @$this->mConn = db2_connect($str, $user, $password);
562 * Closes a database connection, if it is open
563 * Returns success, true if already closed
565 public function close() {
566 $this->mOpened = false;
567 if ( $this->mConn ) {
568 if ($this->trxLevel() > 0) {
569 $this->commit();
571 return db2_close( $this->mConn );
573 else {
574 return true;
579 * Returns a fresh instance of this class
581 * @param $server String: hostname of database server
582 * @param $user String: username
583 * @param $password String
584 * @param $dbName String: database name on the server
585 * @param $failFunction Callback (optional)
586 * @param $flags Integer: database behaviour flags (optional, unused)
587 * @return DatabaseIbm_db2 object
589 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
591 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
595 * Retrieves the most current database error
596 * Forces a database rollback
598 public function lastError() {
599 $connerr = db2_conn_errormsg();
600 if ($connerr) {
601 //$this->rollback();
602 return $connerr;
604 $stmterr = db2_stmt_errormsg();
605 if ($stmterr) {
606 //$this->rollback();
607 return $stmterr;
610 return false;
614 * Get the last error number
615 * Return 0 if no error
616 * @return integer
618 public function lastErrno() {
619 $connerr = db2_conn_error();
620 if ($connerr) return $connerr;
621 $stmterr = db2_stmt_error();
622 if ($stmterr) return $stmterr;
623 return 0;
627 * Is a database connection open?
628 * @return
630 public function isOpen() { return $this->mOpened; }
633 * The DBMS-dependent part of query()
634 * @param $sql String: SQL query.
635 * @return object Result object to feed to fetchObject, fetchRow, ...; or false on failure
636 * @access private
638 /*private*/
639 public function doQuery( $sql ) {
640 //print "<li><pre>$sql</pre></li>";
641 // Switch into the correct namespace
642 $this->applySchema();
644 $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
645 if( !$ret ) {
646 print "<br><pre>";
647 print $sql;
648 print "</pre><br>";
649 $error = db2_stmt_errormsg();
650 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( $error ) );
652 $this->mLastResult = $ret;
653 $this->mAffectedRows = null; // Not calculated until asked for
654 return $ret;
658 * @return string Version information from the database
660 public function getServerVersion() {
661 $info = db2_server_info( $this->mConn );
662 return $info->DBMS_VER;
666 * Queries whether a given table exists
667 * @return boolean
669 public function tableExists( $table ) {
670 $schema = $this->mSchema;
671 $sql = <<< EOF
672 SELECT COUNT(*) FROM SYSIBM.SYSTABLES ST
673 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
674 EOF;
675 $res = $this->query( $sql );
676 if (!$res) return false;
678 // If the table exists, there should be one of it
679 @$row = $this->fetchRow($res);
680 $count = $row[0];
681 if ($count == '1' or $count == 1) {
682 return true;
685 return false;
689 * Fetch the next row from the given result object, in object form.
690 * Fields can be retrieved with $row->fieldname, with fields acting like
691 * member variables.
693 * @param $res SQL result object as returned from Database::query(), etc.
694 * @return DB2 row object
695 * @throws DBUnexpectedError Thrown if the database returns an error
697 public function fetchObject( $res ) {
698 if ( $res instanceof ResultWrapper ) {
699 $res = $res->result;
701 @$row = db2_fetch_object( $res );
702 if( $this->lastErrno() ) {
703 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
705 return $row;
709 * Fetch the next row from the given result object, in associative array
710 * form. Fields are retrieved with $row['fieldname'].
712 * @param $res SQL result object as returned from Database::query(), etc.
713 * @return DB2 row object
714 * @throws DBUnexpectedError Thrown if the database returns an error
716 public function fetchRow( $res ) {
717 if ( $res instanceof ResultWrapper ) {
718 $res = $res->result;
720 @$row = db2_fetch_array( $res );
721 if ( $this->lastErrno() ) {
722 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
724 return $row;
728 * Override if introduced to base Database class
730 public function initial_setup() {
731 // do nothing
735 * Create tables, stored procedures, and so on
737 public function setup_database() {
738 // Timeout was being changed earlier due to mysterious crashes
739 // Changing it now may cause more problems than not changing it
740 //set_time_limit(240);
741 try {
742 // TODO: switch to root login if available
744 // Switch into the correct namespace
745 $this->applySchema();
746 $this->begin();
748 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
749 if ($res !== true) {
750 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
751 } else {
752 print " done</li>";
754 $res = null;
756 // TODO: populate interwiki links
758 if ($this->lastError()) {
759 print "<li>Errors encountered during table creation -- rolled back</li>\n";
760 print "<li>Please install again</li>\n";
761 $this->rollback();
763 else {
764 $this->commit();
767 catch (MWException $mwe)
769 print "<br><pre>$mwe</pre><br>";
774 * Escapes strings
775 * Doesn't escape numbers
776 * @param $s String: string to escape
777 * @return escaped string
779 public function addQuotes( $s ) {
780 //$this->installPrint("DB2::addQuotes($s)\n");
781 if ( is_null( $s ) ) {
782 return "NULL";
783 } else if ($s instanceof Blob) {
784 return "'".$s->fetch($s)."'";
785 } else if ($s instanceof IBM_DB2Blob) {
786 return "'".$this->decodeBlob($s)."'";
788 $s = $this->strencode($s);
789 if ( is_numeric($s) ) {
790 return $s;
792 else {
793 return "'$s'";
798 * Verifies that a DB2 column/field type is numeric
799 * @return bool true if numeric
800 * @param $type String: DB2 column type
802 public function is_numeric_type( $type ) {
803 switch (strtoupper($type)) {
804 case 'SMALLINT':
805 case 'INTEGER':
806 case 'INT':
807 case 'BIGINT':
808 case 'DECIMAL':
809 case 'REAL':
810 case 'DOUBLE':
811 case 'DECFLOAT':
812 return true;
814 return false;
818 * Alias for addQuotes()
819 * @param $s String: string to escape
820 * @return escaped string
822 public function strencode( $s ) {
823 // Bloody useless function
824 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
825 // But also necessary
826 $s = db2_escape_string($s);
827 // Wide characters are evil -- some of them look like '
828 $s = utf8_encode($s);
829 // Fix its stupidity
830 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
831 $to = array("\\", "''", "\n", "\t", '"', "\r");
832 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
833 return $s;
837 * Switch into the database schema
839 protected function applySchema() {
840 if ( !($this->mSchemaSet) ) {
841 $this->mSchemaSet = true;
842 $this->begin();
843 $this->doQuery("SET SCHEMA = $this->mSchema");
844 $this->commit();
849 * Start a transaction (mandatory)
851 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
852 // turn off auto-commit
853 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_OFF);
854 $this->mTrxLevel = 1;
858 * End a transaction
859 * Must have a preceding begin()
861 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
862 db2_commit($this->mConn);
863 // turn auto-commit back on
864 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
865 $this->mTrxLevel = 0;
869 * Cancel a transaction
871 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
872 db2_rollback($this->mConn);
873 // turn auto-commit back on
874 // not sure if this is appropriate
875 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
876 $this->mTrxLevel = 0;
880 * Makes an encoded list of strings from an array
881 * $mode:
882 * LIST_COMMA - comma separated, no field names
883 * LIST_AND - ANDed WHERE clause (without the WHERE)
884 * LIST_OR - ORed WHERE clause (without the WHERE)
885 * LIST_SET - comma separated with field names, like a SET clause
886 * LIST_NAMES - comma separated field names
888 public function makeList( $a, $mode = LIST_COMMA ) {
889 if ( !is_array( $a ) ) {
890 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
893 $first = true;
894 $list = '';
895 foreach ( $a as $field => $value ) {
896 if ( !$first ) {
897 if ( $mode == LIST_AND ) {
898 $list .= ' AND ';
899 } elseif($mode == LIST_OR) {
900 $list .= ' OR ';
901 } else {
902 $list .= ',';
904 } else {
905 $first = false;
907 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
908 $list .= "($value)";
909 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
910 $list .= "$value";
911 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
912 if( count( $value ) == 0 ) {
913 throw new MWException( __METHOD__.': empty input' );
914 } elseif( count( $value ) == 1 ) {
915 // Special-case single values, as IN isn't terribly efficient
916 // Don't necessarily assume the single key is 0; we don't
917 // enforce linear numeric ordering on other arrays here.
918 $value = array_values( $value );
919 $list .= $field." = ".$this->addQuotes( $value[0] );
920 } else {
921 $list .= $field." IN (".$this->makeList($value).") ";
923 } elseif( is_null($value) ) {
924 if ( $mode == LIST_AND || $mode == LIST_OR ) {
925 $list .= "$field IS ";
926 } elseif ( $mode == LIST_SET ) {
927 $list .= "$field = ";
929 $list .= 'NULL';
930 } else {
931 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
932 $list .= "$field = ";
934 if ( $mode == LIST_NAMES ) {
935 $list .= $value;
937 // Leo: Can't insert quoted numbers into numeric columns
938 // (?) Might cause other problems. May have to check column type before insertion.
939 else if ( is_numeric($value) ) {
940 $list .= $value;
942 else {
943 $list .= $this->addQuotes( $value );
947 return $list;
951 * Construct a LIMIT query with optional offset
952 * This is used for query pages
953 * @param $sql string SQL query we will append the limit too
954 * @param $limit integer the SQL limit
955 * @param $offset integer the SQL offset (default false)
957 public function limitResult($sql, $limit, $offset=false) {
958 if( !is_numeric($limit) ) {
959 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
961 if( $offset ) {
962 $this->installPrint("Offset parameter not supported in limitResult()\n");
964 // TODO implement proper offset handling
965 // idea: get all the rows between 0 and offset, advance cursor to offset
966 return "$sql FETCH FIRST $limit ROWS ONLY ";
970 * Handle reserved keyword replacement in table names
971 * @return
972 * @param $name Object
974 public function tableName( $name ) {
975 # Replace reserved words with better ones
976 // switch( $name ) {
977 // case 'user':
978 // return 'mwuser';
979 // case 'text':
980 // return 'pagecontent';
981 // default:
982 // return $name;
983 // }
984 // we want maximum compatibility with MySQL schema
985 return $name;
989 * Generates a timestamp in an insertable format
990 * @return string timestamp value
991 * @param $ts timestamp
993 public function timestamp( $ts=0 ) {
994 // TS_MW cannot be easily distinguished from an integer
995 return wfTimestamp(TS_DB2,$ts);
999 * Return the next in a sequence, save the value for retrieval via insertId()
1000 * @param $seqName String: name of a defined sequence in the database
1001 * @return next value in that sequence
1003 public function nextSequenceValue( $seqName ) {
1004 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1005 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1007 $safeseq = preg_replace( "/'/", "''", $seqName );
1008 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1009 $row = $this->fetchRow( $res );
1010 $this->mInsertId = $row[0];
1011 $this->freeResult( $res );
1012 return $this->mInsertId;
1014 return null;
1018 * This must be called after nextSequenceVal
1019 * @return Last sequence value used as a primary key
1021 public function insertId() {
1022 return $this->mInsertId;
1026 * Updates the mInsertId property with the value of the last insert into a generated column
1027 * @param $table String: sanitized table name
1028 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
1029 * @param $stmt Resource: prepared statement resource
1030 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1032 private function calcInsertId($table, $primaryKey, $stmt) {
1033 if ($primaryKey) {
1034 $id_row = $this->fetchRow($stmt);
1035 $this->mInsertId = $id_row[0];
1040 * INSERT wrapper, inserts an array into a table
1042 * $args may be a single associative array, or an array of these with numeric keys,
1043 * for multi-row insert
1045 * @param $table String: Name of the table to insert to.
1046 * @param $args Array: Items to insert into the table.
1047 * @param $fname String: Name of the function, for profiling
1048 * @param $options String or Array. Valid options: IGNORE
1050 * @return bool Success of insert operation. IGNORE always returns true.
1052 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1053 if ( !count( $args ) ) {
1054 return true;
1056 // get database-specific table name (not used)
1057 $table = $this->tableName( $table );
1058 // format options as an array
1059 if ( !is_array( $options ) ) $options = array( $options );
1060 // format args as an array of arrays
1061 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1062 $args = array($args);
1064 // prevent insertion of NULL into primary key columns
1065 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1066 // if there's only one primary key
1067 // we'll be able to read its value after insertion
1068 $primaryKey = false;
1069 if (count($primaryKeys) == 1) {
1070 $primaryKey = $primaryKeys[0];
1073 // get column names
1074 $keys = array_keys( $args[0] );
1075 $key_count = count($keys);
1077 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1078 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
1080 // assume success
1081 $res = true;
1082 // If we are not in a transaction, we need to be for savepoint trickery
1083 $didbegin = 0;
1084 if (! $this->mTrxLevel) {
1085 $this->begin();
1086 $didbegin = 1;
1089 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1090 switch($key_count) {
1091 //case 0 impossible
1092 case 1:
1093 $sql .= '(?)';
1094 break;
1095 default:
1096 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1098 // add logic to read back the new primary key value
1099 if ($primaryKey) {
1100 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1102 $stmt = $this->prepare($sql);
1104 // start a transaction/enter transaction mode
1105 $this->begin();
1107 if ( !$ignore ) {
1108 $first = true;
1109 foreach ( $args as $row ) {
1110 // insert each row into the database
1111 $res = $res & $this->execute($stmt, $row);
1112 // get the last inserted value into a generated column
1113 $this->calcInsertId($table, $primaryKey, $stmt);
1116 else {
1117 $olde = error_reporting( 0 );
1118 // For future use, we may want to track the number of actual inserts
1119 // Right now, insert (all writes) simply return true/false
1120 $numrowsinserted = 0;
1122 // always return true
1123 $res = true;
1125 foreach ( $args as $row ) {
1126 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1127 db2_exec($this->mConn, $overhead, $this->mStmtOptions);
1129 $res2 = $this->execute($stmt, $row);
1130 // get the last inserted value into a generated column
1131 $this->calcInsertId($table, $primaryKey, $stmt);
1133 $errNum = $this->lastErrno();
1134 if ($errNum) {
1135 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions );
1137 else {
1138 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions );
1139 $numrowsinserted++;
1143 $olde = error_reporting( $olde );
1144 // Set the affected row count for the whole operation
1145 $this->mAffectedRows = $numrowsinserted;
1147 // commit either way
1148 $this->commit();
1150 return $res;
1154 * Given a table name and a hash of columns with values
1155 * Removes primary key columns from the hash where the value is NULL
1157 * @param $table String: name of the table
1158 * @param $args Array of hashes of column names with values
1159 * @return Array: tuple containing filtered array of columns, array of primary keys
1161 private function removeNullPrimaryKeys($table, $args) {
1162 $schema = $this->mSchema;
1163 // find out the primary keys
1164 $keyres = db2_primary_keys($this->mConn, null, strtoupper($schema), strtoupper($table));
1165 $keys = array();
1166 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1167 $keys[] = strtolower($row->column_name);
1169 // remove primary keys
1170 foreach ($args as $ai => $row) {
1171 foreach ($keys as $ki => $key) {
1172 if ($row[$key] == null) {
1173 unset($row[$key]);
1176 $args[$ai] = $row;
1178 // return modified hash
1179 return array($args, $keys);
1183 * UPDATE wrapper, takes a condition array and a SET array
1185 * @param $table String: The table to UPDATE
1186 * @param $values An array of values to SET
1187 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1188 * @param $fname String: The Class::Function calling this function
1189 * (for the log)
1190 * @param $options An array of UPDATE options, can be one or
1191 * more of IGNORE, LOW_PRIORITY
1192 * @return Boolean
1194 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1195 $table = $this->tableName( $table );
1196 $opts = $this->makeUpdateOptions( $options );
1197 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1198 if ( $conds != '*' ) {
1199 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1201 return $this->query( $sql, $fname );
1205 * DELETE query wrapper
1207 * Use $conds == "*" to delete all rows
1209 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1210 if ( !$conds ) {
1211 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1213 $table = $this->tableName( $table );
1214 $sql = "DELETE FROM $table";
1215 if ( $conds != '*' ) {
1216 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1218 return $this->query( $sql, $fname );
1222 * Returns the number of rows affected by the last query or 0
1223 * @return Integer: the number of rows affected by the last query
1225 public function affectedRows() {
1226 if ( !is_null( $this->mAffectedRows ) ) {
1227 // Forced result for simulated queries
1228 return $this->mAffectedRows;
1230 if( empty( $this->mLastResult ) )
1231 return 0;
1232 return db2_num_rows( $this->mLastResult );
1236 * Simulates REPLACE with a DELETE followed by INSERT
1237 * @param $table Object
1238 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1239 * @param $rows Array: rows to insert
1240 * @param $fname String: name of the function for profiling
1241 * @return nothing
1243 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1244 $table = $this->tableName( $table );
1246 if (count($rows)==0) {
1247 return;
1250 # Single row case
1251 if ( !is_array( reset( $rows ) ) ) {
1252 $rows = array( $rows );
1255 foreach( $rows as $row ) {
1256 # Delete rows which collide
1257 if ( $uniqueIndexes ) {
1258 $sql = "DELETE FROM $table WHERE ";
1259 $first = true;
1260 foreach ( $uniqueIndexes as $index ) {
1261 if ( $first ) {
1262 $first = false;
1263 $sql .= "(";
1264 } else {
1265 $sql .= ') OR (';
1267 if ( is_array( $index ) ) {
1268 $first2 = true;
1269 foreach ( $index as $col ) {
1270 if ( $first2 ) {
1271 $first2 = false;
1272 } else {
1273 $sql .= ' AND ';
1275 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1277 } else {
1278 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1281 $sql .= ')';
1282 $this->query( $sql, $fname );
1285 # Now insert the row
1286 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
1287 $this->makeList( $row, LIST_COMMA ) . ')';
1288 $this->query( $sql, $fname );
1293 * Returns the number of rows in the result set
1294 * Has to be called right after the corresponding select query
1295 * @param $res Object result set
1296 * @return Integer: number of rows
1298 public function numRows( $res ) {
1299 if ( $res instanceof ResultWrapper ) {
1300 $res = $res->result;
1302 if ( $this->mNumRows ) {
1303 return $this->mNumRows;
1305 else {
1306 return 0;
1311 * Moves the row pointer of the result set
1312 * @param $res Object: result set
1313 * @param $row Integer: row number
1314 * @return success or failure
1316 public function dataSeek( $res, $row ) {
1317 if ( $res instanceof ResultWrapper ) {
1318 $res = $res->result;
1320 return db2_fetch_row( $res, $row );
1324 # Fix notices in Block.php
1328 * Frees memory associated with a statement resource
1329 * @param $res Object: statement resource to free
1330 * @return Boolean success or failure
1332 public function freeResult( $res ) {
1333 if ( $res instanceof ResultWrapper ) {
1334 $res = $res->result;
1336 if ( !@db2_free_result( $res ) ) {
1337 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1342 * Returns the number of columns in a resource
1343 * @param $res Object: statement resource
1344 * @return Number of fields/columns in resource
1346 public function numFields( $res ) {
1347 if ( $res instanceof ResultWrapper ) {
1348 $res = $res->result;
1350 return db2_num_fields( $res );
1354 * Returns the nth column name
1355 * @param $res Object: statement resource
1356 * @param $n Integer: Index of field or column
1357 * @return String name of nth column
1359 public function fieldName( $res, $n ) {
1360 if ( $res instanceof ResultWrapper ) {
1361 $res = $res->result;
1363 return db2_field_name( $res, $n );
1367 * SELECT wrapper
1369 * @param $table Array or string, table name(s) (prefix auto-added)
1370 * @param $vars Array or string, field name(s) to be retrieved
1371 * @param $conds Array or string, condition(s) for WHERE
1372 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1373 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1374 * see Database::makeSelectOptions code for list of supported stuff
1375 * @param $join_conds Associative array of table join conditions (optional)
1376 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1377 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1379 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1381 $res = parent::select( $table, $vars, $conds, $fname, $options, $join_conds );
1383 // We must adjust for offset
1384 if ( isset( $options['LIMIT'] ) ) {
1385 if ( isset ($options['OFFSET'] ) ) {
1386 $limit = $options['LIMIT'];
1387 $offset = $options['OFFSET'];
1392 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1393 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1394 // Yay!
1396 // we want the count
1397 $vars2 = array('count(*) as num_rows');
1398 // respecting just the limit option
1399 $options2 = array();
1400 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1401 // but don't try to emulate for GROUP BY
1402 if ( isset( $options['GROUP BY'] ) ) return $res;
1404 $res2 = parent::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1405 $obj = $this->fetchObject($res2);
1406 $this->mNumRows = $obj->num_rows;
1409 return $res;
1413 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1414 * Has limited support for per-column options (colnum => 'DISTINCT')
1416 * @private
1418 * @param $options Associative array of options to be turned into
1419 * an SQL query, valid keys are listed in the function.
1420 * @return Array
1422 function makeSelectOptions( $options ) {
1423 $preLimitTail = $postLimitTail = '';
1424 $startOpts = '';
1426 $noKeyOptions = array();
1427 foreach ( $options as $key => $option ) {
1428 if ( is_numeric( $key ) ) {
1429 $noKeyOptions[$option] = true;
1433 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1434 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1435 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1437 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1439 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1443 * Returns link to IBM DB2 free download
1444 * @return string wikitext of a link to the server software's web site
1446 public function getSoftwareLink() {
1447 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1451 * Get search engine class. All subclasses of this
1452 * need to implement this if they wish to use searching.
1454 * @return String
1456 public function getSearchEngine() {
1457 return "SearchIBM_DB2";
1461 * Did the last database access fail because of deadlock?
1462 * @return Boolean
1464 public function wasDeadlock() {
1465 // get SQLSTATE
1466 $err = $this->lastErrno();
1467 switch($err) {
1468 case '40001': // sql0911n, Deadlock or timeout, rollback
1469 case '57011': // sql0904n, Resource unavailable, no rollback
1470 case '57033': // sql0913n, Deadlock or timeout, no rollback
1471 $this->installPrint("In a deadlock because of SQLSTATE $err");
1472 return true;
1474 return false;
1478 * Ping the server and try to reconnect if it there is no connection
1479 * The connection may be closed and reopened while this happens
1480 * @return Boolean: whether the connection exists
1482 public function ping() {
1483 // db2_ping() doesn't exist
1484 // Emulate
1485 $this->close();
1486 if ($this->mCataloged == null) {
1487 return false;
1489 else if ($this->mCataloged) {
1490 $this->mConn = $this->openCataloged($this->mDBName, $this->mUser, $this->mPassword);
1492 else if (!$this->mCataloged) {
1493 $this->mConn = $this->openUncataloged($this->mDBName, $this->mUser, $this->mPassword, $this->mServer, $this->mPort);
1495 return false;
1497 ######################################
1498 # Unimplemented and not applicable
1499 ######################################
1501 * Not implemented
1502 * @return string ''
1503 * @deprecated
1505 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1507 * Not implemented
1508 * TODO
1509 * @return bool true
1512 * Not implemented
1513 * @deprecated
1515 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1517 * Not implemented
1518 * @deprecated
1520 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1522 * Not implemented
1523 * @return string $sql
1524 * @deprecated
1526 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1529 * Only useful with fake prepare like in base Database class
1530 * @return string
1532 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1534 ######################################
1535 # Reflection
1536 ######################################
1539 * Query whether a given column exists in the mediawiki schema
1540 * @param $table String: name of the table
1541 * @param $field String: name of the column
1542 * @param $fname String: function name for logging and profiling
1544 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1545 $table = $this->tableName( $table );
1546 $schema = $this->mSchema;
1547 $etable = preg_replace("/'/", "''", $table);
1548 $eschema = preg_replace("/'/", "''", $schema);
1549 $ecol = preg_replace("/'/", "''", $field);
1550 $sql = <<<SQL
1551 SELECT 1 as fieldexists
1552 FROM sysibm.syscolumns sc
1553 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1554 SQL;
1555 $res = $this->query( $sql, $fname );
1556 $count = $res ? $this->numRows($res) : 0;
1557 if ($res)
1558 $this->freeResult( $res );
1559 return $count;
1563 * Returns information about an index
1564 * If errors are explicitly ignored, returns NULL on failure
1565 * @param $table String: table name
1566 * @param $index String: index name
1567 * @param $fname String: function name for logging and profiling
1568 * @return Object query row in object form
1570 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1571 $table = $this->tableName( $table );
1572 $sql = <<<SQL
1573 SELECT name as indexname
1574 FROM sysibm.sysindexes si
1575 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1576 SQL;
1577 $res = $this->query( $sql, $fname );
1578 if ( !$res ) {
1579 return null;
1581 $row = $this->fetchObject( $res );
1582 if ($row != null) return $row;
1583 else return false;
1587 * Returns an information object on a table column
1588 * @param $table String: table name
1589 * @param $field String: column name
1590 * @return IBM_DB2Field
1592 public function fieldInfo( $table, $field ) {
1593 return IBM_DB2Field::fromText($this, $table, $field);
1597 * db2_field_type() wrapper
1598 * @param $res Object: result of executed statement
1599 * @param $index Mixed: number or name of the column
1600 * @return String column type
1602 public function fieldType( $res, $index ) {
1603 if ( $res instanceof ResultWrapper ) {
1604 $res = $res->result;
1606 return db2_field_type( $res, $index );
1610 * Verifies that an index was created as unique
1611 * @param $table String: table name
1612 * @param $index String: index name
1613 * @param $fname function name for profiling
1614 * @return Bool
1616 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1617 $table = $this->tableName( $table );
1618 $sql = <<<SQL
1619 SELECT si.name as indexname
1620 FROM sysibm.sysindexes si
1621 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1622 AND si.uniquerule IN ('U', 'P')
1623 SQL;
1624 $res = $this->query( $sql, $fname );
1625 if ( !$res ) {
1626 return null;
1628 if ($this->fetchObject( $res )) {
1629 return true;
1631 return false;
1636 * Returns the size of a text field, or -1 for "unlimited"
1637 * @param $table String: table name
1638 * @param $field String: column name
1639 * @return Integer: length or -1 for unlimited
1641 public function textFieldSize( $table, $field ) {
1642 $table = $this->tableName( $table );
1643 $sql = <<<SQL
1644 SELECT length as size
1645 FROM sysibm.syscolumns sc
1646 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1647 SQL;
1648 $res = $this->query($sql);
1649 $row = $this->fetchObject($res);
1650 $size = $row->size;
1651 $this->freeResult( $res );
1652 return $size;
1656 * DELETE where the condition is a join
1657 * @param $delTable String: deleting from this table
1658 * @param $joinTable String: using data from this table
1659 * @param $delVar String: variable in deleteable table
1660 * @param $joinVar String: variable in data table
1661 * @param $conds Array: conditionals for join table
1662 * @param $fname String: function name for profiling
1664 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1665 if ( !$conds ) {
1666 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1669 $delTable = $this->tableName( $delTable );
1670 $joinTable = $this->tableName( $joinTable );
1671 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1672 if ( $conds != '*' ) {
1673 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1675 $sql .= ')';
1677 $this->query( $sql, $fname );
1681 * Description is left as an exercise for the reader
1682 * @param $b Mixed: data to be encoded
1683 * @return IBM_DB2Blob
1685 public function encodeBlob($b) {
1686 return new IBM_DB2Blob($b);
1690 * Description is left as an exercise for the reader
1691 * @param $b IBM_DB2Blob: data to be decoded
1692 * @return mixed
1694 public function decodeBlob($b) {
1695 return $b->getData();
1699 * Convert into a list of string being concatenated
1700 * @param $stringList Array: strings that need to be joined together by the SQL engine
1701 * @return String: joined by the concatenation operator
1703 public function buildConcat( $stringList ) {
1704 // || is equivalent to CONCAT
1705 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1706 return implode( ' || ', $stringList );
1710 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1711 * @param $column String: name of timestamp column
1712 * @return String: SQL code
1714 public function extractUnixEpoch( $column ) {
1715 // TODO
1716 // see SpecialAncientpages
1719 ######################################
1720 # Prepared statements
1721 ######################################
1724 * Intended to be compatible with the PEAR::DB wrapper functions.
1725 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1727 * ? = scalar value, quoted as necessary
1728 * ! = raw SQL bit (a function for instance)
1729 * & = filename; reads the file and inserts as a blob
1730 * (we don't use this though...)
1731 * @param $sql String: SQL statement with appropriate markers
1732 * @param $func String: Name of the function, for profiling
1733 * @return resource a prepared DB2 SQL statement
1735 public function prepare( $sql, $func = 'DB2::prepare' ) {
1736 $stmt = db2_prepare($this->mConn, $sql, $this->mStmtOptions);
1737 return $stmt;
1741 * Frees resources associated with a prepared statement
1742 * @return Boolean success or failure
1744 public function freePrepared( $prepared ) {
1745 return db2_free_stmt($prepared);
1749 * Execute a prepared query with the various arguments
1750 * @param $prepared String: the prepared sql
1751 * @param $args Mixed: either an array here, or put scalars as varargs
1752 * @return Resource: results object
1754 public function execute( $prepared, $args = null ) {
1755 if( !is_array( $args ) ) {
1756 # Pull the var args
1757 $args = func_get_args();
1758 array_shift( $args );
1760 $res = db2_execute($prepared, $args);
1761 return $res;
1765 * Prepare & execute an SQL statement, quoting and inserting arguments
1766 * in the appropriate places.
1767 * @param $query String
1768 * @param $args ...
1770 public function safeQuery( $query, $args = null ) {
1771 // copied verbatim from Database.php
1772 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1773 if( !is_array( $args ) ) {
1774 # Pull the var args
1775 $args = func_get_args();
1776 array_shift( $args );
1778 $retval = $this->execute( $prepared, $args );
1779 $this->freePrepared( $prepared );
1780 return $retval;
1784 * For faking prepared SQL statements on DBs that don't support
1785 * it directly.
1786 * @param $preparedQuery String: a 'preparable' SQL statement
1787 * @param $args Array of arguments to fill it with
1788 * @return String: executable statement
1790 public function fillPrepared( $preparedQuery, $args ) {
1791 reset( $args );
1792 $this->preparedArgs =& $args;
1794 foreach ($args as $i => $arg) {
1795 db2_bind_param($preparedQuery, $i+1, $args[$i]);
1798 return $preparedQuery;
1802 * Switches module between regular and install modes
1804 public function setMode($mode) {
1805 $old = $this->mMode;
1806 $this->mMode = $mode;
1807 return $old;
1811 * Bitwise negation of a column or value in SQL
1812 * Same as (~field) in C
1813 * @param $field String
1814 * @return String
1816 function bitNot($field) {
1817 //expecting bit-fields smaller than 4bytes
1818 return 'BITNOT('.$bitField.')';
1822 * Bitwise AND of two columns or values in SQL
1823 * Same as (fieldLeft & fieldRight) in C
1824 * @param $fieldLeft String
1825 * @param $fieldRight String
1826 * @return String
1828 function bitAnd($fieldLeft, $fieldRight) {
1829 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1833 * Bitwise OR of two columns or values in SQL
1834 * Same as (fieldLeft | fieldRight) in C
1835 * @param $fieldLeft String
1836 * @param $fieldRight String
1837 * @return String
1839 function bitOr($fieldLeft, $fieldRight) {
1840 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';