Cleanup most of the DIY extension detection/dl() code into nice clean wfDl()
[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 $db DatabaseIbm_db2: Database interface
25 * @param $table String: table name
26 * @param $field String: 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 $server String: hostname of database server
407 * @param $user String: username
408 * @param $password String: password
409 * @param $dbName String: database name on the server
410 * @param $failFunction Callback (optional)
411 * @param $flags Integer: database behaviour flags (optional, unused)
412 * @param $schema String
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 $name String: name of the option in the options array
446 * @param $const String: name of the constant holding the right option value
447 * @param $type Integer: whether this is a Connection or Statement otion
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 $server String: hostname
476 * @param $user String
477 * @param $password String
478 * @param $dbName String: 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 wfDl( 'ibm_db2' );
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 ) {
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 *
580 * @param $server String: hostname of database server
581 * @param $user String: username
582 * @param $password String
583 * @param $dbName String: database name on the server
584 * @param $failFunction Callback (optional)
585 * @param $flags Integer: database behaviour flags (optional, unused)
586 * @return DatabaseIbm_db2 object
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 if ($res !== true) {
749 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
750 } else {
751 print " done</li>";
752 }
753 $res = null;
754
755 // TODO: populate interwiki links
756
757 if ($this->lastError()) {
758 print "<li>Errors encountered during table creation -- rolled back</li>\n";
759 print "<li>Please install again</li>\n";
760 $this->rollback();
761 }
762 else {
763 $this->commit();
764 }
765 }
766 catch (MWException $mwe)
767 {
768 print "<br><pre>$mwe</pre><br>";
769 }
770 }
771
772 /**
773 * Escapes strings
774 * Doesn't escape numbers
775 * @param $s String: string to escape
776 * @return escaped string
777 */
778 public function addQuotes( $s ) {
779 //$this->installPrint("DB2::addQuotes($s)\n");
780 if ( is_null( $s ) ) {
781 return "NULL";
782 } else if ($s instanceof Blob) {
783 return "'".$s->fetch($s)."'";
784 } else if ($s instanceof IBM_DB2Blob) {
785 return "'".$this->decodeBlob($s)."'";
786 }
787 $s = $this->strencode($s);
788 if ( is_numeric($s) ) {
789 return $s;
790 }
791 else {
792 return "'$s'";
793 }
794 }
795
796 /**
797 * Verifies that a DB2 column/field type is numeric
798 * @return bool true if numeric
799 * @param $type String: DB2 column type
800 */
801 public function is_numeric_type( $type ) {
802 switch (strtoupper($type)) {
803 case 'SMALLINT':
804 case 'INTEGER':
805 case 'INT':
806 case 'BIGINT':
807 case 'DECIMAL':
808 case 'REAL':
809 case 'DOUBLE':
810 case 'DECFLOAT':
811 return true;
812 }
813 return false;
814 }
815
816 /**
817 * Alias for addQuotes()
818 * @param $s String: string to escape
819 * @return escaped string
820 */
821 public function strencode( $s ) {
822 // Bloody useless function
823 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
824 // But also necessary
825 $s = db2_escape_string($s);
826 // Wide characters are evil -- some of them look like '
827 $s = utf8_encode($s);
828 // Fix its stupidity
829 $from = array("\\\\", "\\'", '\\n', '\\t', '\\"', '\\r');
830 $to = array("\\", "''", "\n", "\t", '"', "\r");
831 $s = str_replace($from, $to, $s); // DB2 expects '', not \' escaping
832 return $s;
833 }
834
835 /**
836 * Switch into the database schema
837 */
838 protected function applySchema() {
839 if ( !($this->mSchemaSet) ) {
840 $this->mSchemaSet = true;
841 $this->begin();
842 $this->doQuery("SET SCHEMA = $this->mSchema");
843 $this->commit();
844 }
845 }
846
847 /**
848 * Start a transaction (mandatory)
849 */
850 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
851 // turn off auto-commit
852 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_OFF);
853 $this->mTrxLevel = 1;
854 }
855
856 /**
857 * End a transaction
858 * Must have a preceding begin()
859 */
860 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
861 db2_commit($this->mConn);
862 // turn auto-commit back on
863 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
864 $this->mTrxLevel = 0;
865 }
866
867 /**
868 * Cancel a transaction
869 */
870 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
871 db2_rollback($this->mConn);
872 // turn auto-commit back on
873 // not sure if this is appropriate
874 db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
875 $this->mTrxLevel = 0;
876 }
877
878 /**
879 * Makes an encoded list of strings from an array
880 * $mode:
881 * LIST_COMMA - comma separated, no field names
882 * LIST_AND - ANDed WHERE clause (without the WHERE)
883 * LIST_OR - ORed WHERE clause (without the WHERE)
884 * LIST_SET - comma separated with field names, like a SET clause
885 * LIST_NAMES - comma separated field names
886 */
887 public function makeList( $a, $mode = LIST_COMMA ) {
888 if ( !is_array( $a ) ) {
889 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
890 }
891
892 $first = true;
893 $list = '';
894 foreach ( $a as $field => $value ) {
895 if ( !$first ) {
896 if ( $mode == LIST_AND ) {
897 $list .= ' AND ';
898 } elseif($mode == LIST_OR) {
899 $list .= ' OR ';
900 } else {
901 $list .= ',';
902 }
903 } else {
904 $first = false;
905 }
906 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
907 $list .= "($value)";
908 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
909 $list .= "$value";
910 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
911 if( count( $value ) == 0 ) {
912 throw new MWException( __METHOD__.': empty input' );
913 } elseif( count( $value ) == 1 ) {
914 // Special-case single values, as IN isn't terribly efficient
915 // Don't necessarily assume the single key is 0; we don't
916 // enforce linear numeric ordering on other arrays here.
917 $value = array_values( $value );
918 $list .= $field." = ".$this->addQuotes( $value[0] );
919 } else {
920 $list .= $field." IN (".$this->makeList($value).") ";
921 }
922 } elseif( is_null($value) ) {
923 if ( $mode == LIST_AND || $mode == LIST_OR ) {
924 $list .= "$field IS ";
925 } elseif ( $mode == LIST_SET ) {
926 $list .= "$field = ";
927 }
928 $list .= 'NULL';
929 } else {
930 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
931 $list .= "$field = ";
932 }
933 if ( $mode == LIST_NAMES ) {
934 $list .= $value;
935 }
936 // Leo: Can't insert quoted numbers into numeric columns
937 // (?) Might cause other problems. May have to check column type before insertion.
938 else if ( is_numeric($value) ) {
939 $list .= $value;
940 }
941 else {
942 $list .= $this->addQuotes( $value );
943 }
944 }
945 }
946 return $list;
947 }
948
949 /**
950 * Construct a LIMIT query with optional offset
951 * This is used for query pages
952 * @param $sql string SQL query we will append the limit too
953 * @param $limit integer the SQL limit
954 * @param $offset integer the SQL offset (default false)
955 */
956 public function limitResult($sql, $limit, $offset=false) {
957 if( !is_numeric($limit) ) {
958 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
959 }
960 if( $offset ) {
961 $this->installPrint("Offset parameter not supported in limitResult()\n");
962 }
963 // TODO implement proper offset handling
964 // idea: get all the rows between 0 and offset, advance cursor to offset
965 return "$sql FETCH FIRST $limit ROWS ONLY ";
966 }
967
968 /**
969 * Handle reserved keyword replacement in table names
970 * @return
971 * @param $name Object
972 */
973 public function tableName( $name ) {
974 # Replace reserved words with better ones
975 // switch( $name ) {
976 // case 'user':
977 // return 'mwuser';
978 // case 'text':
979 // return 'pagecontent';
980 // default:
981 // return $name;
982 // }
983 // we want maximum compatibility with MySQL schema
984 return $name;
985 }
986
987 /**
988 * Generates a timestamp in an insertable format
989 * @return string timestamp value
990 * @param $ts timestamp
991 */
992 public function timestamp( $ts=0 ) {
993 // TS_MW cannot be easily distinguished from an integer
994 return wfTimestamp(TS_DB2,$ts);
995 }
996
997 /**
998 * Return the next in a sequence, save the value for retrieval via insertId()
999 * @param $seqName String: name of a defined sequence in the database
1000 * @return next value in that sequence
1001 */
1002 public function nextSequenceValue( $seqName ) {
1003 // Not using sequences in the primary schema to allow for easy third-party migration scripts
1004 // Emulating MySQL behaviour of using NULL to signal that sequences aren't used
1005 /*
1006 $safeseq = preg_replace( "/'/", "''", $seqName );
1007 $res = $this->query( "VALUES NEXTVAL FOR $safeseq" );
1008 $row = $this->fetchRow( $res );
1009 $this->mInsertId = $row[0];
1010 $this->freeResult( $res );
1011 return $this->mInsertId;
1012 */
1013 return null;
1014 }
1015
1016 /**
1017 * This must be called after nextSequenceVal
1018 * @return Last sequence value used as a primary key
1019 */
1020 public function insertId() {
1021 return $this->mInsertId;
1022 }
1023
1024 /**
1025 * Updates the mInsertId property with the value of the last insert into a generated column
1026 * @param $table String: sanitized table name
1027 * @param $primaryKey Mixed: string name of the primary key or a bool if this call is a do-nothing
1028 * @param $stmt Resource: prepared statement resource
1029 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
1030 */
1031 private function calcInsertId($table, $primaryKey, $stmt) {
1032 if ($primaryKey) {
1033 $id_row = $this->fetchRow($stmt);
1034 $this->mInsertId = $id_row[0];
1035 }
1036 }
1037
1038 /**
1039 * INSERT wrapper, inserts an array into a table
1040 *
1041 * $args may be a single associative array, or an array of these with numeric keys,
1042 * for multi-row insert
1043 *
1044 * @param $table String: Name of the table to insert to.
1045 * @param $args Array: Items to insert into the table.
1046 * @param $fname String: Name of the function, for profiling
1047 * @param $options String or Array. Valid options: IGNORE
1048 *
1049 * @return bool Success of insert operation. IGNORE always returns true.
1050 */
1051 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert', $options = array() ) {
1052 if ( !count( $args ) ) {
1053 return true;
1054 }
1055 // get database-specific table name (not used)
1056 $table = $this->tableName( $table );
1057 // format options as an array
1058 if ( !is_array( $options ) ) $options = array( $options );
1059 // format args as an array of arrays
1060 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
1061 $args = array($args);
1062 }
1063 // prevent insertion of NULL into primary key columns
1064 list($args, $primaryKeys) = $this->removeNullPrimaryKeys($table, $args);
1065 // if there's only one primary key
1066 // we'll be able to read its value after insertion
1067 $primaryKey = false;
1068 if (count($primaryKeys) == 1) {
1069 $primaryKey = $primaryKeys[0];
1070 }
1071
1072 // get column names
1073 $keys = array_keys( $args[0] );
1074 $key_count = count($keys);
1075
1076 // If IGNORE is set, we use savepoints to emulate mysql's behavior
1077 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
1078
1079 // assume success
1080 $res = true;
1081 // If we are not in a transaction, we need to be for savepoint trickery
1082 $didbegin = 0;
1083 if (! $this->mTrxLevel) {
1084 $this->begin();
1085 $didbegin = 1;
1086 }
1087
1088 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1089 switch($key_count) {
1090 //case 0 impossible
1091 case 1:
1092 $sql .= '(?)';
1093 break;
1094 default:
1095 $sql .= '(?' . str_repeat(',?', $key_count-1) . ')';
1096 }
1097 // add logic to read back the new primary key value
1098 if ($primaryKey) {
1099 $sql = "SELECT $primaryKey FROM FINAL TABLE($sql)";
1100 }
1101 $stmt = $this->prepare($sql);
1102
1103 // start a transaction/enter transaction mode
1104 $this->begin();
1105
1106 if ( !$ignore ) {
1107 $first = true;
1108 foreach ( $args as $row ) {
1109 // insert each row into the database
1110 $res = $res & $this->execute($stmt, $row);
1111 // get the last inserted value into a generated column
1112 $this->calcInsertId($table, $primaryKey, $stmt);
1113 }
1114 }
1115 else {
1116 $olde = error_reporting( 0 );
1117 // For future use, we may want to track the number of actual inserts
1118 // Right now, insert (all writes) simply return true/false
1119 $numrowsinserted = 0;
1120
1121 // always return true
1122 $res = true;
1123
1124 foreach ( $args as $row ) {
1125 $overhead = "SAVEPOINT $ignore ON ROLLBACK RETAIN CURSORS";
1126 db2_exec($this->mConn, $overhead, $this->mStmtOptions);
1127
1128 $res2 = $this->execute($stmt, $row);
1129 // get the last inserted value into a generated column
1130 $this->calcInsertId($table, $primaryKey, $stmt);
1131
1132 $errNum = $this->lastErrno();
1133 if ($errNum) {
1134 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore", $this->mStmtOptions );
1135 }
1136 else {
1137 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore", $this->mStmtOptions );
1138 $numrowsinserted++;
1139 }
1140 }
1141
1142 $olde = error_reporting( $olde );
1143 // Set the affected row count for the whole operation
1144 $this->mAffectedRows = $numrowsinserted;
1145 }
1146 // commit either way
1147 $this->commit();
1148
1149 return $res;
1150 }
1151
1152 /**
1153 * Given a table name and a hash of columns with values
1154 * Removes primary key columns from the hash where the value is NULL
1155 *
1156 * @param $table String: name of the table
1157 * @param $args Array of hashes of column names with values
1158 * @return Array: tuple containing filtered array of columns, array of primary keys
1159 */
1160 private function removeNullPrimaryKeys($table, $args) {
1161 $schema = $this->mSchema;
1162 // find out the primary keys
1163 $keyres = db2_primary_keys($this->mConn, null, strtoupper($schema), strtoupper($table));
1164 $keys = array();
1165 for ($row = $this->fetchObject($keyres); $row != null; $row = $this->fetchRow($keyres)) {
1166 $keys[] = strtolower($row->column_name);
1167 }
1168 // remove primary keys
1169 foreach ($args as $ai => $row) {
1170 foreach ($keys as $ki => $key) {
1171 if ($row[$key] == null) {
1172 unset($row[$key]);
1173 }
1174 }
1175 $args[$ai] = $row;
1176 }
1177 // return modified hash
1178 return array($args, $keys);
1179 }
1180
1181 /**
1182 * UPDATE wrapper, takes a condition array and a SET array
1183 *
1184 * @param $table String: The table to UPDATE
1185 * @param $values An array of values to SET
1186 * @param $conds An array of conditions (WHERE). Use '*' to update all rows.
1187 * @param $fname String: The Class::Function calling this function
1188 * (for the log)
1189 * @param $options An array of UPDATE options, can be one or
1190 * more of IGNORE, LOW_PRIORITY
1191 * @return Boolean
1192 */
1193 public function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1194 $table = $this->tableName( $table );
1195 $opts = $this->makeUpdateOptions( $options );
1196 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1197 if ( $conds != '*' ) {
1198 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1199 }
1200 return $this->query( $sql, $fname );
1201 }
1202
1203 /**
1204 * DELETE query wrapper
1205 *
1206 * Use $conds == "*" to delete all rows
1207 */
1208 public function delete( $table, $conds, $fname = 'Database::delete' ) {
1209 if ( !$conds ) {
1210 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1211 }
1212 $table = $this->tableName( $table );
1213 $sql = "DELETE FROM $table";
1214 if ( $conds != '*' ) {
1215 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1216 }
1217 return $this->query( $sql, $fname );
1218 }
1219
1220 /**
1221 * Returns the number of rows affected by the last query or 0
1222 * @return Integer: the number of rows affected by the last query
1223 */
1224 public function affectedRows() {
1225 if ( !is_null( $this->mAffectedRows ) ) {
1226 // Forced result for simulated queries
1227 return $this->mAffectedRows;
1228 }
1229 if( empty( $this->mLastResult ) )
1230 return 0;
1231 return db2_num_rows( $this->mLastResult );
1232 }
1233
1234 /**
1235 * Simulates REPLACE with a DELETE followed by INSERT
1236 * @param $table Object
1237 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1238 * @param $rows Array: rows to insert
1239 * @param $fname String: name of the function for profiling
1240 * @return nothing
1241 */
1242 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseIbm_db2::replace' ) {
1243 $table = $this->tableName( $table );
1244
1245 if (count($rows)==0) {
1246 return;
1247 }
1248
1249 # Single row case
1250 if ( !is_array( reset( $rows ) ) ) {
1251 $rows = array( $rows );
1252 }
1253
1254 foreach( $rows as $row ) {
1255 # Delete rows which collide
1256 if ( $uniqueIndexes ) {
1257 $sql = "DELETE FROM $table WHERE ";
1258 $first = true;
1259 foreach ( $uniqueIndexes as $index ) {
1260 if ( $first ) {
1261 $first = false;
1262 $sql .= "(";
1263 } else {
1264 $sql .= ') OR (';
1265 }
1266 if ( is_array( $index ) ) {
1267 $first2 = true;
1268 foreach ( $index as $col ) {
1269 if ( $first2 ) {
1270 $first2 = false;
1271 } else {
1272 $sql .= ' AND ';
1273 }
1274 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1275 }
1276 } else {
1277 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1278 }
1279 }
1280 $sql .= ')';
1281 $this->query( $sql, $fname );
1282 }
1283
1284 # Now insert the row
1285 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
1286 $this->makeList( $row, LIST_COMMA ) . ')';
1287 $this->query( $sql, $fname );
1288 }
1289 }
1290
1291 /**
1292 * Returns the number of rows in the result set
1293 * Has to be called right after the corresponding select query
1294 * @param $res Object result set
1295 * @return Integer: number of rows
1296 */
1297 public function numRows( $res ) {
1298 if ( $res instanceof ResultWrapper ) {
1299 $res = $res->result;
1300 }
1301 if ( $this->mNumRows ) {
1302 return $this->mNumRows;
1303 }
1304 else {
1305 return 0;
1306 }
1307 }
1308
1309 /**
1310 * Moves the row pointer of the result set
1311 * @param $res Object: result set
1312 * @param $row Integer: row number
1313 * @return success or failure
1314 */
1315 public function dataSeek( $res, $row ) {
1316 if ( $res instanceof ResultWrapper ) {
1317 $res = $res->result;
1318 }
1319 return db2_fetch_row( $res, $row );
1320 }
1321
1322 ###
1323 # Fix notices in Block.php
1324 ###
1325
1326 /**
1327 * Frees memory associated with a statement resource
1328 * @param $res Object: statement resource to free
1329 * @return Boolean success or failure
1330 */
1331 public function freeResult( $res ) {
1332 if ( $res instanceof ResultWrapper ) {
1333 $res = $res->result;
1334 }
1335 if ( !@db2_free_result( $res ) ) {
1336 throw new DBUnexpectedError($this, "Unable to free DB2 result\n" );
1337 }
1338 }
1339
1340 /**
1341 * Returns the number of columns in a resource
1342 * @param $res Object: statement resource
1343 * @return Number of fields/columns in resource
1344 */
1345 public function numFields( $res ) {
1346 if ( $res instanceof ResultWrapper ) {
1347 $res = $res->result;
1348 }
1349 return db2_num_fields( $res );
1350 }
1351
1352 /**
1353 * Returns the nth column name
1354 * @param $res Object: statement resource
1355 * @param $n Integer: Index of field or column
1356 * @return String name of nth column
1357 */
1358 public function fieldName( $res, $n ) {
1359 if ( $res instanceof ResultWrapper ) {
1360 $res = $res->result;
1361 }
1362 return db2_field_name( $res, $n );
1363 }
1364
1365 /**
1366 * SELECT wrapper
1367 *
1368 * @param $table Array or string, table name(s) (prefix auto-added)
1369 * @param $vars Array or string, field name(s) to be retrieved
1370 * @param $conds Array or string, condition(s) for WHERE
1371 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
1372 * @param $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1373 * see Database::makeSelectOptions code for list of supported stuff
1374 * @param $join_conds Associative array of table join conditions (optional)
1375 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1376 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
1377 */
1378 public function select( $table, $vars, $conds='', $fname = 'DatabaseIbm_db2::select', $options = array(), $join_conds = array() )
1379 {
1380 $res = parent::select( $table, $vars, $conds, $fname, $options, $join_conds );
1381
1382 // We must adjust for offset
1383 if ( isset( $options['LIMIT'] ) ) {
1384 if ( isset ($options['OFFSET'] ) ) {
1385 $limit = $options['LIMIT'];
1386 $offset = $options['OFFSET'];
1387 }
1388 }
1389
1390
1391 // DB2 does not have a proper num_rows() function yet, so we must emulate it
1392 // DB2 9.5.3/9.5.4 and the corresponding ibm_db2 driver will introduce a working one
1393 // Yay!
1394
1395 // we want the count
1396 $vars2 = array('count(*) as num_rows');
1397 // respecting just the limit option
1398 $options2 = array();
1399 if ( isset( $options['LIMIT'] ) ) $options2['LIMIT'] = $options['LIMIT'];
1400 // but don't try to emulate for GROUP BY
1401 if ( isset( $options['GROUP BY'] ) ) return $res;
1402
1403 $res2 = parent::select( $table, $vars2, $conds, $fname, $options2, $join_conds );
1404 $obj = $this->fetchObject($res2);
1405 $this->mNumRows = $obj->num_rows;
1406
1407
1408 return $res;
1409 }
1410
1411 /**
1412 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1413 * Has limited support for per-column options (colnum => 'DISTINCT')
1414 *
1415 * @private
1416 *
1417 * @param $options Associative array of options to be turned into
1418 * an SQL query, valid keys are listed in the function.
1419 * @return Array
1420 */
1421 function makeSelectOptions( $options ) {
1422 $preLimitTail = $postLimitTail = '';
1423 $startOpts = '';
1424
1425 $noKeyOptions = array();
1426 foreach ( $options as $key => $option ) {
1427 if ( is_numeric( $key ) ) {
1428 $noKeyOptions[$option] = true;
1429 }
1430 }
1431
1432 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1433 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1434 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1435
1436 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1437
1438 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1439 }
1440
1441 /**
1442 * Returns link to IBM DB2 free download
1443 * @return string wikitext of a link to the server software's web site
1444 */
1445 public function getSoftwareLink() {
1446 return "[http://www.ibm.com/software/data/db2/express/?s_cmp=ECDDWW01&s_tact=MediaWiki IBM DB2]";
1447 }
1448
1449 /**
1450 * Get search engine class. All subclasses of this
1451 * need to implement this if they wish to use searching.
1452 *
1453 * @return String
1454 */
1455 public function getSearchEngine() {
1456 return "SearchIBM_DB2";
1457 }
1458
1459 /**
1460 * Did the last database access fail because of deadlock?
1461 * @return Boolean
1462 */
1463 public function wasDeadlock() {
1464 // get SQLSTATE
1465 $err = $this->lastErrno();
1466 switch($err) {
1467 case '40001': // sql0911n, Deadlock or timeout, rollback
1468 case '57011': // sql0904n, Resource unavailable, no rollback
1469 case '57033': // sql0913n, Deadlock or timeout, no rollback
1470 $this->installPrint("In a deadlock because of SQLSTATE $err");
1471 return true;
1472 }
1473 return false;
1474 }
1475
1476 /**
1477 * Ping the server and try to reconnect if it there is no connection
1478 * The connection may be closed and reopened while this happens
1479 * @return Boolean: whether the connection exists
1480 */
1481 public function ping() {
1482 // db2_ping() doesn't exist
1483 // Emulate
1484 $this->close();
1485 if ($this->mCataloged == null) {
1486 return false;
1487 }
1488 else if ($this->mCataloged) {
1489 $this->mConn = $this->openCataloged($this->mDBName, $this->mUser, $this->mPassword);
1490 }
1491 else if (!$this->mCataloged) {
1492 $this->mConn = $this->openUncataloged($this->mDBName, $this->mUser, $this->mPassword, $this->mServer, $this->mPort);
1493 }
1494 return false;
1495 }
1496 ######################################
1497 # Unimplemented and not applicable
1498 ######################################
1499 /**
1500 * Not implemented
1501 * @return string ''
1502 * @deprecated
1503 */
1504 public function getStatus( $which="%" ) { $this->installPrint('Not implemented for DB2: getStatus()'); return ''; }
1505 /**
1506 * Not implemented
1507 * TODO
1508 * @return bool true
1509 */
1510 /**
1511 * Not implemented
1512 * @deprecated
1513 */
1514 public function setFakeSlaveLag( $lag ) { $this->installPrint('Not implemented for DB2: setFakeSlaveLag()'); }
1515 /**
1516 * Not implemented
1517 * @deprecated
1518 */
1519 public function setFakeMaster( $enabled = true ) { $this->installPrint('Not implemented for DB2: setFakeMaster()'); }
1520 /**
1521 * Not implemented
1522 * @return string $sql
1523 * @deprecated
1524 */
1525 public function limitResultForUpdate($sql, $num) { $this->installPrint('Not implemented for DB2: limitResultForUpdate()'); return $sql; }
1526
1527 /**
1528 * Only useful with fake prepare like in base Database class
1529 * @return string
1530 */
1531 public function fillPreparedArg( $matches ) { $this->installPrint('Not useful for DB2: fillPreparedArg()'); return ''; }
1532
1533 ######################################
1534 # Reflection
1535 ######################################
1536
1537 /**
1538 * Query whether a given column exists in the mediawiki schema
1539 * @param $table String: name of the table
1540 * @param $field String: name of the column
1541 * @param $fname String: function name for logging and profiling
1542 */
1543 public function fieldExists( $table, $field, $fname = 'DatabaseIbm_db2::fieldExists' ) {
1544 $table = $this->tableName( $table );
1545 $schema = $this->mSchema;
1546 $etable = preg_replace("/'/", "''", $table);
1547 $eschema = preg_replace("/'/", "''", $schema);
1548 $ecol = preg_replace("/'/", "''", $field);
1549 $sql = <<<SQL
1550 SELECT 1 as fieldexists
1551 FROM sysibm.syscolumns sc
1552 WHERE sc.name='$ecol' AND sc.tbname='$etable' AND sc.tbcreator='$eschema'
1553 SQL;
1554 $res = $this->query( $sql, $fname );
1555 $count = $res ? $this->numRows($res) : 0;
1556 if ($res)
1557 $this->freeResult( $res );
1558 return $count;
1559 }
1560
1561 /**
1562 * Returns information about an index
1563 * If errors are explicitly ignored, returns NULL on failure
1564 * @param $table String: table name
1565 * @param $index String: index name
1566 * @param $fname String: function name for logging and profiling
1567 * @return Object query row in object form
1568 */
1569 public function indexInfo( $table, $index, $fname = 'DatabaseIbm_db2::indexExists' ) {
1570 $table = $this->tableName( $table );
1571 $sql = <<<SQL
1572 SELECT name as indexname
1573 FROM sysibm.sysindexes si
1574 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1575 SQL;
1576 $res = $this->query( $sql, $fname );
1577 if ( !$res ) {
1578 return null;
1579 }
1580 $row = $this->fetchObject( $res );
1581 if ($row != null) return $row;
1582 else return false;
1583 }
1584
1585 /**
1586 * Returns an information object on a table column
1587 * @param $table String: table name
1588 * @param $field String: column name
1589 * @return IBM_DB2Field
1590 */
1591 public function fieldInfo( $table, $field ) {
1592 return IBM_DB2Field::fromText($this, $table, $field);
1593 }
1594
1595 /**
1596 * db2_field_type() wrapper
1597 * @param $res Object: result of executed statement
1598 * @param $index Mixed: number or name of the column
1599 * @return String column type
1600 */
1601 public function fieldType( $res, $index ) {
1602 if ( $res instanceof ResultWrapper ) {
1603 $res = $res->result;
1604 }
1605 return db2_field_type( $res, $index );
1606 }
1607
1608 /**
1609 * Verifies that an index was created as unique
1610 * @param $table String: table name
1611 * @param $index String: index name
1612 * @param $fname function name for profiling
1613 * @return Bool
1614 */
1615 public function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
1616 $table = $this->tableName( $table );
1617 $sql = <<<SQL
1618 SELECT si.name as indexname
1619 FROM sysibm.sysindexes si
1620 WHERE si.name='$index' AND si.tbname='$table' AND sc.tbcreator='$this->mSchema'
1621 AND si.uniquerule IN ('U', 'P')
1622 SQL;
1623 $res = $this->query( $sql, $fname );
1624 if ( !$res ) {
1625 return null;
1626 }
1627 if ($this->fetchObject( $res )) {
1628 return true;
1629 }
1630 return false;
1631
1632 }
1633
1634 /**
1635 * Returns the size of a text field, or -1 for "unlimited"
1636 * @param $table String: table name
1637 * @param $field String: column name
1638 * @return Integer: length or -1 for unlimited
1639 */
1640 public function textFieldSize( $table, $field ) {
1641 $table = $this->tableName( $table );
1642 $sql = <<<SQL
1643 SELECT length as size
1644 FROM sysibm.syscolumns sc
1645 WHERE sc.name='$field' AND sc.tbname='$table' AND sc.tbcreator='$this->mSchema'
1646 SQL;
1647 $res = $this->query($sql);
1648 $row = $this->fetchObject($res);
1649 $size = $row->size;
1650 $this->freeResult( $res );
1651 return $size;
1652 }
1653
1654 /**
1655 * DELETE where the condition is a join
1656 * @param $delTable String: deleting from this table
1657 * @param $joinTable String: using data from this table
1658 * @param $delVar String: variable in deleteable table
1659 * @param $joinVar String: variable in data table
1660 * @param $conds Array: conditionals for join table
1661 * @param $fname String: function name for profiling
1662 */
1663 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseIbm_db2::deleteJoin" ) {
1664 if ( !$conds ) {
1665 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1666 }
1667
1668 $delTable = $this->tableName( $delTable );
1669 $joinTable = $this->tableName( $joinTable );
1670 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1671 if ( $conds != '*' ) {
1672 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1673 }
1674 $sql .= ')';
1675
1676 $this->query( $sql, $fname );
1677 }
1678
1679 /**
1680 * Description is left as an exercise for the reader
1681 * @param $b Mixed: data to be encoded
1682 * @return IBM_DB2Blob
1683 */
1684 public function encodeBlob($b) {
1685 return new IBM_DB2Blob($b);
1686 }
1687
1688 /**
1689 * Description is left as an exercise for the reader
1690 * @param $b IBM_DB2Blob: data to be decoded
1691 * @return mixed
1692 */
1693 public function decodeBlob($b) {
1694 return $b->getData();
1695 }
1696
1697 /**
1698 * Convert into a list of string being concatenated
1699 * @param $stringList Array: strings that need to be joined together by the SQL engine
1700 * @return String: joined by the concatenation operator
1701 */
1702 public function buildConcat( $stringList ) {
1703 // || is equivalent to CONCAT
1704 // Sample query: VALUES 'foo' CONCAT 'bar' CONCAT 'baz'
1705 return implode( ' || ', $stringList );
1706 }
1707
1708 /**
1709 * Generates the SQL required to convert a DB2 timestamp into a Unix epoch
1710 * @param $column String: name of timestamp column
1711 * @return String: SQL code
1712 */
1713 public function extractUnixEpoch( $column ) {
1714 // TODO
1715 // see SpecialAncientpages
1716 }
1717
1718 ######################################
1719 # Prepared statements
1720 ######################################
1721
1722 /**
1723 * Intended to be compatible with the PEAR::DB wrapper functions.
1724 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1725 *
1726 * ? = scalar value, quoted as necessary
1727 * ! = raw SQL bit (a function for instance)
1728 * & = filename; reads the file and inserts as a blob
1729 * (we don't use this though...)
1730 * @param $sql String: SQL statement with appropriate markers
1731 * @param $func String: Name of the function, for profiling
1732 * @return resource a prepared DB2 SQL statement
1733 */
1734 public function prepare( $sql, $func = 'DB2::prepare' ) {
1735 $stmt = db2_prepare($this->mConn, $sql, $this->mStmtOptions);
1736 return $stmt;
1737 }
1738
1739 /**
1740 * Frees resources associated with a prepared statement
1741 * @return Boolean success or failure
1742 */
1743 public function freePrepared( $prepared ) {
1744 return db2_free_stmt($prepared);
1745 }
1746
1747 /**
1748 * Execute a prepared query with the various arguments
1749 * @param $prepared String: the prepared sql
1750 * @param $args Mixed: either an array here, or put scalars as varargs
1751 * @return Resource: results object
1752 */
1753 public function execute( $prepared, $args = null ) {
1754 if( !is_array( $args ) ) {
1755 # Pull the var args
1756 $args = func_get_args();
1757 array_shift( $args );
1758 }
1759 $res = db2_execute($prepared, $args);
1760 return $res;
1761 }
1762
1763 /**
1764 * Prepare & execute an SQL statement, quoting and inserting arguments
1765 * in the appropriate places.
1766 * @param $query String
1767 * @param $args ...
1768 */
1769 public function safeQuery( $query, $args = null ) {
1770 // copied verbatim from Database.php
1771 $prepared = $this->prepare( $query, 'DB2::safeQuery' );
1772 if( !is_array( $args ) ) {
1773 # Pull the var args
1774 $args = func_get_args();
1775 array_shift( $args );
1776 }
1777 $retval = $this->execute( $prepared, $args );
1778 $this->freePrepared( $prepared );
1779 return $retval;
1780 }
1781
1782 /**
1783 * For faking prepared SQL statements on DBs that don't support
1784 * it directly.
1785 * @param $preparedQuery String: a 'preparable' SQL statement
1786 * @param $args Array of arguments to fill it with
1787 * @return String: executable statement
1788 */
1789 public function fillPrepared( $preparedQuery, $args ) {
1790 reset( $args );
1791 $this->preparedArgs =& $args;
1792
1793 foreach ($args as $i => $arg) {
1794 db2_bind_param($preparedQuery, $i+1, $args[$i]);
1795 }
1796
1797 return $preparedQuery;
1798 }
1799
1800 /**
1801 * Switches module between regular and install modes
1802 */
1803 public function setMode($mode) {
1804 $old = $this->mMode;
1805 $this->mMode = $mode;
1806 return $old;
1807 }
1808
1809 /**
1810 * Bitwise negation of a column or value in SQL
1811 * Same as (~field) in C
1812 * @param $field String
1813 * @return String
1814 */
1815 function bitNot($field) {
1816 //expecting bit-fields smaller than 4bytes
1817 return 'BITNOT('.$bitField.')';
1818 }
1819
1820 /**
1821 * Bitwise AND of two columns or values in SQL
1822 * Same as (fieldLeft & fieldRight) in C
1823 * @param $fieldLeft String
1824 * @param $fieldRight String
1825 * @return String
1826 */
1827 function bitAnd($fieldLeft, $fieldRight) {
1828 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1829 }
1830
1831 /**
1832 * Bitwise OR of two columns or values in SQL
1833 * Same as (fieldLeft | fieldRight) in C
1834 * @param $fieldLeft String
1835 * @param $fieldRight String
1836 * @return String
1837 */
1838 function bitOr($fieldLeft, $fieldRight) {
1839 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1840 }
1841 }