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