config/index.php:
[lhc/web/wiklou.git] / includes / db / DatabaseIbm_db2.php
1 <?php
2 /**
3 * This script is the IBM DB2 database abstraction layer
4 *
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 */
10
11 /**
12 * Utility class for generating blank objects
13 * Intended as an equivalent to {} in Javascript
14 * @ingroup Database
15 */
16 class BlankObject {
17 }
18
19
20 /**
21 * This represents a column in a DB2 database
22 * @ingroup Database
23 */
24 class IBM_DB2Field {
25 private $name = '';
26 private $tablename = '';
27 private $type = '';
28 private $nullable = false;
29 private $max_length = 0;
30
31 /**
32 * Builder method for the class
33 * @param DatabaseIbm_db2 $db Database interface
34 * @param string $table table name
35 * @param string $field column name
36 * @return IBM_DB2Field
37 */
38 static function fromText($db, $table, $field) {
39 global $wgDBmwschema;
40
41 $q = <<<END
42 SELECT
43 lcase(coltype) AS typname,
44 nulls AS attnotnull, length AS attlen
45 FROM sysibm.syscolumns
46 WHERE tbcreator=%s AND tbname=%s AND name=%s;
47 END;
48 $res = $db->query(sprintf($q,
49 $db->addQuotes($wgDBmwschema),
50 $db->addQuotes($table),
51 $db->addQuotes($field)));
52 $row = $db->fetchObject($res);
53 if (!$row)
54 return null;
55 $n = new IBM_DB2Field;
56 $n->type = $row->typname;
57 $n->nullable = ($row->attnotnull == 'N');
58 $n->name = $field;
59 $n->tablename = $table;
60 $n->max_length = $row->attlen;
61 return $n;
62 }
63 /**
64 * Get column name
65 * @return string column name
66 */
67 function name() { return $this->name; }
68 /**
69 * Get table name
70 * @return string table name
71 */
72 function tableName() { return $this->tablename; }
73 /**
74 * Get column type
75 * @return string column type
76 */
77 function type() { return $this->type; }
78 /**
79 * Can column be null?
80 * @return bool true or false
81 */
82 function nullable() { return $this->nullable; }
83 /**
84 * How much can you fit in the column per row?
85 * @return int length
86 */
87 function maxLength() { return $this->max_length; }
88 }
89
90 /**
91 * Wrapper around binary large objects
92 * @ingroup Database
93 */
94 class IBM_DB2Blob {
95 private $mData;
96
97 function __construct($data) {
98 $this->mData = $data;
99 }
100
101 function getData() {
102 return $this->mData;
103 }
104 }
105
106 /**
107 * Primary database interface
108 * @ingroup Database
109 */
110 class DatabaseIbm_db2 extends DatabaseBase {
111 /*
112 * Inherited members
113 protected $mLastQuery = '';
114 protected $mPHPError = false;
115
116 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
117 protected $mOut, $mOpened = false;
118
119 protected $mFailFunction;
120 protected $mTablePrefix;
121 protected $mFlags;
122 protected $mTrxLevel = 0;
123 protected $mErrorCount = 0;
124 protected $mLBInfo = array();
125 protected $mFakeSlaveLag = null, $mFakeMaster = false;
126 *
127 */
128
129 /// Server port for uncataloged connections
130 protected $mPort = NULL;
131 /// Whether connection is cataloged
132 protected $mCataloged = NULL;
133 /// Schema for tables, stored procedures, triggers
134 protected $mSchema = NULL;
135 /// Whether the schema has been applied in this session
136 protected $mSchemaSet = false;
137 /// Result of last query
138 protected $mLastResult = NULL;
139 /// Number of rows affected by last INSERT/UPDATE/DELETE
140 protected $mAffectedRows = NULL;
141 /// Number of rows returned by last SELECT
142 protected $mNumRows = NULL;
143
144 /// Connection config options - see constructor
145 public $mConnOptions = array();
146 /// Statement config options -- see constructor
147 public $mStmtOptions = array();
148
149
150 const CATALOGED = "cataloged";
151 const UNCATALOGED = "uncataloged";
152 const USE_GLOBAL = "get from global";
153
154 const NONE_OPTION = 0x00;
155 const CONN_OPTION = 0x01;
156 const STMT_OPTION = 0x02;
157
158 const REGULAR_MODE = 'regular';
159 const INSTALL_MODE = 'install';
160
161 // Whether this is regular operation or the initial installation
162 protected $mMode = self::REGULAR_MODE;
163
164 /// Last sequence value used for a primary key
165 protected $mInsertId = NULL;
166
167 /*
168 * These can be safely inherited
169 *
170 * Getter/Setter: (18)
171 * failFunction
172 * setOutputPage
173 * bufferResults
174 * ignoreErrors
175 * trxLevel
176 * errorCount
177 * getLBInfo
178 * setLBInfo
179 * lastQuery
180 * isOpen
181 * setFlag
182 * clearFlag
183 * getFlag
184 * getProperty
185 * getDBname
186 * getServer
187 * tableNameCallback
188 * tablePrefix
189 *
190 * Administrative: (8)
191 * debug
192 * installErrorHandler
193 * restoreErrorHandler
194 * connectionErrorHandler
195 * reportConnectionError
196 * sourceFile
197 * sourceStream
198 * replaceVars
199 *
200 * Database: (5)
201 * query
202 * set
203 * selectField
204 * generalizeSQL
205 * update
206 * strreplace
207 * deadlockLoop
208 *
209 * Prepared Statement: 6
210 * prepare
211 * freePrepared
212 * execute
213 * safeQuery
214 * fillPrepared
215 * fillPreparedArg
216 *
217 * Slave/Master: (4)
218 * masterPosWait
219 * getSlavePos
220 * getMasterPos
221 * getLag
222 *
223 * Generation: (9)
224 * tableNames
225 * tableNamesN
226 * tableNamesWithUseIndexOrJOIN
227 * escapeLike
228 * delete
229 * insertSelect
230 * timestampOrNull
231 * resultObject
232 * aggregateValue
233 * selectSQLText
234 * selectRow
235 * makeUpdateOptions
236 *
237 * Reflection: (1)
238 * indexExists
239 */
240
241 /*
242 * These have been implemented
243 *
244 * Administrative: 7 / 7
245 * constructor [Done]
246 * open [Done]
247 * openCataloged [Done]
248 * close [Done]
249 * newFromParams [Done]
250 * openUncataloged [Done]
251 * setup_database [Done]
252 *
253 * Getter/Setter: 13 / 13
254 * cascadingDeletes [Done]
255 * cleanupTriggers [Done]
256 * strictIPs [Done]
257 * realTimestamps [Done]
258 * impliciGroupby [Done]
259 * implicitOrderby [Done]
260 * searchableIPs [Done]
261 * functionalIndexes [Done]
262 * getWikiID [Done]
263 * isOpen [Done]
264 * getServerVersion [Done]
265 * getSoftwareLink [Done]
266 * getSearchEngine [Done]
267 *
268 * Database driver wrapper: 23 / 23
269 * lastError [Done]
270 * lastErrno [Done]
271 * doQuery [Done]
272 * tableExists [Done]
273 * fetchObject [Done]
274 * fetchRow [Done]
275 * freeResult [Done]
276 * numRows [Done]
277 * numFields [Done]
278 * fieldName [Done]
279 * insertId [Done]
280 * dataSeek [Done]
281 * affectedRows [Done]
282 * selectDB [Done]
283 * strencode [Done]
284 * conditional [Done]
285 * wasDeadlock [Done]
286 * ping [Done]
287 * getStatus [Done]
288 * setTimeout [Done]
289 * lock [Done]
290 * unlock [Done]
291 * insert [Done]
292 * select [Done]
293 *
294 * Slave/master: 2 / 2
295 * setFakeSlaveLag [Done]
296 * setFakeMaster [Done]
297 *
298 * Reflection: 6 / 6
299 * fieldExists [Done]
300 * indexInfo [Done]
301 * fieldInfo [Done]
302 * fieldType [Done]
303 * indexUnique [Done]
304 * textFieldSize [Done]
305 *
306 * Generation: 16 / 16
307 * tableName [Done]
308 * addQuotes [Done]
309 * makeList [Done]
310 * makeSelectOptions [Done]
311 * estimateRowCount [Done]
312 * nextSequenceValue [Done]
313 * useIndexClause [Done]
314 * replace [Done]
315 * deleteJoin [Done]
316 * lowPriorityOption [Done]
317 * limitResult [Done]
318 * limitResultForUpdate [Done]
319 * timestamp [Done]
320 * encodeBlob [Done]
321 * decodeBlob [Done]
322 * buildConcat [Done]
323 */
324
325 ######################################
326 # Getters and Setters
327 ######################################
328
329 /**
330 * Returns true if this database supports (and uses) cascading deletes
331 */
332 function cascadingDeletes() {
333 return true;
334 }
335
336 /**
337 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
338 */
339 function cleanupTriggers() {
340 return true;
341 }
342
343 /**
344 * Returns true if this database is strict about what can be put into an IP field.
345 * Specifically, it uses a NULL value instead of an empty string.
346 */
347 function strictIPs() {
348 return true;
349 }
350
351 /**
352 * Returns true if this database uses timestamps rather than integers
353 */
354 function realTimestamps() {
355 return true;
356 }
357
358 /**
359 * Returns true if this database does an implicit sort when doing GROUP BY
360 */
361 function implicitGroupby() {
362 return false;
363 }
364
365 /**
366 * Returns true if this database does an implicit order by when the column has an index
367 * For example: SELECT page_title FROM page LIMIT 1
368 */
369 function implicitOrderby() {
370 return false;
371 }
372
373 /**
374 * Returns true if this database can do a native search on IP columns
375 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
376 */
377 function searchableIPs() {
378 return true;
379 }
380
381 /**
382 * Returns true if this database can use functional indexes
383 */
384 function functionalIndexes() {
385 return true;
386 }
387
388 /**
389 * Returns a unique string representing the wiki on the server
390 */
391 function getWikiID() {
392 if( $this->mSchema ) {
393 return "{$this->mDBname}-{$this->mSchema}";
394 } else {
395 return $this->mDBname;
396 }
397 }
398
399
400 ######################################
401 # Setup
402 ######################################
403
404
405 /**
406 *
407 * @param string $server hostname of database server
408 * @param string $user username
409 * @param string $password
410 * @param string $dbName database name on the server
411 * @param function $failFunction (optional)
412 * @param integer $flags database behaviour flags (optional, unused)
413 */
414 public function DatabaseIbm_db2($server = false, $user = false, $password = false,
415 $dbName = false, $failFunction = false, $flags = 0,
416 $schema = self::USE_GLOBAL )
417 {
418
419 global $wgOut, $wgDBmwschema;
420 # Can't get a reference if it hasn't been set yet
421 if ( !isset( $wgOut ) ) {
422 $wgOut = NULL;
423 }
424 $this->mOut =& $wgOut;
425 $this->mFailFunction = $failFunction;
426 $this->mFlags = DBO_TRX | $flags;
427
428 if ( $schema == self::USE_GLOBAL ) {
429 $this->mSchema = $wgDBmwschema;
430 }
431 else {
432 $this->mSchema = $schema;
433 }
434
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);
439
440 $this->open( $server, $user, $password, $dbName);
441 }
442
443 /**
444 * Enables options only if the ibm_db2 extension version supports them
445 * @param string $name Name of the option in the options array
446 * @param string $const Name of the constant holding the right option value
447 * @param int $type Whether this is a Connection or Statement otion
448 */
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);
453 }
454 else {
455 $this->installPrint("$const is not defined. ibm_db2 version is likely too low.");
456 }
457 }
458
459 /**
460 * Outputs debug information in the appropriate place
461 * @param string $string The relevant debug message
462 */
463 private function installPrint($string) {
464 wfDebug("$string");
465 if ($this->mMode == self::INSTALL_MODE) {
466 print "<li>$string</li>";
467 flush();
468 }
469 }
470
471 /**
472 * Opens a database connection and returns it
473 * Closes any existing connection
474 * @return a fresh connection
475 * @param string $server hostname
476 * @param string $user
477 * @param string $password
478 * @param string $dbName database name
479 */
480 public function open( $server, $user, $password, $dbName )
481 {
482 // Load the port number
483 global $wgDBport_db2, $wgDBcataloged;
484 wfProfileIn( __METHOD__ );
485
486 // Load IBM DB2 driver if missing
487 if (!@extension_loaded('ibm_db2')) {
488 @dl('ibm_db2.so');
489 }
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);
495 }
496
497 if (!strlen($user)) { // Copied from Postgres
498 return null;
499 }
500
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;
510
511 if ( $cataloged == self::CATALOGED ) {
512 $this->openCataloged($dbName, $user, $password);
513 }
514 elseif ( $cataloged == self::UNCATALOGED ) {
515 $this->openUncataloged($dbName, $user, $password, $server, $port);
516 }
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);
522
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;
528 }
529
530 $this->mOpened = true;
531 $this->applySchema();
532
533 wfProfileOut( __METHOD__ );
534 return $this->mConn;
535 }
536
537 /**
538 * Opens a cataloged database connection, sets mConn
539 */
540 protected function openCataloged( $dbName, $user, $password )
541 {
542 @$this->mConn = db2_connect($dbName, $user, $password);
543 }
544
545 /**
546 * Opens an uncataloged database connection, sets mConn
547 */
548 protected function openUncataloged( $dbName, $user, $password, $server, $port )
549 {
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;";
557
558 @$this->mConn = db2_connect($str, $user, $password);
559 }
560
561 /**
562 * Closes a database connection, if it is open
563 * Returns success, true if already closed
564 */
565 public function close() {
566 $this->mOpened = false;
567 if ( $this->mConn ) {
568 if ($this->trxLevel() > 0) {
569 $this->commit();
570 }
571 return db2_close( $this->mConn );
572 }
573 else {
574 return true;
575 }
576 }
577
578 /**
579 * Returns a fresh instance of this class
580 * @static
581 * @return
582 * @param string $server hostname of database server
583 * @param string $user username
584 * @param string $password
585 * @param string $dbName database name on the server
586 * @param function $failFunction (optional)
587 * @param integer $flags database behaviour flags (optional, unused)
588 */
589 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
590 {
591 return new DatabaseIbm_db2( $server, $user, $password, $dbName, $failFunction, $flags );
592 }
593
594 /**
595 * Retrieves the most current database error
596 * Forces a database rollback
597 */
598 public function lastError() {
599 $connerr = db2_conn_errormsg();
600 if ($connerr) {
601 //$this->rollback();
602 return $connerr;
603 }
604 $stmterr = db2_stmt_errormsg();
605 if ($stmterr) {
606 //$this->rollback();
607 return $stmterr;
608 }
609
610 return false;
611 }
612
613 /**
614 * Get the last error number
615 * Return 0 if no error
616 * @return integer
617 */
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;
624 }
625
626 /**
627 * Is a database connection open?
628 * @return
629 */
630 public function isOpen() { return $this->mOpened; }
631
632 /**
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
637 */
638 /*private*/
639 public function doQuery( $sql ) {
640 //print "<li><pre>$sql</pre></li>";
641 // Switch into the correct namespace
642 $this->applySchema();
643
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 ) );
651 }
652 $this->mLastResult = $ret;
653 $this->mAffectedRows = NULL; // Not calculated until asked for
654 return $ret;
655 }
656
657 /**
658 * @return string Version information from the database
659 */
660 public function getServerVersion() {
661 $info = db2_server_info( $this->mConn );
662 return $info->DBMS_VER;
663 }
664
665 /**
666 * Queries whether a given table exists
667 * @return boolean
668 */
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;
677
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;
683 }
684
685 return false;
686 }
687
688 /**
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.
692 *
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
696 */
697 public function fetchObject( $res ) {
698 if ( $res instanceof ResultWrapper ) {
699 $res = $res->result;
700 }
701 @$row = db2_fetch_object( $res );
702 if( $this->lastErrno() ) {
703 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
704 }
705 // Make field names lowercase for compatibility with MySQL
706 if ($row)
707 {
708 $row2 = new BlankObject();
709 foreach ($row as $key => $value)
710 {
711 $keyu = strtolower($key);
712 $row2->$keyu = $value;
713 }
714 $row = $row2;
715 }
716 return $row;
717 }
718
719 /**
720 * Fetch the next row from the given result object, in associative array
721 * form. Fields are retrieved with $row['fieldname'].
722 *
723 * @param $res SQL result object as returned from Database::query(), etc.
724 * @return DB2 row object
725 * @throws DBUnexpectedError Thrown if the database returns an error
726 */
727 public function fetchRow( $res ) {
728 if ( $res instanceof ResultWrapper ) {
729 $res = $res->result;
730 }
731 @$row = db2_fetch_array( $res );
732 if ( $this->lastErrno() ) {
733 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
734 }
735 return $row;
736 }
737
738 /**
739 * Override if introduced to base Database class
740 */
741 public function initial_setup() {
742 // do nothing
743 }
744
745 /**
746 * Create tables, stored procedures, and so on
747 */
748 public function setup_database() {
749 // Timeout was being changed earlier due to mysterious crashes
750 // Changing it now may cause more problems than not changing it
751 //set_time_limit(240);
752 try {
753 // TODO: switch to root login if available
754
755 // Switch into the correct namespace
756 $this->applySchema();
757 $this->begin();
758
759 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
760 $res = null;
761
762 // TODO: update mediawiki_version table
763
764 // TODO: populate interwiki links
765
766 if ($this->lastError()) {
767 print "<li>Errors encountered during table creation -- rolled back</li>\n";
768 print "<li>Please install again</li>\n";
769 $this->rollback();
770 }
771 else {
772 $this->commit();
773 }
774 }
775 catch (MWException $mwe)
776 {
777 print "<br><pre>$mwe</pre><br>";
778 }
779 }
780
781 /**
782 * Escapes strings
783 * Doesn't escape numbers
784 * @param string s string to escape
785 * @return escaped string
786 */
787 public function addQuotes( $s ) {
788 //$this->installPrint("DB2::addQuotes($s)\n");
789 if ( is_null( $s ) ) {
790 return "NULL";
791 } else if ($s instanceof Blob) {
792 return "'".$s->fetch($s)."'";
793 }
794 $s = $this->strencode($s);
795 if ( is_numeric($s) ) {
796 return $s;
797 }
798 else {
799 return "'$s'";
800 }
801 }
802
803 /**
804 * Verifies that a DB2 column/field type is numeric
805 * @return bool true if numeric
806 * @param string $type DB2 column type
807 */
808 public function is_numeric_type( $type ) {
809 switch (strtoupper($type)) {
810 case 'SMALLINT':
811 case 'INTEGER':
812 case 'INT':
813 case 'BIGINT':
814 case 'DECIMAL':
815 case 'REAL':
816 case 'DOUBLE':
817 case 'DECFLOAT':
818 return true;
819 }
820 return false;
821 }
822
823 /**
824 * Alias for addQuotes()
825 * @param string s string to escape
826 * @return escaped string
827 */
828 public function strencode( $s ) {
829 // Bloody useless function
830 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
831 // But also necessary
832 $s = db2_escape_string($s);
833 // Wide characters are evil -- some of them look like '
834 $s = utf8_encode($s);
835 // Fix its stupidity
836 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
837 $to = array("\\", "''", "\n", "\t", '"', "\r");
838 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
839 return $s;
840 }
841
842 /**
843 * Switch into the database schema
844 */
845 protected function applySchema() {
846 if ( !($this->mSchemaSet) ) {
847 $this->mSchemaSet = true;
848 $this->begin();
849 $this->doQuery("SET SCHEMA = $this->mSchema");
850 $this->commit();
851 }
852 }
853
854 /**
855 * Start a transaction (mandatory)
856 */
857 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
858 // turn off auto-commit
859 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_OFF);
860 $this->mTrxLevel = 1;
861 }
862
863 /**
864 * End a transaction
865 * Must have a preceding begin()
866 */
867 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
868 db2_commit($this->mConn);
869 // turn auto-commit back on
870 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
871 $this->mTrxLevel = 0;
872 }
873
874 /**
875 * Cancel a transaction
876 */
877 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
878 db2_rollback($this->mConn);
879 // turn auto-commit back on
880 // not sure if this is appropriate
881 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
882 $this->mTrxLevel = 0;
883 }
884
885 /**
886 * Makes an encoded list of strings from an array
887 * $mode:
888 * LIST_COMMA - comma separated, no field names
889 * LIST_AND - ANDed WHERE clause (without the WHERE)
890 * LIST_OR - ORed WHERE clause (without the WHERE)
891 * LIST_SET - comma separated with field names, like a SET clause
892 * LIST_NAMES - comma separated field names
893 */
894 public function makeList( $a, $mode = LIST_COMMA ) {
895 $this->installPrint("DB2::makeList()\n");
896 if ( !is_array( $a ) ) {
897 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
898 }
899
900 $first = true;
901 $list = '';
902 foreach ( $a as $field => $value ) {
903 if ( !$first ) {
904 if ( $mode == LIST_AND ) {
905 $list .= ' AND ';
906 } elseif($mode == LIST_OR) {
907 $list .= ' OR ';
908 } else {
909 $list .= ',';
910 }
911 } else {
912 $first = false;
913 }
914 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
915 $list .= "($value)";
916 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
917 $list .= "$value";
918 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
919 if( count( $value ) == 0 ) {
920 throw new MWException( __METHOD__.': empty input' );
921 } elseif( count( $value ) == 1 ) {
922 // Special-case single values, as IN isn't terribly efficient
923 // Don't necessarily assume the single key is 0; we don't
924 // enforce linear numeric ordering on other arrays here.
925 $value = array_values( $value );
926 $list .= $field." = ".$this->addQuotes( $value[0] );
927 } else {
928 $list .= $field." IN (".$this->makeList($value).") ";
929 }
930 } elseif( is_null($value) ) {
931 if ( $mode == LIST_AND || $mode == LIST_OR ) {
932 $list .= "$field IS ";
933 } elseif ( $mode == LIST_SET ) {
934 $list .= "$field = ";
935 }
936 $list .= 'NULL';
937 } else {
938 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
939 $list .= "$field = ";
940 }
941 if ( $mode == LIST_NAMES ) {
942 $list .= $value;
943 }
944 // Leo: Can't insert quoted numbers into numeric columns
945 // (?) Might cause other problems. May have to check column type before insertion.
946 else if ( is_numeric($value) ) {
947 $list .= $value;
948 }
949 else {
950 $list .= $this->addQuotes( $value );
951 }
952 }
953 }
954 return $list;
955 }
956
957 /**
958 * Construct a LIMIT query with optional offset
959 * This is used for query pages
960 * $sql string SQL query we will append the limit too
961 * $limit integer the SQL limit
962 * $offset integer the SQL offset (default false)
963 */
964 public function limitResult($sql, $limit, $offset=false) {
965 if( !is_numeric($limit) ) {
966 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
967 }
968 if( $offset ) {
969 $this->installPrint("Offset parameter not supported in limitResult()\n");
970 }
971 // TODO implement proper offset handling
972 // idea: get all the rows between 0 and offset, advance cursor to offset
973 return "$sql FETCH FIRST $limit ROWS ONLY ";
974 }
975
976 /**
977 * Handle reserved keyword replacement in table names
978 * @return
979 * @param $name Object
980 */
981 public function tableName( $name ) {
982 # Replace reserved words with better ones
983 // switch( $name ) {
984 // case 'user':
985 // return 'mwuser';
986 // case 'text':
987 // return 'pagecontent';
988 // default:
989 // return $name;
990 // }
991 // we want maximum compatibility with MySQL schema
992 return $name;
993 }
994
995 /**
996 * Generates a timestamp in an insertable format
997 * @return string timestamp value
998 * @param timestamp $ts
999 */
1000 public function timestamp( $ts=0 ) {
1001 // TS_MW cannot be easily distinguished from an integer
1002 return wfTimestamp(TS_DB2,$ts);
1003 }
1004
1005 /**
1006 * Return the next in a sequence, save the value for retrieval via insertId()
1007 * @param string seqName Name of a defined sequence in the database
1008 * @return next value in that sequence
1009 */
1010 public function nextSequenceValue( $seqName ) {
1011 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1012 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1013 /*
1014 $safeseq = preg_replace( "/'/", "''", $seqName );
1015 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1016 $row = $this->fetchRow( $res );
1017 $this->mInsertId = $row[0];
1018 $this->freeResult( $res );
1019 return $this->mInsertId;
1020 */
1021 return NULL;
1022 }
1023
1024 /**
1025 * This must be called after nextSequenceVal
1026 * @return Last sequence value used as a primary key
1027 */
1028 public function insertId() {
1029 return $this->mInsertId;
1030 }
1031
1032 /**
1033 * INSERT wrapper, inserts an array into a table
1034 *
1035 * $args may be a single associative array, or an array of these with numeric keys,
1036 * for multi-row insert
1037 *
1038 * @param array $table String: Name of the table to insert to.
1039 * @param array $args Array: Items to insert into the table.
1040 * @param array $fname String: Name of the function, for profiling
1041 * @param mixed $options String or Array. Valid options: IGNORE
1042 *
1043 * @return bool Success of insert operation. IGNORE always returns true.
1044 */
1045 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1046 $this->installPrint("DB2::insert($table)\n");
1047 if ( !count( $args ) ) {
1048 return true;
1049 }
1050 // get database-specific table name (not used)
1051 $table = $this->tableName( $table );
1052 // format options as an array
1053 if ( !is_array( $options ) ) $options = array( $options );
1054 // format args as an array of arrays
1055 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1056 $args = array($args);
1057 }
1058 // prevent insertion of NULL into primary key columns
1059 $args = $this->removeNullPrimaryKeys($table, $args);
1060
1061 // get column names
1062 $keys = array_keys( $args[0] );
1063 $key_count = count($keys);
1064
1065 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1066 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
1067
1068 // If we are not in a transaction, we need to be for savepoint trickery
1069 $didbegin = 0;
1070 if (! $this->mTrxLevel) {
1071 $this->begin();
1072 $didbegin = 1;
1073 }
1074 if ( $ignore ) {
1075 $olde = error_reporting( 0 );
1076 // For future use, we may want to track the number of actual inserts
1077 // Right now, insert (all writes) simply return true/false
1078 $numrowsinserted = 0;
1079 }
1080
1081 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1082 switch($key_count) {
1083 //case 0 impossible
1084 case 1:
1085 $sql .= '(?)';
1086 break;
1087 default:
1088 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1089 }
1090 $stmt = $this->prepare($sql);
1091
1092 if ( !$ignore ) {
1093 $first = true;
1094 foreach ( $args as $row ) {
1095 // insert each row into the database
1096 $this->execute($stmt, $row);
1097 }
1098 }
1099 else {
1100 // we must have autocommit turned off -- transaction mode on
1101 $this->begin();
1102
1103 $res = true;
1104 foreach ( $args as $row ) {
1105 if ( $ignore ) {
1106 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1107 db2_exec($this->mConn, $overhead, $this->mStmtOptions);
1108 }
1109
1110 $this->execute($sql, $row);
1111 if ( $ignore ) {
1112 $bar = $this->lastError();
1113 if (!$bar) {
1114 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions );
1115 }
1116 else {
1117 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions );
1118 $numrowsinserted++;
1119 }
1120 }
1121 }
1122 }
1123
1124 // commit either way
1125 $this->commit();
1126
1127 if ( $ignore ) {
1128 $olde = error_reporting( $olde );
1129 // Set the affected row count for the whole operation
1130 $this->mAffectedRows = $numrowsinserted;
1131
1132 // IGNORE always returns true
1133 return true;
1134 }
1135
1136 return $res;
1137 }
1138
1139 /**
1140 * Given a table name and a hash of columns with values
1141 * Removes primary key columns from the hash where the value is NULL
1142 *
1143 * @param string $table Name of the table
1144 * @param array $args Array of hashes of column names with values
1145 * @return array Filtered array of hashes
1146 */
1147 private function removeNullPrimaryKeys($table, $args) {
1148 $schema = $this->mSchema;
1149 // find out the primary keys
1150 $keyres = db2_primary_keys($this->mConn, null, strtoupper($schema), strtoupper($table));
1151 $keys = array();
1152 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1153 $keys[] = strtolower($row->column_name);
1154 }
1155 // remove primary keys
1156 foreach ($args as $ai => $row) {
1157 foreach ($keys as $ki => $key) {
1158 if ($row[$key] == NULL) {
1159 unset($row[$key]);
1160 }
1161 }
1162 $args[$ai] = $row;
1163 }
1164 // return modified hash
1165 return $args;
1166 }
1167
1168 /**
1169 * UPDATE wrapper, takes a condition array and a SET array
1170 *
1171 * @param string $table The table to UPDATE
1172 * @param array $values An array of values to SET
1173 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1174 * @param string $fname The Class::Function calling this function
1175 * (for the log)
1176 * @param array $options An array of UPDATE options, can be one or
1177 * more of IGNORE, LOW_PRIORITY
1178 * @return bool
1179 */
1180 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1181 $table = $this->tableName( $table );
1182 $opts = $this->makeUpdateOptions( $options );
1183 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1184 if ( $conds != '*' ) {
1185 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1186 }
1187 return $this->query( $sql, $fname );
1188 }
1189
1190 /**
1191 * DELETE query wrapper
1192 *
1193 * Use $conds == "*" to delete all rows
1194 */
1195 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1196 if ( !$conds ) {
1197 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1198 }
1199 $table = $this->tableName( $table );
1200 $sql = "DELETE FROM $table";
1201 if ( $conds != '*' ) {
1202 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1203 }
1204 return $this->query( $sql, $fname );
1205 }
1206
1207 /**
1208 * Returns the number of rows affected by the last query or 0
1209 * @return int the number of rows affected by the last query
1210 */
1211 public function affectedRows() {
1212 if ( !is_null( $this->mAffectedRows ) ) {
1213 // Forced result for simulated queries
1214 return $this->mAffectedRows;
1215 }
1216 if( empty( $this->mLastResult ) )
1217 return 0;
1218 return db2_num_rows( $this->mLastResult );
1219 }
1220
1221 /**
1222 * Simulates REPLACE with a DELETE followed by INSERT
1223 * @param $table Object
1224 * @param array $uniqueIndexes array consisting of indexes and arrays of indexes
1225 * @param array $rows Rows to insert
1226 * @param string $fname Name of the function for profiling
1227 * @return nothing
1228 */
1229 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1230 $table = $this->tableName( $table );
1231
1232 if (count($rows)==0) {
1233 return;
1234 }
1235
1236 # Single row case
1237 if ( !is_array( reset( $rows ) ) ) {
1238 $rows = array( $rows );
1239 }
1240
1241 foreach( $rows as $row ) {
1242 # Delete rows which collide
1243 if ( $uniqueIndexes ) {
1244 $sql = "DELETE FROM $table WHERE ";
1245 $first = true;
1246 foreach ( $uniqueIndexes as $index ) {
1247 if ( $first ) {
1248 $first = false;
1249 $sql .= "(";
1250 } else {
1251 $sql .= ') OR (';
1252 }
1253 if ( is_array( $index ) ) {
1254 $first2 = true;
1255 foreach ( $index as $col ) {
1256 if ( $first2 ) {
1257 $first2 = false;
1258 } else {
1259 $sql .= ' AND ';
1260 }
1261 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1262 }
1263 } else {
1264 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1265 }
1266 }
1267 $sql .= ')';
1268 $this->query( $sql, $fname );
1269 }
1270
1271 # Now insert the row
1272 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
1273 $this->makeList( $row, LIST_COMMA ) . ')';
1274 $this->query( $sql, $fname );
1275 }
1276 }
1277
1278 /**
1279 * Returns the number of rows in the result set
1280 * Has to be called right after the corresponding select query
1281 * @param object $res result set
1282 * @return int number of rows
1283 */
1284 public function numRows( $res ) {
1285 if ( $res instanceof ResultWrapper ) {
1286 $res = $res->result;
1287 }
1288 if ( $this->mNumRows ) {
1289 return $this->mNumRows;
1290 }
1291 else {
1292 return 0;
1293 }
1294 }
1295
1296 /**
1297 * Moves the row pointer of the result set
1298 * @param object $res result set
1299 * @param int $row row number
1300 * @return success or failure
1301 */
1302 public function dataSeek( $res, $row ) {
1303 if ( $res instanceof ResultWrapper ) {
1304 $res = $res->result;
1305 }
1306 return db2_fetch_row( $res, $row );
1307 }
1308
1309 ###
1310 # Fix notices in Block.php
1311 ###
1312
1313 /**
1314 * Frees memory associated with a statement resource
1315 * @param object $res Statement resource to free
1316 * @return bool success or failure
1317 */
1318 public function freeResult( $res ) {
1319 if ( $res instanceof ResultWrapper ) {
1320 $res = $res->result;
1321 }
1322 if ( !@db2_free_result( $res ) ) {
1323 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1324 }
1325 }
1326
1327 /**
1328 * Returns the number of columns in a resource
1329 * @param object $res Statement resource
1330 * @return Number of fields/columns in resource
1331 */
1332 public function numFields( $res ) {
1333 if ( $res instanceof ResultWrapper ) {
1334 $res = $res->result;
1335 }
1336 return db2_num_fields( $res );
1337 }
1338
1339 /**
1340 * Returns the nth column name
1341 * @param object $res Statement resource
1342 * @param int $n Index of field or column
1343 * @return string name of nth column
1344 */
1345 public function fieldName( $res, $n ) {
1346 if ( $res instanceof ResultWrapper ) {
1347 $res = $res->result;
1348 }
1349 return db2_field_name( $res, $n );
1350 }
1351
1352 /**
1353 * SELECT wrapper
1354 *
1355 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1356 * @param mixed $vars Array or string, field name(s) to be retrieved
1357 * @param mixed $conds Array or string, condition(s) for WHERE
1358 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1359 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1360 * see Database::makeSelectOptions code for list of supported stuff
1361 * @param array $join_conds Associative array of table join conditions (optional)
1362 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1363 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1364 */
1365 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1366 {
1367 $res = parent::select( $table, $vars, $conds, $fname, $options, $join_conds );
1368
1369 // We must adjust for offset
1370 if ( isset( $options['LIMIT'] ) ) {
1371 if ( isset ($options['OFFSET'] ) ) {
1372 $limit = $options['LIMIT'];
1373 $offset = $options['OFFSET'];
1374 }
1375 }
1376
1377
1378 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1379 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1380 // Yay!
1381
1382 // we want the count
1383 $vars2 = array('count(*) as num_rows');
1384 // respecting just the limit option
1385 $options2 = array();
1386 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1387 // but don't try to emulate for GROUP BY
1388 if ( isset( $options['GROUP BY'] ) ) return $res;
1389
1390 $res2 = parent::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1391 $obj = $this->fetchObject($res2);
1392 $this->mNumRows = $obj->num_rows;
1393
1394 $this->installPrint("DatabaseIbm_db2::select: There are $this->mNumRows rows.\n");
1395
1396 return $res;
1397 }
1398
1399 /**
1400 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1401 * Has limited support for per-column options (colnum => 'DISTINCT')
1402 *
1403 * @private
1404 *
1405 * @param array $options an associative array of options to be turned into
1406 * an SQL query, valid keys are listed in the function.
1407 * @return array
1408 */
1409 function makeSelectOptions( $options ) {
1410 $preLimitTail = $postLimitTail = '';
1411 $startOpts = '';
1412
1413 $noKeyOptions = array();
1414 foreach ( $options as $key => $option ) {
1415 if ( is_numeric( $key ) ) {
1416 $noKeyOptions[$option] = true;
1417 }
1418 }
1419
1420 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1421 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1422 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1423
1424 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1425
1426 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1427 }
1428
1429 /**
1430 * Returns link to IBM DB2 free download
1431 * @return string wikitext of a link to the server software's web site
1432 */
1433 public function getSoftwareLink() {
1434 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1435 }
1436
1437 /**
1438 * @return String: Database type for use in messages
1439 */
1440 function getDBtypeForMsg() {
1441 return 'IBM DB2';
1442 }
1443
1444 ###
1445 # Fix search crash
1446 ###
1447 /**
1448 * Get search engine class. All subclasses of this
1449 * need to implement this if they wish to use searching.
1450 *
1451 * @return string
1452 */
1453 public function getSearchEngine() {
1454 return "SearchIBM_DB2";
1455 }
1456
1457 ###
1458 # Tuesday the 14th of October, 2008
1459 ###
1460 /**
1461 * Did the last database access fail because of deadlock?
1462 * @return bool
1463 */
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;
1473 }
1474 return false;
1475 }
1476
1477 /**
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 bool whether the connection exists
1481 */
1482 public function ping() {
1483 // db2_ping() doesn't exist
1484 // Emulate
1485 $this->close();
1486 if ($this->mCataloged == NULL) {
1487 return false;
1488 }
1489 else if ($this->mCataloged) {
1490 $this->mConn = $this->openCataloged($this->mDBName, $this->mUser, $this->mPassword);
1491 }
1492 else if (!$this->mCataloged) {
1493 $this->mConn = $this->openUncataloged($this->mDBName, $this->mUser, $this->mPassword, $this->mServer, $this->mPort);
1494 }
1495 return false;
1496 }
1497 ######################################
1498 # Unimplemented and not applicable
1499 ######################################
1500 /**
1501 * Not implemented
1502 * @return string ''
1503 * @deprecated
1504 */
1505 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1506 /**
1507 * Not implemented
1508 * TODO
1509 * @return bool true
1510 */
1511 /**
1512 * Not implemented
1513 * @deprecated
1514 */
1515 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1516 /**
1517 * Not implemented
1518 * @deprecated
1519 */
1520 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1521 /**
1522 * Not implemented
1523 * @return string $sql
1524 * @deprecated
1525 */
1526 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1527
1528 /**
1529 * Only useful with fake prepare like in base Database class
1530 * @return string
1531 */
1532 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1533
1534 ######################################
1535 # Reflection
1536 ######################################
1537
1538 /**
1539 * Query whether a given column exists in the mediawiki schema
1540 * @param string $table name of the table
1541 * @param string $field name of the column
1542 * @param string $fname function name for logging and profiling
1543 */
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;
1560 }
1561
1562 /**
1563 * Returns information about an index
1564 * If errors are explicitly ignored, returns NULL on failure
1565 * @param string $table table name
1566 * @param string $index index name
1567 * @param string
1568 * @return object query row in object form
1569 */
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;
1580 }
1581 $row = $this->fetchObject( $res );
1582 if ($row != NULL) return $row;
1583 else return false;
1584 }
1585
1586 /**
1587 * Returns an information object on a table column
1588 * @param string $table table name
1589 * @param string $field column name
1590 * @return IBM_DB2Field
1591 */
1592 public function fieldInfo( $table, $field ) {
1593 return IBM_DB2Field::fromText($this, $table, $field);
1594 }
1595
1596 /**
1597 * db2_field_type() wrapper
1598 * @param object $res Result of executed statement
1599 * @param mixed $index number or name of the column
1600 * @return string column type
1601 */
1602 public function fieldType( $res, $index ) {
1603 if ( $res instanceof ResultWrapper ) {
1604 $res = $res->result;
1605 }
1606 return db2_field_type( $res, $index );
1607 }
1608
1609 /**
1610 * Verifies that an index was created as unique
1611 * @param string $table table name
1612 * @param string $index index name
1613 * @param string $fnam function name for profiling
1614 * @return bool
1615 */
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;
1627 }
1628 if ($this->fetchObject( $res )) {
1629 return true;
1630 }
1631 return false;
1632
1633 }
1634
1635 /**
1636 * Returns the size of a text field, or -1 for "unlimited"
1637 * @param string $table table name
1638 * @param string $field column name
1639 * @return int length or -1 for unlimited
1640 */
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;
1653 }
1654
1655 /**
1656 * DELETE where the condition is a join
1657 * @param string $delTable deleting from this table
1658 * @param string $joinTable using data from this table
1659 * @param string $delVar variable in deleteable table
1660 * @param string $joinVar variable in data table
1661 * @param array $conds conditionals for join table
1662 * @param string $fname function name for profiling
1663 */
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' );
1667 }
1668
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 );
1674 }
1675 $sql .= ')';
1676
1677 $this->query( $sql, $fname );
1678 }
1679
1680 /**
1681 * Estimate rows in dataset
1682 * Returns estimated count, based on COUNT(*) output
1683 * Takes same arguments as Database::select()
1684 * @param string $table table name
1685 * @param array $vars unused
1686 * @param array $conds filters on the table
1687 * @param string $fname function name for profiling
1688 * @param array $options options for select
1689 * @return int row count
1690 */
1691 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1692 $rows = 0;
1693 $res = $this->select ($table, 'COUNT(*) as mwrowcount', $conds, $fname, $options );
1694 if ($res) {
1695 $row = $this->fetchRow($res);
1696 $rows = (isset($row['mwrowcount'])) ? $row['mwrowcount'] : 0;
1697 }
1698 $this->freeResult($res);
1699 return $rows;
1700 }
1701
1702 /**
1703 * Description is left as an exercise for the reader
1704 * @param mixed $b data to be encoded
1705 * @return IBM_DB2Blob
1706 */
1707 public function encodeBlob($b) {
1708 return new IBM_DB2Blob($b);
1709 }
1710
1711 /**
1712 * Description is left as an exercise for the reader
1713 * @param IBM_DB2Blob $b data to be decoded
1714 * @return mixed
1715 */
1716 public function decodeBlob($b) {
1717 return $b->getData();
1718 }
1719
1720 /**
1721 * Convert into a list of string being concatenated
1722 * @param array $stringList strings that need to be joined together by the SQL engine
1723 * @return string joined by the concatenation operator
1724 */
1725 public function buildConcat( $stringList ) {
1726 // || is equivalent to CONCAT
1727 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1728 return implode( ' || ', $stringList );
1729 }
1730
1731 /**
1732 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1733 * @param string $column name of timestamp column
1734 * @return string SQL code
1735 */
1736 public function extractUnixEpoch( $column ) {
1737 // TODO
1738 // see SpecialAncientpages
1739 }
1740
1741 ######################################
1742 # Prepared statements
1743 ######################################
1744
1745 /**
1746 * Intended to be compatible with the PEAR::DB wrapper functions.
1747 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1748 *
1749 * ? = scalar value, quoted as necessary
1750 * ! = raw SQL bit (a function for instance)
1751 * & = filename; reads the file and inserts as a blob
1752 * (we don't use this though...)
1753 * @param string $sql SQL statement with appropriate markers
1754 * @return resource a prepared DB2 SQL statement
1755 */
1756 public function prepare( $sql, $func = 'DB2::prepare' ) {
1757 $stmt = db2_prepare($this->mConn, $sql, $this->mStmtOptions);
1758 return $stmt;
1759 }
1760
1761 /**
1762 * Frees resources associated with a prepared statement
1763 * @return bool success or failure
1764 */
1765 public function freePrepared( $prepared ) {
1766 return db2_free_stmt($prepared);
1767 }
1768
1769 /**
1770 * Execute a prepared query with the various arguments
1771 * @param string $prepared the prepared sql
1772 * @param mixed $args Either an array here, or put scalars as varargs
1773 * @return resource Results object
1774 */
1775 public function execute( $prepared, $args = null ) {
1776 if( !is_array( $args ) ) {
1777 # Pull the var args
1778 $args = func_get_args();
1779 array_shift( $args );
1780 }
1781 $res = db2_execute($prepared, $args);
1782 return $res;
1783 }
1784
1785 /**
1786 * Prepare & execute an SQL statement, quoting and inserting arguments
1787 * in the appropriate places.
1788 * @param $query String
1789 * @param $args ...
1790 */
1791 public function safeQuery( $query, $args = null ) {
1792 // copied verbatim from Database.php
1793 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1794 if( !is_array( $args ) ) {
1795 # Pull the var args
1796 $args = func_get_args();
1797 array_shift( $args );
1798 }
1799 $retval = $this->execute( $prepared, $args );
1800 $this->freePrepared( $prepared );
1801 return $retval;
1802 }
1803
1804 /**
1805 * For faking prepared SQL statements on DBs that don't support
1806 * it directly.
1807 * @param resource $preparedQuery String: a 'preparable' SQL statement
1808 * @param array $args Array of arguments to fill it with
1809 * @return string executable statement
1810 */
1811 public function fillPrepared( $preparedQuery, $args ) {
1812 reset( $args );
1813 $this->preparedArgs =& $args;
1814
1815 foreach ($args as $i => $arg) {
1816 db2_bind_param($preparedQuery, $i+1, $args[$i]);
1817 }
1818
1819 return $preparedQuery;
1820 }
1821
1822 /**
1823 * Switches module between regular and install modes
1824 */
1825 public function setMode($mode) {
1826 $old = $this->mMode;
1827 $this->mMode = $mode;
1828 return $old;
1829 }
1830
1831 /**
1832 * Bitwise negation of a column or value in SQL
1833 * Same as (~field) in C
1834 * @param string $field
1835 * @return string
1836 */
1837 function bitNot($field) {
1838 //expecting bit-fields smaller than 4bytes
1839 return 'BITNOT('.$bitField.')';
1840 }
1841
1842 /**
1843 * Bitwise AND of two columns or values in SQL
1844 * Same as (fieldLeft & fieldRight) in C
1845 * @param string $fieldLeft
1846 * @param string $fieldRight
1847 * @return string
1848 */
1849 function bitAnd($fieldLeft, $fieldRight) {
1850 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1851 }
1852
1853 /**
1854 * Bitwise OR of two columns or values in SQL
1855 * Same as (fieldLeft | fieldRight) in C
1856 * @param string $fieldLeft
1857 * @param string $fieldRight
1858 * @return string
1859 */
1860 function bitOr($fieldLeft, $fieldRight) {
1861 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1862 }
1863 }