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