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