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