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