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