* (bug 20494) OutputPage::getArticleBodyOnly() no longer requires an useless argument
[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 * Get search engine class. All subclasses of this
1439 * need to implement this if they wish to use searching.
1440 *
1441 * @return string
1442 */
1443 public function getSearchEngine() {
1444 return "SearchIBM_DB2";
1445 }
1446
1447 /**
1448 * Did the last database access fail because of deadlock?
1449 * @return bool
1450 */
1451 public function wasDeadlock() {
1452 // get SQLSTATE
1453 $err = $this->lastErrno();
1454 switch($err) {
1455 case '40001': // sql0911n, Deadlock or timeout, rollback
1456 case '57011': // sql0904n, Resource unavailable, no rollback
1457 case '57033': // sql0913n, Deadlock or timeout, no rollback
1458 $this->installPrint("In a deadlock because of SQLSTATE $err");
1459 return true;
1460 }
1461 return false;
1462 }
1463
1464 /**
1465 * Ping the server and try to reconnect if it there is no connection
1466 * The connection may be closed and reopened while this happens
1467 * @return bool whether the connection exists
1468 */
1469 public function ping() {
1470 // db2_ping() doesn't exist
1471 // Emulate
1472 $this->close();
1473 if ($this->mCataloged == NULL) {
1474 return false;
1475 }
1476 else if ($this->mCataloged) {
1477 $this->mConn = $this->openCataloged($this->mDBName, $this->mUser, $this->mPassword);
1478 }
1479 else if (!$this->mCataloged) {
1480 $this->mConn = $this->openUncataloged($this->mDBName, $this->mUser, $this->mPassword, $this->mServer, $this->mPort);
1481 }
1482 return false;
1483 }
1484 ######################################
1485 # Unimplemented and not applicable
1486 ######################################
1487 /**
1488 * Not implemented
1489 * @return string ''
1490 * @deprecated
1491 */
1492 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1493 /**
1494 * Not implemented
1495 * TODO
1496 * @return bool true
1497 */
1498 /**
1499 * Not implemented
1500 * @deprecated
1501 */
1502 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1503 /**
1504 * Not implemented
1505 * @deprecated
1506 */
1507 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1508 /**
1509 * Not implemented
1510 * @return string $sql
1511 * @deprecated
1512 */
1513 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1514
1515 /**
1516 * Only useful with fake prepare like in base Database class
1517 * @return string
1518 */
1519 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1520
1521 ######################################
1522 # Reflection
1523 ######################################
1524
1525 /**
1526 * Query whether a given column exists in the mediawiki schema
1527 * @param string $table name of the table
1528 * @param string $field name of the column
1529 * @param string $fname function name for logging and profiling
1530 */
1531 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1532 $table = $this->tableName( $table );
1533 $schema = $this->mSchema;
1534 $etable = preg_replace("/'/", "''", $table);
1535 $eschema = preg_replace("/'/", "''", $schema);
1536 $ecol = preg_replace("/'/", "''", $field);
1537 $sql = <<<SQL
1538 SELECT 1 as fieldexists
1539 FROM sysibm.syscolumns sc
1540 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1541 SQL;
1542 $res = $this->query( $sql, $fname );
1543 $count = $res ? $this->numRows($res) : 0;
1544 if ($res)
1545 $this->freeResult( $res );
1546 return $count;
1547 }
1548
1549 /**
1550 * Returns information about an index
1551 * If errors are explicitly ignored, returns NULL on failure
1552 * @param string $table table name
1553 * @param string $index index name
1554 * @param string
1555 * @return object query row in object form
1556 */
1557 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1558 $table = $this->tableName( $table );
1559 $sql = <<<SQL
1560 SELECT name as indexname
1561 FROM sysibm.sysindexes si
1562 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1563 SQL;
1564 $res = $this->query( $sql, $fname );
1565 if ( !$res ) {
1566 return NULL;
1567 }
1568 $row = $this->fetchObject( $res );
1569 if ($row != NULL) return $row;
1570 else return false;
1571 }
1572
1573 /**
1574 * Returns an information object on a table column
1575 * @param string $table table name
1576 * @param string $field column name
1577 * @return IBM_DB2Field
1578 */
1579 public function fieldInfo( $table, $field ) {
1580 return IBM_DB2Field::fromText($this, $table, $field);
1581 }
1582
1583 /**
1584 * db2_field_type() wrapper
1585 * @param object $res Result of executed statement
1586 * @param mixed $index number or name of the column
1587 * @return string column type
1588 */
1589 public function fieldType( $res, $index ) {
1590 if ( $res instanceof ResultWrapper ) {
1591 $res = $res->result;
1592 }
1593 return db2_field_type( $res, $index );
1594 }
1595
1596 /**
1597 * Verifies that an index was created as unique
1598 * @param string $table table name
1599 * @param string $index index name
1600 * @param string $fnam function name for profiling
1601 * @return bool
1602 */
1603 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1604 $table = $this->tableName( $table );
1605 $sql = <<<SQL
1606 SELECT si.name as indexname
1607 FROM sysibm.sysindexes si
1608 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1609 AND si.uniquerule IN ('U', 'P')
1610 SQL;
1611 $res = $this->query( $sql, $fname );
1612 if ( !$res ) {
1613 return null;
1614 }
1615 if ($this->fetchObject( $res )) {
1616 return true;
1617 }
1618 return false;
1619
1620 }
1621
1622 /**
1623 * Returns the size of a text field, or -1 for "unlimited"
1624 * @param string $table table name
1625 * @param string $field column name
1626 * @return int length or -1 for unlimited
1627 */
1628 public function textFieldSize( $table, $field ) {
1629 $table = $this->tableName( $table );
1630 $sql = <<<SQL
1631 SELECT length as size
1632 FROM sysibm.syscolumns sc
1633 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1634 SQL;
1635 $res = $this->query($sql);
1636 $row = $this->fetchObject($res);
1637 $size = $row->size;
1638 $this->freeResult( $res );
1639 return $size;
1640 }
1641
1642 /**
1643 * DELETE where the condition is a join
1644 * @param string $delTable deleting from this table
1645 * @param string $joinTable using data from this table
1646 * @param string $delVar variable in deleteable table
1647 * @param string $joinVar variable in data table
1648 * @param array $conds conditionals for join table
1649 * @param string $fname function name for profiling
1650 */
1651 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1652 if ( !$conds ) {
1653 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1654 }
1655
1656 $delTable = $this->tableName( $delTable );
1657 $joinTable = $this->tableName( $joinTable );
1658 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1659 if ( $conds != '*' ) {
1660 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1661 }
1662 $sql .= ')';
1663
1664 $this->query( $sql, $fname );
1665 }
1666
1667 /**
1668 * Estimate rows in dataset
1669 * Returns estimated count, based on COUNT(*) output
1670 * Takes same arguments as Database::select()
1671 * @param string $table table name
1672 * @param array $vars unused
1673 * @param array $conds filters on the table
1674 * @param string $fname function name for profiling
1675 * @param array $options options for select
1676 * @return int row count
1677 */
1678 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1679 $rows = 0;
1680 $res = $this->select ($table, 'COUNT(*) as mwrowcount', $conds, $fname, $options );
1681 if ($res) {
1682 $row = $this->fetchRow($res);
1683 $rows = (isset($row['mwrowcount'])) ? $row['mwrowcount'] : 0;
1684 }
1685 $this->freeResult($res);
1686 return $rows;
1687 }
1688
1689 /**
1690 * Description is left as an exercise for the reader
1691 * @param mixed $b data to be encoded
1692 * @return IBM_DB2Blob
1693 */
1694 public function encodeBlob($b) {
1695 return new IBM_DB2Blob($b);
1696 }
1697
1698 /**
1699 * Description is left as an exercise for the reader
1700 * @param IBM_DB2Blob $b data to be decoded
1701 * @return mixed
1702 */
1703 public function decodeBlob($b) {
1704 return $b->getData();
1705 }
1706
1707 /**
1708 * Convert into a list of string being concatenated
1709 * @param array $stringList strings that need to be joined together by the SQL engine
1710 * @return string joined by the concatenation operator
1711 */
1712 public function buildConcat( $stringList ) {
1713 // || is equivalent to CONCAT
1714 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1715 return implode( ' || ', $stringList );
1716 }
1717
1718 /**
1719 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1720 * @param string $column name of timestamp column
1721 * @return string SQL code
1722 */
1723 public function extractUnixEpoch( $column ) {
1724 // TODO
1725 // see SpecialAncientpages
1726 }
1727
1728 ######################################
1729 # Prepared statements
1730 ######################################
1731
1732 /**
1733 * Intended to be compatible with the PEAR::DB wrapper functions.
1734 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1735 *
1736 * ? = scalar value, quoted as necessary
1737 * ! = raw SQL bit (a function for instance)
1738 * & = filename; reads the file and inserts as a blob
1739 * (we don't use this though...)
1740 * @param string $sql SQL statement with appropriate markers
1741 * @return resource a prepared DB2 SQL statement
1742 */
1743 public function prepare( $sql, $func = 'DB2::prepare' ) {
1744 $stmt = db2_prepare($this->mConn, $sql, $this->mStmtOptions);
1745 return $stmt;
1746 }
1747
1748 /**
1749 * Frees resources associated with a prepared statement
1750 * @return bool success or failure
1751 */
1752 public function freePrepared( $prepared ) {
1753 return db2_free_stmt($prepared);
1754 }
1755
1756 /**
1757 * Execute a prepared query with the various arguments
1758 * @param string $prepared the prepared sql
1759 * @param mixed $args Either an array here, or put scalars as varargs
1760 * @return resource Results object
1761 */
1762 public function execute( $prepared, $args = null ) {
1763 if( !is_array( $args ) ) {
1764 # Pull the var args
1765 $args = func_get_args();
1766 array_shift( $args );
1767 }
1768 $res = db2_execute($prepared, $args);
1769 return $res;
1770 }
1771
1772 /**
1773 * Prepare & execute an SQL statement, quoting and inserting arguments
1774 * in the appropriate places.
1775 * @param $query String
1776 * @param $args ...
1777 */
1778 public function safeQuery( $query, $args = null ) {
1779 // copied verbatim from Database.php
1780 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1781 if( !is_array( $args ) ) {
1782 # Pull the var args
1783 $args = func_get_args();
1784 array_shift( $args );
1785 }
1786 $retval = $this->execute( $prepared, $args );
1787 $this->freePrepared( $prepared );
1788 return $retval;
1789 }
1790
1791 /**
1792 * For faking prepared SQL statements on DBs that don't support
1793 * it directly.
1794 * @param resource $preparedQuery String: a 'preparable' SQL statement
1795 * @param array $args Array of arguments to fill it with
1796 * @return string executable statement
1797 */
1798 public function fillPrepared( $preparedQuery, $args ) {
1799 reset( $args );
1800 $this->preparedArgs =& $args;
1801
1802 foreach ($args as $i => $arg) {
1803 db2_bind_param($preparedQuery, $i+1, $args[$i]);
1804 }
1805
1806 return $preparedQuery;
1807 }
1808
1809 /**
1810 * Switches module between regular and install modes
1811 */
1812 public function setMode($mode) {
1813 $old = $this->mMode;
1814 $this->mMode = $mode;
1815 return $old;
1816 }
1817
1818 /**
1819 * Bitwise negation of a column or value in SQL
1820 * Same as (~field) in C
1821 * @param string $field
1822 * @return string
1823 */
1824 function bitNot($field) {
1825 //expecting bit-fields smaller than 4bytes
1826 return 'BITNOT('.$bitField.')';
1827 }
1828
1829 /**
1830 * Bitwise AND of two columns or values in SQL
1831 * Same as (fieldLeft & fieldRight) in C
1832 * @param string $fieldLeft
1833 * @param string $fieldRight
1834 * @return string
1835 */
1836 function bitAnd($fieldLeft, $fieldRight) {
1837 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1838 }
1839
1840 /**
1841 * Bitwise OR of two columns or values in SQL
1842 * Same as (fieldLeft | fieldRight) in C
1843 * @param string $fieldLeft
1844 * @param string $fieldRight
1845 * @return string
1846 */
1847 function bitOr($fieldLeft, $fieldRight) {
1848 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1849 }
1850 }