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