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