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