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