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