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