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