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