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