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