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