trim trailing whitespace
[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( sprintf( $q,
41 $db->addQuotes( $wgDBmwschema ),
42 $db->addQuotes( $table ),
43 $db->addQuotes( $field )) );
44 $row = $db->fetchObject( $res );
45 if ( !$row )
46 return null;
47 $n = new IBM_DB2Field;
48 $n->type = $row->typname;
49 $n->nullable = ( $row->attnotnull == 'N' );
50 $n->name = $field;
51 $n->tablename = $table;
52 $n->max_length = $row->attlen;
53 return $n;
54 }
55 /**
56 * Get column name
57 * @return string column name
58 */
59 function name() { return $this->name; }
60 /**
61 * Get table name
62 * @return string table name
63 */
64 function tableName() { return $this->tablename; }
65 /**
66 * Get column type
67 * @return string column type
68 */
69 function type() { return $this->type; }
70 /**
71 * Can column be null?
72 * @return bool true or false
73 */
74 function nullable() { return $this->nullable; }
75 /**
76 * How much can you fit in the column per row?
77 * @return int length
78 */
79 function maxLength() { return $this->max_length; }
80 }
81
82 /**
83 * Wrapper around binary large objects
84 * @ingroup Database
85 */
86 class IBM_DB2Blob {
87 private $mData;
88
89 public function __construct( $data ) {
90 $this->mData = $data;
91 }
92
93 public function getData() {
94 return $this->mData;
95 }
96
97 public function __toString()
98 {
99 return $this->mData;
100 }
101 }
102
103 /**
104 * Primary database interface
105 * @ingroup Database
106 */
107 class DatabaseIbm_db2 extends DatabaseBase {
108 /*
109 * Inherited members
110 protected $mLastQuery = '';
111 protected $mPHPError = false;
112
113 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
114 protected $mOut, $mOpened = false;
115
116 protected $mFailFunction;
117 protected $mTablePrefix;
118 protected $mFlags;
119 protected $mTrxLevel = 0;
120 protected $mErrorCount = 0;
121 protected $mLBInfo = array();
122 protected $mFakeSlaveLag = null, $mFakeMaster = false;
123 *
124 */
125
126 /** Database server port */
127 protected $mPort = null;
128 /** Schema for tables, stored procedures, triggers */
129 protected $mSchema = null;
130 /** Whether the schema has been applied in this session */
131 protected $mSchemaSet = false;
132 /** Result of last query */
133 protected $mLastResult = null;
134 /** Number of rows affected by last INSERT/UPDATE/DELETE */
135 protected $mAffectedRows = null;
136 /** Number of rows returned by last SELECT */
137 protected $mNumRows = null;
138
139 /** Connection config options - see constructor */
140 public $mConnOptions = array();
141 /** Statement config options -- see constructor */
142 public $mStmtOptions = array();
143
144 /** Default schema */
145 const USE_GLOBAL = "mediawiki";
146
147 /** Option that applies to nothing */
148 const NONE_OPTION = 0x00;
149 /** Option that applies to connection objects */
150 const CONN_OPTION = 0x01;
151 /** Option that applies to statement objects */
152 const STMT_OPTION = 0x02;
153
154 /** Regular operation mode -- minimal debug messages */
155 const REGULAR_MODE = 'regular';
156 /** Installation mode -- lots of debug messages */
157 const INSTALL_MODE = 'install';
158
159 /** Controls the level of debug message output */
160 protected $mMode = self::REGULAR_MODE;
161
162 /** Last sequence value used for a primary key */
163 protected $mInsertId = null;
164
165 ######################################
166 # Getters and Setters
167 ######################################
168
169 /**
170 * Returns true if this database supports (and uses) cascading deletes
171 */
172 function cascadingDeletes() {
173 return true;
174 }
175
176 /**
177 * Returns true if this database supports (and uses) triggers (e.g. on the
178 * page table)
179 */
180 function cleanupTriggers() {
181 return true;
182 }
183
184 /**
185 * Returns true if this database is strict about what can be put into an
186 * IP field.
187 * Specifically, it uses a NULL value instead of an empty string.
188 */
189 function strictIPs() {
190 return true;
191 }
192
193 /**
194 * Returns true if this database uses timestamps rather than integers
195 */
196 function realTimestamps() {
197 return true;
198 }
199
200 /**
201 * Returns true if this database does an implicit sort when doing GROUP BY
202 */
203 function implicitGroupby() {
204 return false;
205 }
206
207 /**
208 * Returns true if this database does an implicit order by when the column
209 * has an index
210 * For example: SELECT page_title FROM page LIMIT 1
211 */
212 function implicitOrderby() {
213 return false;
214 }
215
216 /**
217 * Returns true if this database can do a native search on IP columns
218 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
219 */
220 function searchableIPs() {
221 return true;
222 }
223
224 /**
225 * Returns true if this database can use functional indexes
226 */
227 function functionalIndexes() {
228 return true;
229 }
230
231 /**
232 * Returns a unique string representing the wiki on the server
233 */
234 function getWikiID() {
235 if( $this->mSchema ) {
236 return "{$this->mDBname}-{$this->mSchema}";
237 } else {
238 return $this->mDBname;
239 }
240 }
241
242 function getType() {
243 return 'ibm_db2';
244 }
245
246 ######################################
247 # Setup
248 ######################################
249
250
251 /**
252 *
253 * @param $server String: hostname of database server
254 * @param $user String: username
255 * @param $password String: password
256 * @param $dbName String: database name on the server
257 * @param $failFunction Callback (optional)
258 * @param $flags Integer: database behaviour flags (optional, unused)
259 * @param $schema String
260 */
261 public function DatabaseIbm_db2( $server = false, $user = false,
262 $password = false,
263 $dbName = false, $failFunction = false, $flags = 0,
264 $schema = self::USE_GLOBAL )
265 {
266
267 global $wgOut, $wgDBmwschema;
268 # Can't get a reference if it hasn't been set yet
269 if ( !isset( $wgOut ) ) {
270 $wgOut = null;
271 }
272 $this->mOut =& $wgOut;
273 $this->mFailFunction = $failFunction;
274 $this->mFlags = DBO_TRX | $flags;
275
276 if ( $schema == self::USE_GLOBAL ) {
277 $this->mSchema = $wgDBmwschema;
278 }
279 else {
280 $this->mSchema = $schema;
281 }
282
283 // configure the connection and statement objects
284 $this->setDB2Option( 'db2_attr_case', 'DB2_CASE_LOWER',
285 self::CONN_OPTION | self::STMT_OPTION );
286 $this->setDB2Option( 'deferred_prepare', 'DB2_DEFERRED_PREPARE_ON',
287 self::STMT_OPTION );
288 $this->setDB2Option( 'rowcount', 'DB2_ROWCOUNT_PREFETCH_ON',
289 self::STMT_OPTION );
290
291 $this->open( $server, $user, $password, $dbName );
292 }
293
294 /**
295 * Enables options only if the ibm_db2 extension version supports them
296 * @param $name String: name of the option in the options array
297 * @param $const String: name of the constant holding the right option value
298 * @param $type Integer: whether this is a Connection or Statement otion
299 */
300 private function setDB2Option( $name, $const, $type ) {
301 if ( defined( $const )) {
302 if ( $type & self::CONN_OPTION ) {
303 $this->mConnOptions[$name] = constant( $const );
304 }
305 if ( $type & self::STMT_OPTION ) {
306 $this->mStmtOptions[$name] = constant( $const );
307 }
308 }
309 else {
310 $this->installPrint(
311 "$const is not defined. ibm_db2 version is likely too low." );
312 }
313 }
314
315 /**
316 * Outputs debug information in the appropriate place
317 * @param $string String: the relevant debug message
318 */
319 private function installPrint( $string ) {
320 wfDebug( "$string\n" );
321 if ( $this->mMode == self::INSTALL_MODE ) {
322 print "<li><pre>$string</pre></li>";
323 flush();
324 }
325 }
326
327 /**
328 * Opens a database connection and returns it
329 * Closes any existing connection
330 * @return a fresh connection
331 * @param $server String: hostname
332 * @param $user String
333 * @param $password String
334 * @param $dbName String: database name
335 */
336 public function open( $server, $user, $password, $dbName )
337 {
338 // Load the port number
339 global $wgDBport;
340 wfProfileIn( __METHOD__ );
341
342 // Load IBM DB2 driver if missing
343 wfDl( 'ibm_db2' );
344
345 // Test for IBM DB2 support, to avoid suppressed fatal error
346 if ( !function_exists( 'db2_connect' ) ) {
347 $error = <<<ERROR
348 DB2 functions missing, have you enabled the ibm_db2 extension for PHP?
349
350 ERROR;
351 $this->installPrint( $error );
352 $this->reportConnectionError( $error );
353 }
354
355 if ( strlen( $user ) < 1) {
356 return null;
357 }
358
359 // Close existing connection
360 $this->close();
361 // Cache conn info
362 $this->mServer = $server;
363 $this->mPort = $port = $wgDBport;
364 $this->mUser = $user;
365 $this->mPassword = $password;
366 $this->mDBname = $dbName;
367
368 $this->openUncataloged( $dbName, $user, $password, $server, $port );
369
370 // Apply connection config
371 db2_set_option( $this->mConn, $this->mConnOptions, 1 );
372 // Some MediaWiki code is still transaction-less (?).
373 // The strategy is to keep AutoCommit on for that code
374 // but switch it off whenever a transaction is begun.
375 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
376
377 if ( !$this->mConn ) {
378 $this->installPrint( "DB connection error\n" );
379 $this->installPrint(
380 "Server: $server, Database: $dbName, User: $user, Password: "
381 . substr( $password, 0, 3 ) . "...\n" );
382 $this->installPrint( $this->lastError() . "\n" );
383 return null;
384 }
385
386 $this->mOpened = true;
387 $this->applySchema();
388
389 wfProfileOut( __METHOD__ );
390 return $this->mConn;
391 }
392
393 /**
394 * Opens a cataloged database connection, sets mConn
395 */
396 protected function openCataloged( $dbName, $user, $password )
397 {
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 }
430 else {
431 return true;
432 }
433 }
434
435 /**
436 * Returns a fresh instance of this class
437 *
438 * @param $server String: hostname of database server
439 * @param $user String: username
440 * @param $password String
441 * @param $dbName String: database name on the server
442 * @param $failFunction Callback (optional)
443 * @param $flags Integer: database behaviour flags (optional, unused)
444 * @return DatabaseIbm_db2 object
445 */
446 static function newFromParams( $server, $user, $password, $dbName,
447 $failFunction = false, $flags = 0 )
448 {
449 return new DatabaseIbm_db2( $server, $user, $password, $dbName,
450 $failFunction, $flags );
451 }
452
453 /**
454 * Retrieves the most current database error
455 * Forces a database rollback
456 */
457 public function lastError() {
458 $connerr = db2_conn_errormsg();
459 if ( $connerr ) {
460 //$this->rollback();
461 return $connerr;
462 }
463 $stmterr = db2_stmt_errormsg();
464 if ( $stmterr ) {
465 //$this->rollback();
466 return $stmterr;
467 }
468
469 return false;
470 }
471
472 /**
473 * Get the last error number
474 * Return 0 if no error
475 * @return integer
476 */
477 public function lastErrno() {
478 $connerr = db2_conn_error();
479 if ( $connerr ) {
480 return $connerr;
481 }
482 $stmterr = db2_stmt_error();
483 if ( $stmterr ) {
484 return $stmterr;
485 }
486 return 0;
487 }
488
489 /**
490 * Is a database connection open?
491 * @return
492 */
493 public function isOpen() { return $this->mOpened; }
494
495 /**
496 * The DBMS-dependent part of query()
497 * @param $sql String: SQL query.
498 * @return object Result object for fetch functions or false on failure
499 * @access private
500 */
501 /*private*/
502 public function doQuery( $sql ) {
503 $this->applySchema();
504
505 $ret = db2_exec( $this->mConn, $sql, $this->mStmtOptions );
506 if( $ret == FALSE ) {
507 $error = db2_stmt_errormsg();
508 $this->installPrint( "<pre>$sql</pre>" );
509 $this->installPrint( $error );
510 throw new DBUnexpectedError( $this, 'SQL error: '
511 . htmlspecialchars( $error ) );
512 }
513 $this->mLastResult = $ret;
514 $this->mAffectedRows = null; // Not calculated until asked for
515 return $ret;
516 }
517
518 /**
519 * @return string Version information from the database
520 */
521 public function getServerVersion() {
522 $info = db2_server_info( $this->mConn );
523 return $info->DBMS_VER;
524 }
525
526 /**
527 * Queries whether a given table exists
528 * @return boolean
529 */
530 public function tableExists( $table ) {
531 $schema = $this->mSchema;
532 $sql = <<< EOF
533 SELECT COUNT( * ) FROM SYSIBM.SYSTABLES ST
534 WHERE ST.NAME = '$table' AND ST.CREATOR = '$schema'
535 EOF;
536 $res = $this->query( $sql );
537 if ( !$res ) return false;
538
539 // If the table exists, there should be one of it
540 @$row = $this->fetchRow( $res );
541 $count = $row[0];
542 if ( $count == '1' or $count == 1 ) {
543 return true;
544 }
545
546 return false;
547 }
548
549 /**
550 * Fetch the next row from the given result object, in object form.
551 * Fields can be retrieved with $row->fieldname, with fields acting like
552 * member variables.
553 *
554 * @param $res SQL result object as returned from Database::query(), etc.
555 * @return DB2 row object
556 * @throws DBUnexpectedError Thrown if the database returns an error
557 */
558 public function fetchObject( $res ) {
559 if ( $res instanceof ResultWrapper ) {
560 $res = $res->result;
561 }
562 @$row = db2_fetch_object( $res );
563 if( $this->lastErrno() ) {
564 throw new DBUnexpectedError( $this, 'Error in fetchObject(): '
565 . htmlspecialchars( $this->lastError() ) );
566 }
567 return $row;
568 }
569
570 /**
571 * Fetch the next row from the given result object, in associative array
572 * form. Fields are retrieved with $row['fieldname'].
573 *
574 * @param $res SQL result object as returned from Database::query(), etc.
575 * @return DB2 row object
576 * @throws DBUnexpectedError Thrown if the database returns an error
577 */
578 public function fetchRow( $res ) {
579 if ( $res instanceof ResultWrapper ) {
580 $res = $res->result;
581 }
582 @$row = db2_fetch_array( $res );
583 if ( $this->lastErrno() ) {
584 throw new DBUnexpectedError( $this, 'Error in fetchRow(): '
585 . htmlspecialchars( $this->lastError() ) );
586 }
587 return $row;
588 }
589
590 /**
591 * Override if introduced to base Database class
592 */
593 public function initial_setup() {
594 // do nothing
595 }
596
597 /**
598 * Create tables, stored procedures, and so on
599 */
600 public function setup_database() {
601 try {
602 // TODO: switch to root login if available
603
604 // Switch into the correct namespace
605 $this->applySchema();
606 $this->begin();
607
608 $res = $this->sourceFile( "../maintenance/ibm_db2/tables.sql" );
609 if ( $res !== true ) {
610 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
611 } else {
612 print " done</li>";
613 }
614 $res = $this->sourceFile( "../maintenance/ibm_db2/foreignkeys.sql" );
615 if ( $res !== true ) {
616 print " <b>FAILED</b>: " . htmlspecialchars( $res ) . "</li>";
617 } else {
618 print "<li>Foreign keys done</li>";
619 }
620 $res = null;
621
622 // TODO: populate interwiki links
623
624 if ( $this->lastError() ) {
625 $this->installPrint(
626 "Errors encountered during table creation -- rolled back" );
627 $this->installPrint( "Please install again" );
628 $this->rollback();
629 }
630 else {
631 $this->commit();
632 }
633 }
634 catch ( MWException $mwe )
635 {
636 print "<br><pre>$mwe</pre><br>";
637 }
638 }
639
640 /**
641 * Escapes strings
642 * Doesn't escape numbers
643 * @param $s String: string to escape
644 * @return escaped string
645 */
646 public function addQuotes( $s ) {
647 //$this->installPrint( "DB2::addQuotes( $s )\n" );
648 if ( is_null( $s ) ) {
649 return "NULL";
650 } else if ( $s instanceof Blob ) {
651 return "'" . $s->fetch( $s ) . "'";
652 } else if ( $s instanceof IBM_DB2Blob ) {
653 return "'" . $this->decodeBlob( $s ) . "'";
654 }
655 $s = $this->strencode( $s );
656 if ( is_numeric( $s ) ) {
657 return $s;
658 }
659 else {
660 return "'$s'";
661 }
662 }
663
664 /**
665 * Verifies that a DB2 column/field type is numeric
666 * @return bool true if numeric
667 * @param $type String: DB2 column type
668 */
669 public function is_numeric_type( $type ) {
670 switch ( strtoupper( $type )) {
671 case 'SMALLINT':
672 case 'INTEGER':
673 case 'INT':
674 case 'BIGINT':
675 case 'DECIMAL':
676 case 'REAL':
677 case 'DOUBLE':
678 case 'DECFLOAT':
679 return true;
680 }
681 return false;
682 }
683
684 /**
685 * Alias for addQuotes()
686 * @param $s String: string to escape
687 * @return escaped string
688 */
689 public function strencode( $s ) {
690 // Bloody useless function
691 // Prepends backslashes to \x00, \n, \r, \, ', " and \x1a.
692 // But also necessary
693 $s = db2_escape_string( $s );
694 // Wide characters are evil -- some of them look like '
695 $s = utf8_encode( $s );
696 // Fix its stupidity
697 $from = array( "\\\\", "\\'", '\\n', '\\t', '\\"', '\\r' );
698 $to = array( "\\", "''", "\n", "\t", '"', "\r" );
699 $s = str_replace( $from, $to, $s ); // DB2 expects '', not \' escaping
700 return $s;
701 }
702
703 /**
704 * Switch into the database schema
705 */
706 protected function applySchema() {
707 if ( !( $this->mSchemaSet ) ) {
708 $this->mSchemaSet = true;
709 $this->begin();
710 $this->doQuery( "SET SCHEMA = $this->mSchema" );
711 $this->commit();
712 }
713 }
714
715 /**
716 * Start a transaction (mandatory)
717 */
718 public function begin( $fname = 'DatabaseIbm_db2::begin' ) {
719 // BEGIN is implicit for DB2
720 // However, it requires that AutoCommit be off.
721
722 // Some MediaWiki code is still transaction-less (?).
723 // The strategy is to keep AutoCommit on for that code
724 // but switch it off whenever a transaction is begun.
725 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_OFF );
726
727 $this->mTrxLevel = 1;
728 }
729
730 /**
731 * End a transaction
732 * Must have a preceding begin()
733 */
734 public function commit( $fname = 'DatabaseIbm_db2::commit' ) {
735 db2_commit( $this->mConn );
736
737 // Some MediaWiki code is still transaction-less (?).
738 // The strategy is to keep AutoCommit on for that code
739 // but switch it off whenever a transaction is begun.
740 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
741
742 $this->mTrxLevel = 0;
743 }
744
745 /**
746 * Cancel a transaction
747 */
748 public function rollback( $fname = 'DatabaseIbm_db2::rollback' ) {
749 db2_rollback( $this->mConn );
750 // turn auto-commit back on
751 // not sure if this is appropriate
752 db2_autocommit( $this->mConn, DB2_AUTOCOMMIT_ON );
753 $this->mTrxLevel = 0;
754 }
755
756 /**
757 * Makes an encoded list of strings from an array
758 * $mode:
759 * LIST_COMMA - comma separated, no field names
760 * LIST_AND - ANDed WHERE clause (without the WHERE)
761 * LIST_OR - ORed WHERE clause (without the WHERE)
762 * LIST_SET - comma separated with field names, like a SET clause
763 * LIST_NAMES - comma separated field names
764 * LIST_SET_PREPARED - like LIST_SET, except with ? tokens as values
765 */
766 function makeList( $a, $mode = LIST_COMMA ) {
767 if ( !is_array( $a ) ) {
768 throw new DBUnexpectedError( $this,
769 'DatabaseBase::makeList called with incorrect parameters' );
770 }
771
772 // if this is for a prepared UPDATE statement
773 // (this should be promoted to the parent class
774 // once other databases use prepared statements)
775 if ( $mode == LIST_SET_PREPARED ) {
776 $first = true;
777 $list = '';
778 foreach ( $a as $field => $value ) {
779 if ( !$first ) {
780 $list .= ", $field = ?";
781 }
782 else {
783 $list .= "$field = ?";
784 $first = false;
785 }
786 }
787 $list .= '';
788
789 return $list;
790 }
791
792 // otherwise, call the usual function
793 return parent::makeList( $a, $mode );
794 }
795
796 /**
797 * Construct a LIMIT query with optional offset
798 * This is used for query pages
799 * @param $sql string SQL query we will append the limit too
800 * @param $limit integer the SQL limit
801 * @param $offset integer the SQL offset (default false)
802 */
803 public function limitResult( $sql, $limit, $offset=false ) {
804 if( !is_numeric( $limit ) ) {
805 throw new DBUnexpectedError( $this,
806 "Invalid non-numeric limit passed to limitResult()\n" );
807 }
808 if( $offset ) {
809 if ( stripos( $sql, 'where' ) === false ) {
810 return "$sql AND ( ROWNUM BETWEEN $offset AND $offset+$limit )";
811 }
812 else {
813 return "$sql WHERE ( ROWNUM BETWEEN $offset AND $offset+$limit )";
814 }
815 }
816 return "$sql FETCH FIRST $limit ROWS ONLY ";
817 }
818
819 /**
820 * Handle reserved keyword replacement in table names
821 * @return
822 * @param $name Object
823 */
824 public function tableName( $name ) {
825 // we want maximum compatibility with MySQL schema
826 return $name;
827 }
828
829 /**
830 * Generates a timestamp in an insertable format
831 * @return string timestamp value
832 * @param $ts timestamp
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 * @param $table String: sanitized table name
871 * @param $primaryKey Mixed: string name of the primary key
872 * @param $stmt Resource: prepared statement resource
873 * of the SELECT primary_key FROM FINAL TABLE ( INSERT ... ) form
874 */
875 private function calcInsertId( $table, $primaryKey, $stmt ) {
876 if ( $primaryKey ) {
877 $this->mInsertId = db2_last_insert_id( $this->mConn );
878 }
879 }
880
881 /**
882 * INSERT wrapper, inserts an array into a table
883 *
884 * $args may be a single associative array, or an array of arrays
885 * with numeric keys, for multi-row insert
886 *
887 * @param $table String: Name of the table to insert to.
888 * @param $args Array: Items to insert into the table.
889 * @param $fname String: Name of the function, for profiling
890 * @param $options String or Array. Valid options: IGNORE
891 *
892 * @return bool Success of insert operation. IGNORE always returns true.
893 */
894 public function insert( $table, $args, $fname = 'DatabaseIbm_db2::insert',
895 $options = array() )
896 {
897 if ( !count( $args ) ) {
898 return true;
899 }
900 // get database-specific table name (not used)
901 $table = $this->tableName( $table );
902 // format options as an array
903 $options = IBM_DB2Helper::makeArray( $options );
904 // format args as an array of arrays
905 if ( !( isset( $args[0] ) && is_array( $args[0] ) ) ) {
906 $args = array( $args );
907 }
908
909 // prevent insertion of NULL into primary key columns
910 list( $args, $primaryKeys ) = $this->removeNullPrimaryKeys( $table, $args );
911 // if there's only one primary key
912 // we'll be able to read its value after insertion
913 $primaryKey = false;
914 if ( count( $primaryKeys ) == 1 ) {
915 $primaryKey = $primaryKeys[0];
916 }
917
918 // get column names
919 $keys = array_keys( $args[0] );
920 $key_count = count( $keys );
921
922 // If IGNORE is set, we use savepoints to emulate mysql's behavior
923 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
924
925 // assume success
926 $res = true;
927 // If we are not in a transaction, we need to be for savepoint trickery
928 if ( ! $this->mTrxLevel ) {
929 $this->begin();
930 }
931
932 $sql = "INSERT INTO $table ( " . implode( ',', $keys ) . ' ) VALUES ';
933 if ( $key_count == 1 ) {
934 $sql .= '( ? )';
935 } else {
936 $sql .= '( ?' . str_repeat( ',?', $key_count-1 ) . ' )';
937 }
938 //$this->installPrint( "Preparing the following SQL:" );
939 //$this->installPrint( "$sql" );
940 //$this->installPrint( print_r( $args, true ));
941 $stmt = $this->prepare( $sql );
942
943 // start a transaction/enter transaction mode
944 $this->begin();
945
946 if ( !$ignore ) {
947 //$first = true;
948 foreach ( $args as $row ) {
949 //$this->installPrint( "Inserting " . print_r( $row, true ));
950 // insert each row into the database
951 $res = $res & $this->execute( $stmt, $row );
952 if ( !$res ) {
953 $this->installPrint( "Last error:" );
954 $this->installPrint( $this->lastError() );
955 }
956 // get the last inserted value into a generated column
957 $this->calcInsertId( $table, $primaryKey, $stmt );
958 }
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
974 $this->execute( $stmt, $row );
975
976 if ( !$res2 ) {
977 $this->installPrint( "Last error:" );
978 $this->installPrint( $this->lastError() );
979 }
980 // get the last inserted value into a generated column
981 $this->calcInsertId( $table, $primaryKey, $stmt );
982
983 $errNum = $this->lastErrno();
984 if ( $errNum ) {
985 db2_exec( $this->mConn, "ROLLBACK TO SAVEPOINT $ignore",
986 $this->mStmtOptions );
987 }
988 else {
989 db2_exec( $this->mConn, "RELEASE SAVEPOINT $ignore",
990 $this->mStmtOptions );
991 $numrowsinserted++;
992 }
993 }
994
995 $olde = error_reporting( $olde );
996 // Set the affected row count for the whole operation
997 $this->mAffectedRows = $numrowsinserted;
998 }
999 // commit either way
1000 $this->commit();
1001 $this->freePrepared( $stmt );
1002
1003 return $res;
1004 }
1005
1006 /**
1007 * Given a table name and a hash of columns with values
1008 * Removes primary key columns from the hash where the value is NULL
1009 *
1010 * @param $table String: name of the table
1011 * @param $args Array of hashes of column names with values
1012 * @return Array: tuple( filtered array of columns, array of primary keys )
1013 */
1014 private function removeNullPrimaryKeys( $table, $args ) {
1015 $schema = $this->mSchema;
1016 // find out the primary keys
1017 $keyres = db2_primary_keys( $this->mConn, null, strtoupper( $schema ),
1018 strtoupper( $table ));
1019 $keys = array();
1020 for (
1021 $row = $this->fetchObject( $keyres );
1022 $row != null;
1023 $row = $this->fetchObject( $keyres ))
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 return db2_num_rows( $this->mLastResult );
1104 }
1105
1106 /**
1107 * Simulates REPLACE with a DELETE followed by INSERT
1108 * @param $table Object
1109 * @param $uniqueIndexes Array consisting of indexes and arrays of indexes
1110 * @param $rows Array: rows to insert
1111 * @param $fname String: name of the function for profiling
1112 * @return nothing
1113 */
1114 function replace( $table, $uniqueIndexes, $rows,
1115 $fname = 'DatabaseIbm_db2::replace' )
1116 {
1117 $table = $this->tableName( $table );
1118
1119 if ( count( $rows )==0 ) {
1120 return;
1121 }
1122
1123 # Single row case
1124 if ( !is_array( reset( $rows ) ) ) {
1125 $rows = array( $rows );
1126 }
1127
1128 foreach( $rows as $row ) {
1129 # Delete rows which collide
1130 if ( $uniqueIndexes ) {
1131 $sql = "DELETE FROM $table WHERE ";
1132 $first = true;
1133 foreach ( $uniqueIndexes as $index ) {
1134 if ( $first ) {
1135 $first = false;
1136 $sql .= "( ";
1137 } else {
1138 $sql .= ' ) OR ( ';
1139 }
1140 if ( is_array( $index ) ) {
1141 $first2 = true;
1142 foreach ( $index as $col ) {
1143 if ( $first2 ) {
1144 $first2 = false;
1145 } else {
1146 $sql .= ' AND ';
1147 }
1148 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
1149 }
1150 } else {
1151 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
1152 }
1153 }
1154 $sql .= ' )';
1155 $this->query( $sql, $fname );
1156 }
1157
1158 # Now insert the row
1159 $sql = "INSERT INTO $table ( "
1160 . $this->makeList( array_keys( $row ), LIST_NAMES )
1161 .' ) VALUES ( ' . $this->makeList( $row, LIST_COMMA ) . ' )';
1162 $this->query( $sql, $fname );
1163 }
1164 }
1165
1166 /**
1167 * Returns the number of rows in the result set
1168 * Has to be called right after the corresponding select query
1169 * @param $res Object result set
1170 * @return Integer: number of rows
1171 */
1172 public function numRows( $res ) {
1173 if ( $res instanceof ResultWrapper ) {
1174 $res = $res->result;
1175 }
1176 if ( $this->mNumRows ) {
1177 return $this->mNumRows;
1178 }
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
1295 return $res;
1296 }
1297
1298 /**
1299 * Handles ordering, grouping, and having options ('GROUP BY' => colname)
1300 * Has limited support for per-column options (colnum => 'DISTINCT')
1301 *
1302 * @private
1303 *
1304 * @param $options Associative array of options to be turned into
1305 * an SQL query, valid keys are listed in the function.
1306 * @return Array
1307 */
1308 function makeSelectOptions( $options ) {
1309 $preLimitTail = $postLimitTail = '';
1310 $startOpts = '';
1311
1312 $noKeyOptions = array();
1313 foreach ( $options as $key => $option ) {
1314 if ( is_numeric( $key ) ) {
1315 $noKeyOptions[$option] = true;
1316 }
1317 }
1318
1319 if ( isset( $options['GROUP BY'] ) ) {
1320 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1321 }
1322 if ( isset( $options['HAVING'] ) ) {
1323 $preLimitTail .= " HAVING {$options['HAVING']}";
1324 }
1325 if ( isset( $options['ORDER BY'] ) ) {
1326 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1327 }
1328
1329 if ( isset( $noKeyOptions['DISTINCT'] )
1330 || isset( $noKeyOptions['DISTINCTROW'] ) )
1331 {
1332 $startOpts .= 'DISTINCT';
1333 }
1334
1335 return array( $startOpts, '', $preLimitTail, $postLimitTail );
1336 }
1337
1338 /**
1339 * Returns link to IBM DB2 free download
1340 * @return string wikitext of a link to the server software's web site
1341 */
1342 public static function getSoftwareLink() {
1343 return "[http://www.ibm.com/db2/express/ IBM DB2]";
1344 }
1345
1346 /**
1347 * Get search engine class. All subclasses of this
1348 * need to implement this if they wish to use searching.
1349 *
1350 * @return String
1351 */
1352 public function getSearchEngine() {
1353 return "SearchIBM_DB2";
1354 }
1355
1356 /**
1357 * Did the last database access fail because of deadlock?
1358 * @return Boolean
1359 */
1360 public function wasDeadlock() {
1361 // get SQLSTATE
1362 $err = $this->lastErrno();
1363 switch( $err ) {
1364 // This is literal port of the MySQL logic and may be wrong for DB2
1365 case '40001': // sql0911n, Deadlock or timeout, rollback
1366 case '57011': // sql0904n, Resource unavailable, no rollback
1367 case '57033': // sql0913n, Deadlock or timeout, no rollback
1368 $this->installPrint( "In a deadlock because of SQLSTATE $err" );
1369 return true;
1370 }
1371 return false;
1372 }
1373
1374 /**
1375 * Ping the server and try to reconnect if it there is no connection
1376 * The connection may be closed and reopened while this happens
1377 * @return Boolean: whether the connection exists
1378 */
1379 public function ping() {
1380 // db2_ping() doesn't exist
1381 // Emulate
1382 $this->close();
1383 $this->mConn = $this->openUncataloged( $this->mDBName, $this->mUser,
1384 $this->mPassword, $this->mServer, $this->mPort );
1385
1386 return false;
1387 }
1388 ######################################
1389 # Unimplemented and not applicable
1390 ######################################
1391 /**
1392 * Not implemented
1393 * @return string ''
1394 */
1395 public function getStatus( $which="%" ) {
1396 $this->installPrint( 'Not implemented for DB2: getStatus()' );
1397 return '';
1398 }
1399 /**
1400 * Not implemented
1401 * @return string $sql
1402 */
1403 public function limitResultForUpdate( $sql, $num ) {
1404 $this->installPrint( 'Not implemented for DB2: limitResultForUpdate()' );
1405 return $sql;
1406 }
1407
1408 /**
1409 * Only useful with fake prepare like in base Database class
1410 * @return string
1411 */
1412 public function fillPreparedArg( $matches ) {
1413 $this->installPrint( 'Not useful for DB2: fillPreparedArg()' );
1414 return '';
1415 }
1416
1417 ######################################
1418 # Reflection
1419 ######################################
1420
1421 /**
1422 * Returns information about an index
1423 * If errors are explicitly ignored, returns NULL on failure
1424 * @param $table String: table name
1425 * @param $index String: index name
1426 * @param $fname String: function name for logging and profiling
1427 * @return Object query row in object form
1428 */
1429 public function indexInfo( $table, $index,
1430 $fname = 'DatabaseIbm_db2::indexExists' )
1431 {
1432 $table = $this->tableName( $table );
1433 $sql = <<<SQL
1434 SELECT name as indexname
1435 FROM sysibm.sysindexes si
1436 WHERE si.name='$index' AND si.tbname='$table'
1437 AND sc.tbcreator='$this->mSchema'
1438 SQL;
1439 $res = $this->query( $sql, $fname );
1440 if ( !$res ) {
1441 return null;
1442 }
1443 $row = $this->fetchObject( $res );
1444 if ( $row != null ) {
1445 return $row;
1446 }
1447 else return false;
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 }