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