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