5ba0d3b5302feedc98f44cbee1207f66e6221127
[lhc/web/wiklou.git] / includes / DatabasePostgres.php
1 <?php
2
3 /**
4 * This is PostgreSQL database abstraction layer.
5 *
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
8 * Database class.
9 *
10 * @package MediaWiki
11 */
12
13 /**
14 * Depends on database
15 */
16 require_once( 'Database.php' );
17
18 class DatabasePostgres extends Database {
19 var $mInsertId = NULL;
20 var $mLastResult = NULL;
21
22 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0 )
24 {
25
26 global $wgOut, $wgDBprefix, $wgCommandLineMode;
27 # Can't get a reference if it hasn't been set yet
28 if ( !isset( $wgOut ) ) {
29 $wgOut = NULL;
30 }
31 $this->mOut =& $wgOut;
32 $this->mFailFunction = $failFunction;
33 $this->mFlags = $flags;
34
35 $this->open( $server, $user, $password, $dbName);
36
37 }
38
39 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
40 $failFunction = false, $flags = 0)
41 {
42 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
43 }
44
45 /**
46 * Usually aborts on failure
47 * If the failFunction is set to a non-zero integer, returns success
48 */
49 function open( $server, $user, $password, $dbName ) {
50 # Test for PostgreSQL support, to avoid suppressed fatal error
51 if ( !function_exists( 'pg_connect' ) ) {
52 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
53 }
54
55 global $wgDBport;
56
57 $this->close();
58 $this->mServer = $server;
59 $port = $wgDBport;
60 $this->mUser = $user;
61 $this->mPassword = $password;
62 $this->mDBname = $dbName;
63
64 $success = false;
65
66 $hstring="";
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
69 }
70 if ($port!=false && $port!="") {
71 $hstring .= "port=$port ";
72 }
73
74 error_reporting( E_ALL );
75
76 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
77
78 if ( $this->mConn == false ) {
79 wfDebug( "DB connection error\n" );
80 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
81 wfDebug( $this->lastError()."\n" );
82 return false;
83 }
84
85 $this->mOpened = true;
86 ## If this is the initial connection, setup the schema stuff
87 if (defined('MEDIAWIKI_INSTALL') and !defined('POSTGRES_SEARCHPATH')) {
88 global $wgDBmwschema, $wgDBts2schema;
89
90 ## Do we have the basic tsearch2 table?
91 print "<li>Checking for tsearch2 ...";
92 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
93 print "FAILED. Make sure tsearch2 is installed. See <a href=";
94 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
95 print " for instructions.</li>\n";
96 dieout("</ul>");
97 }
98 print "OK</li>\n";
99
100 ## Does the schema already exist? Who owns it?
101 $result = $this->schemaExists($wgDBmwschema);
102 if (!$result) {
103 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
104 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
105 if (!$result) {
106 print "FAILED.</li>\n";
107 return false;
108 }
109 print "ok</li>\n";
110 }
111 else if ($result != $user) {
112 print "<li>Schema <b>$wgDBmwschema</b> exists but is not owned by <b>$user</b>. Not ideal.</li>\n";
113 }
114 else {
115 print "<li>Schema <b>$wgDBmwschema</b> exists and is owned by <b>$user ($result)</b>. Excellent.</li>\n";
116 }
117
118 ## Fix up the search paths if needed
119 print "<li>Setting the search path for user <b>$user</b> ...";
120 $path = "$wgDBmwschema";
121 if ($wgDBts2schema !== $wgDBmwschema)
122 $path .= ", $wgDBts2schema";
123 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
124 $path .= ", public";
125 $SQL = "ALTER USER $user SET search_path = $path";
126 $result = pg_query($this->mConn, $SQL);
127 if (!$result) {
128 print "FAILED.</li>\n";
129 return false;
130 }
131 print "ok</li>\n";
132 ## Set for the rest of this session
133 $SQL = "SET search_path = $path";
134 $result = pg_query($this->mConn, $SQL);
135 if (!$result) {
136 print "<li>Failed to set search_path</li>\n";
137 return false;
138 }
139 define( "POSTGRES_SEARCHPATH", $path );
140 }
141
142 return $this->mConn;
143 }
144
145 /**
146 * Closes a database connection, if it is open
147 * Returns success, true if already closed
148 */
149 function close() {
150 $this->mOpened = false;
151 if ( $this->mConn ) {
152 return pg_close( $this->mConn );
153 } else {
154 return true;
155 }
156 }
157
158 function doQuery( $sql ) {
159 return $this->mLastResult=pg_query( $this->mConn , $sql);
160 }
161
162 function queryIgnore( $sql, $fname = '' ) {
163 return $this->query( $sql, $fname, true );
164 }
165
166 function freeResult( $res ) {
167 if ( !@pg_free_result( $res ) ) {
168 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
169 }
170 }
171
172 function fetchObject( $res ) {
173 @$row = pg_fetch_object( $res );
174 # FIXME: HACK HACK HACK HACK debug
175
176 # TODO:
177 # hashar : not sure if the following test really trigger if the object
178 # fetching failled.
179 if( pg_last_error($this->mConn) ) {
180 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
181 }
182 return $row;
183 }
184
185 function fetchRow( $res ) {
186 @$row = pg_fetch_array( $res );
187 if( pg_last_error($this->mConn) ) {
188 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
189 }
190 return $row;
191 }
192
193 function numRows( $res ) {
194 @$n = pg_num_rows( $res );
195 if( pg_last_error($this->mConn) ) {
196 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
197 }
198 return $n;
199 }
200 function numFields( $res ) { return pg_num_fields( $res ); }
201 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
202
203 /**
204 * This must be called after nextSequenceVal
205 */
206 function insertId() {
207 return $this->mInsertId;
208 }
209
210 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
211 function lastError() {
212 if ( $this->mConn ) {
213 return pg_last_error();
214 }
215 else {
216 return "No database connection";
217 }
218 }
219 function lastErrno() { return 1; }
220
221 function affectedRows() {
222 return pg_affected_rows( $this->mLastResult );
223 }
224
225 /**
226 * Returns information about an index
227 * If errors are explicitly ignored, returns NULL on failure
228 */
229 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
230 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
231 $res = $this->query( $sql, $fname );
232 if ( !$res ) {
233 return NULL;
234 }
235
236 while ( $row = $this->fetchObject( $res ) ) {
237 if ( $row->indexname == $index ) {
238 return $row;
239 }
240 }
241 return false;
242 }
243
244 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
245 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
246 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
247 $res = $this->query( $sql, $fname );
248 if ( !$res )
249 return NULL;
250 while ($row = $this->fetchObject( $res ))
251 return true;
252 return false;
253
254 }
255
256 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
257 # PostgreSQL doesn't support options
258 # We have a go at faking one of them
259 # TODO: DELAYED, LOW_PRIORITY
260
261 if ( !is_array($options))
262 $options = array($options);
263
264 if ( in_array( 'IGNORE', $options ) )
265 $oldIgnore = $this->ignoreErrors( true );
266
267 # IGNORE is performed using single-row inserts, ignoring errors in each
268 # FIXME: need some way to distiguish between key collision and other types of error
269 $oldIgnore = $this->ignoreErrors( true );
270 if ( !is_array( reset( $a ) ) ) {
271 $a = array( $a );
272 }
273 foreach ( $a as $row ) {
274 parent::insert( $table, $row, $fname, array() );
275 }
276 $this->ignoreErrors( $oldIgnore );
277 $retVal = true;
278
279 if ( in_array( 'IGNORE', $options ) )
280 $this->ignoreErrors( $oldIgnore );
281
282 return $retVal;
283 }
284
285 function tableName( $name ) {
286 # Replace backticks into double quotes
287 $name = strtr($name,'`','"');
288
289 # Now quote PG reserved keywords
290 switch( $name ) {
291 case 'user':
292 case 'old':
293 case 'group':
294 return '"' . $name . '"';
295
296 default:
297 return $name;
298 }
299 }
300
301 function strencode( $s ) {
302 return pg_escape_string( $s );
303 }
304
305 /**
306 * Return the next in a sequence, save the value for retrieval via insertId()
307 */
308 function nextSequenceValue( $seqName ) {
309 $value = $this->selectField(''," nextval('" . $seqName . "')");
310 $this->mInsertId = $value;
311 return $value;
312 }
313
314 /**
315 * USE INDEX clause
316 * PostgreSQL doesn't have them and returns ""
317 */
318 function useIndexClause( $index ) {
319 return '';
320 }
321
322 # REPLACE query wrapper
323 # PostgreSQL simulates this with a DELETE followed by INSERT
324 # $row is the row to insert, an associative array
325 # $uniqueIndexes is an array of indexes. Each element may be either a
326 # field name or an array of field names
327 #
328 # It may be more efficient to leave off unique indexes which are unlikely to collide.
329 # However if you do this, you run the risk of encountering errors which wouldn't have
330 # occurred in MySQL
331 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
332 $table = $this->tableName( $table );
333
334 if (count($rows)==0) {
335 return;
336 }
337
338 # Single row case
339 if ( !is_array( reset( $rows ) ) ) {
340 $rows = array( $rows );
341 }
342
343 foreach( $rows as $row ) {
344 # Delete rows which collide
345 if ( $uniqueIndexes ) {
346 $sql = "DELETE FROM $table WHERE ";
347 $first = true;
348 foreach ( $uniqueIndexes as $index ) {
349 if ( $first ) {
350 $first = false;
351 $sql .= "(";
352 } else {
353 $sql .= ') OR (';
354 }
355 if ( is_array( $index ) ) {
356 $first2 = true;
357 foreach ( $index as $col ) {
358 if ( $first2 ) {
359 $first2 = false;
360 } else {
361 $sql .= ' AND ';
362 }
363 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
364 }
365 } else {
366 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
367 }
368 }
369 $sql .= ')';
370 $this->query( $sql, $fname );
371 }
372
373 # Now insert the row
374 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
375 $this->makeList( $row, LIST_COMMA ) . ')';
376 $this->query( $sql, $fname );
377 }
378 }
379
380 # DELETE where the condition is a join
381 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
382 if ( !$conds ) {
383 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
384 }
385
386 $delTable = $this->tableName( $delTable );
387 $joinTable = $this->tableName( $joinTable );
388 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
389 if ( $conds != '*' ) {
390 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
391 }
392 $sql .= ')';
393
394 $this->query( $sql, $fname );
395 }
396
397 # Returns the size of a text field, or -1 for "unlimited"
398 function textFieldSize( $table, $field ) {
399 $table = $this->tableName( $table );
400 $sql = "SELECT t.typname as ftype,a.atttypmod as size
401 FROM pg_class c, pg_attribute a, pg_type t
402 WHERE relname='$table' AND a.attrelid=c.oid AND
403 a.atttypid=t.oid and a.attname='$field'";
404 $res =$this->query($sql);
405 $row=$this->fetchObject($res);
406 if ($row->ftype=="varchar") {
407 $size=$row->size-4;
408 } else {
409 $size=$row->size;
410 }
411 $this->freeResult( $res );
412 return $size;
413 }
414
415 function lowPriorityOption() {
416 return '';
417 }
418
419 function limitResult($sql, $limit,$offset) {
420 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
421 }
422
423 /**
424 * Returns an SQL expression for a simple conditional.
425 * Uses CASE on PostgreSQL.
426 *
427 * @param string $cond SQL expression which will result in a boolean value
428 * @param string $trueVal SQL expression to return if true
429 * @param string $falseVal SQL expression to return if false
430 * @return string SQL fragment
431 */
432 function conditional( $cond, $trueVal, $falseVal ) {
433 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
434 }
435
436 # FIXME: actually detecting deadlocks might be nice
437 function wasDeadlock() {
438 return false;
439 }
440
441 # Return DB-style timestamp used for MySQL schema
442 function timestamp( $ts=0 ) {
443 return wfTimestamp(TS_DB,$ts);
444 }
445
446 /**
447 * Return aggregated value function call
448 */
449 function aggregateValue ($valuedata,$valuename='value') {
450 return $valuedata;
451 }
452
453
454 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
455 $message = "A database error has occurred\n" .
456 "Query: $sql\n" .
457 "Function: $fname\n" .
458 "Error: $errno $error\n";
459 throw new DBUnexpectedError($this, $message);
460 }
461
462 /**
463 * @return string wikitext of a link to the server software's web site
464 */
465 function getSoftwareLink() {
466 return "[http://www.postgresql.org/ PostgreSQL]";
467 }
468
469 /**
470 * @return string Version information from the database
471 */
472 function getServerVersion() {
473 $res = $this->query( "SELECT version()" );
474 $row = $this->fetchRow( $res );
475 $version = $row[0];
476 $this->freeResult( $res );
477 return $version;
478 }
479
480
481 /**
482 * Query whether a given table exists (in the given schema, or the default mw one if not given)
483 */
484 function tableExists( $table, $schema = false ) {
485 global $wgDBmwschema;
486 if (! $schema )
487 $schema = $wgDBmwschema;
488 $etable = preg_replace("/'/", "''", $table);
489 $eschema = preg_replace("/'/", "''", $schema);
490 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
491 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
492 $res = $this->query( $SQL );
493 $count = $res ? pg_num_rows($res) : 0;
494 if ($res)
495 $this->freeResult( $res );
496 return $count;
497 }
498
499
500 /**
501 * Query whether a given schema exists. Returns the name of the owner
502 */
503 function schemaExists( $schema ) {
504 $eschema = preg_replace("/'/", "''", $schema);
505 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
506 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
507 $res = $this->query( $SQL );
508 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
509 if ($res)
510 $this->freeResult($res);
511 return $owner;
512 }
513
514 /**
515 * Query whether a given column exists in the mediawiki schema
516 */
517 function fieldExists( $table, $field ) {
518 global $wgDBmwschema;
519 $etable = preg_replace("/'/", "''", $table);
520 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
521 $ecol = preg_replace("/'/", "''", $field);
522 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
523 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
524 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
525 $res = $this->query( $SQL );
526 $count = $res ? pg_num_rows($res) : 0;
527 if ($res)
528 $this->freeResult( $res );
529 return $count;
530 }
531
532 function fieldInfo( $table, $field ) {
533 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
534 $type = pg_field_type( $res, 0 );
535 return $type;
536 }
537
538 function commit( $fname = 'Database::commit' ) {
539 ## XXX
540 return;
541 $this->query( 'COMMIT', $fname );
542 $this->mTrxLevel = 0;
543 }
544
545 /* Not even sure why this is used in the main codebase... */
546 function limitResultForUpdate($sql, $num) {
547 return $sql;
548 }
549
550 function update_interwiki() {
551 ## Avoid the non-standard "REPLACE INTO" syntax
552 ## Called by config/index.php
553 $f = fopen( "../maintenance/interwiki.sql", 'r' );
554 if ($f == false ) {
555 dieout( "<li>Could not find the interwiki.sql file");
556 }
557 ## We simply assume it is already empty as we have just created it
558 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
559 while ( ! feof( $f ) ) {
560 $line = fgets($f,1024);
561 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
562 continue;
563 }
564 $yesno = $matches[2]; ## ? "'true'" : "'false'";
565 $this->query("$SQL $matches[1],$matches[2])");
566 }
567 print " (table interwiki successfully populated)...\n";
568 }
569
570 }
571
572 ?>