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