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