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