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