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