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