Return nothing on empty math tags instead of char encoding
[lhc/web/wiklou.git] / includes / DatabasePostgres.php
1 <?php
2
3 /**
4 * This is the Postgres 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 class DatabasePostgres extends Database {
14 var $mInsertId = NULL;
15 var $mLastResult = NULL;
16
17 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
18 $failFunction = false, $flags = 0 )
19 {
20
21 global $wgOut;
22 # Can't get a reference if it hasn't been set yet
23 if ( !isset( $wgOut ) ) {
24 $wgOut = NULL;
25 }
26 $this->mOut =& $wgOut;
27 $this->mFailFunction = $failFunction;
28 $this->mCascadingDeletes = true;
29 $this->mCleanupTriggers = true;
30 $this->mStrictIPs = true;
31 $this->mFlags = $flags;
32 $this->open( $server, $user, $password, $dbName);
33
34 }
35
36 function realTimestamps() {
37 return true;
38 }
39
40 function implicitGroupby() {
41 return false;
42 }
43
44 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
45 $failFunction = false, $flags = 0)
46 {
47 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
48 }
49
50 /**
51 * Usually aborts on failure
52 * If the failFunction is set to a non-zero integer, returns success
53 */
54 function open( $server, $user, $password, $dbName ) {
55 # Test for Postgres support, to avoid suppressed fatal error
56 if ( !function_exists( 'pg_connect' ) ) {
57 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
58 }
59
60
61 global $wgDBport;
62
63 $this->close();
64 $this->mServer = $server;
65 $port = $wgDBport;
66 $this->mUser = $user;
67 $this->mPassword = $password;
68 $this->mDBname = $dbName;
69
70 $hstring="";
71 if ($server!=false && $server!="") {
72 $hstring="host=$server ";
73 }
74 if ($port!=false && $port!="") {
75 $hstring .= "port=$port ";
76 }
77
78 if (!strlen($user)) { ## e.g. the class is being loaded
79 return;
80 }
81
82 error_reporting( E_ALL );
83 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
84
85 if ( $this->mConn == false ) {
86 wfDebug( "DB connection error\n" );
87 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
88 wfDebug( $this->lastError()."\n" );
89 return false;
90 }
91
92 $this->mOpened = true;
93 ## If this is the initial connection, setup the schema stuff and possibly create the user
94 if (defined('MEDIAWIKI_INSTALL')) {
95 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
96 $wgDBts2schema;
97 print "OK</li>\n";
98
99 print "<li>Checking the version of Postgres...";
100 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
101 $thisver = array();
102 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
103 print "<b>FAILED</b> (could not determine the version)</li>\n";
104 dieout("</ul>");
105 }
106 $PGMINVER = "8.1";
107 if ($thisver[1] < $PGMINVER) {
108 print "<b>FAILED</b>. Required version is $PGMINVER. You have $thisver[1]$thisver[2]</li>\n";
109 dieout("</ul>");
110 }
111 print "version $thisver[1]$thisver[2] is OK.</li>\n";
112
113 $safeuser = $this->quote_ident($wgDBuser);
114 ## Are we connecting as a superuser for the first time?
115 if ($wgDBsuperuser) {
116 ## Are we really a superuser? Check out our rights
117 $SQL = "SELECT
118 CASE WHEN usesuper IS TRUE THEN
119 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
120 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
121 END AS rights
122 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
123 $rows = $this->numRows($res = $this->doQuery($SQL));
124 if (!$rows) {
125 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
126 dieout('</ul>');
127 }
128 $perms = pg_fetch_result($res, 0, 0);
129
130 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
131 $rows = $this->numRows($this->doQuery($SQL));
132 if ($rows) {
133 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
134 }
135 else {
136 if ($perms != 1 and $perms != 3) {
137 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
138 print 'Please use a different Postgres user.</li>';
139 dieout('</ul>');
140 }
141 print "<li>Creating user <b>$wgDBuser</b>...";
142 $safepass = $this->addQuotes($wgDBpassword);
143 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
144 $this->doQuery($SQL);
145 print "OK</li>\n";
146 }
147 ## User now exists, check out the database
148 if ($dbName != $wgDBname) {
149 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
150 $rows = $this->numRows($this->doQuery($SQL));
151 if ($rows) {
152 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
153 }
154 else {
155 if ($perms < 2) {
156 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
157 print 'Please use a different Postgres user.</li>';
158 dieout('</ul>');
159 }
160 print "<li>Creating database <b>$wgDBname</b>...";
161 $safename = $this->quote_ident($wgDBname);
162 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
163 $this->doQuery($SQL);
164 print "OK</li>\n";
165 ## Hopefully tsearch2 and plpgsql are in template1...
166 }
167
168 ## Reconnect to check out tsearch2 rights for this user
169 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
170 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
171 if ( $this->mConn == false ) {
172 print "<b>FAILED TO CONNECT!</b></li>";
173 dieout("</ul>");
174 }
175 print "OK</li>\n";
176 }
177
178 ## Tsearch2 checks
179 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
180 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
181 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
182 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
183 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
184 dieout("</ul>");
185 }
186 print "OK</li>\n";
187 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
188 foreach (array('cfg','cfgmap','dict','parser') as $table) {
189 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
190 $this->doQuery($SQL);
191 }
192 print "OK</li>\n";
193
194
195 ## Setup the schema for this user if needed
196 $result = $this->schemaExists($wgDBmwschema);
197 $safeschema = $this->quote_ident($wgDBmwschema);
198 if (!$result) {
199 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
200 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
201 if (!$result) {
202 print "<b>FAILED</b>.</li>\n";
203 dieout("</ul>");
204 }
205 print "OK</li>\n";
206 }
207 else {
208 print "<li>Schema already exists, explicitly granting rights...\n";
209 $safeschema2 = $this->addQuotes($wgDBmwschema);
210 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
211 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
212 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
213 "AND p.relkind IN ('r','S','v')\n";
214 $SQL .= "UNION\n";
215 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
216 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
217 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
218 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
219 $res = $this->doQuery($SQL);
220 if (!$res) {
221 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
222 dieout("</ul>");
223 }
224 $this->doQuery("SET search_path = $safeschema");
225 $rows = $this->numRows($res);
226 while ($rows) {
227 $rows--;
228 $this->doQuery(pg_fetch_result($res, $rows, 0));
229 }
230 print "OK</li>";
231 }
232
233 $wgDBsuperuser = '';
234 return true; ## Reconnect as regular user
235 }
236
237 if (!defined('POSTGRES_SEARCHPATH')) {
238
239 ## Do we have the basic tsearch2 table?
240 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
241 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
242 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
243 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
244 print " for instructions.</li>\n";
245 dieout("</ul>");
246 }
247 print "OK</li>\n";
248
249 ## Does this user have the rights to the tsearch2 tables?
250 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
251 print "<li>Checking tsearch2 permissions...";
252 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
253 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
254 error_reporting( 0 );
255 $res = $this->doQuery($SQL);
256 error_reporting( E_ALL );
257 if (!$res) {
258 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
259 dieout("</ul>");
260 }
261 print "OK</li>";
262
263 ## Will the current locale work? Can we force it to?
264 print "<li>Verifying tsearch2 locale with $ctype...";
265 $rows = $this->numRows($res);
266 $resetlocale = 0;
267 if (!$rows) {
268 print "<b>not found</b></li>\n";
269 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
270 $resetlocale = 1;
271 }
272 else {
273 $tsname = pg_fetch_result($res, 0, 0);
274 if ($tsname != 'default') {
275 print "<b>not set to default ($tsname)</b>";
276 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
277 $resetlocale = 1;
278 }
279 }
280 if ($resetlocale) {
281 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
282 $res = $this->doQuery($SQL);
283 if (!$res) {
284 print "<b>FAILED</b>. ";
285 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"ctype\"</li>\n";
286 dieout("</ul>");
287 }
288 print "OK</li>";
289 }
290
291 ## Final test: try out a simple tsearch2 query
292 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
293 $res = $this->doQuery($SQL);
294 if (!$res) {
295 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
296 dieout("</ul>");
297 }
298 print "OK</li>";
299
300 ## Do we have plpgsql installed?
301 print "<li>Checking for Pl/Pgsql ...";
302 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
303 $rows = $this->numRows($this->doQuery($SQL));
304 if ($rows < 1) {
305 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
306 print "not installed. Attempting to install Pl/Pgsql ...";
307 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
308 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
309 $rows = $this->numRows($this->doQuery($SQL));
310 if ($rows >= 1) {
311 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
312 if (!$result) {
313 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
314 dieout("</ul>");
315 }
316 }
317 else {
318 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
319 dieout("</ul>");
320 }
321 }
322 print "OK</li>\n";
323
324 ## Does the schema already exist? Who owns it?
325 $result = $this->schemaExists($wgDBmwschema);
326 if (!$result) {
327 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
328 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
329 if (!$result) {
330 print "<b>FAILED</b>.</li>\n";
331 dieout("</ul>");
332 }
333 print "OK</li>\n";
334 }
335 else if ($result != $user) {
336 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
337 }
338 else {
339 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
340 }
341
342 ## Fix up the search paths if needed
343 print "<li>Setting the search path for user \"$user\" ...";
344 $path = $this->quote_ident($wgDBmwschema);
345 if ($wgDBts2schema !== $wgDBmwschema)
346 $path .= ", ". $this->quote_ident($wgDBts2schema);
347 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
348 $path .= ", public";
349 $SQL = "ALTER USER $safeuser SET search_path = $path";
350 $result = pg_query($this->mConn, $SQL);
351 if (!$result) {
352 print "<b>FAILED</b>.</li>\n";
353 dieout("</ul>");
354 }
355 print "OK</li>\n";
356 ## Set for the rest of this session
357 $SQL = "SET search_path = $path";
358 $result = pg_query($this->mConn, $SQL);
359 if (!$result) {
360 print "<li>Failed to set search_path</li>\n";
361 dieout("</ul>");
362 }
363 define( "POSTGRES_SEARCHPATH", $path );
364 }}
365
366 global $wgCommandLineMode;
367 ## If called from the command-line (e.g. importDump), only show errors
368 if ($wgCommandLineMode) {
369 $this->doQuery("SET client_min_messages = 'ERROR'");
370 }
371
372 return $this->mConn;
373 }
374
375 /**
376 * Closes a database connection, if it is open
377 * Returns success, true if already closed
378 */
379 function close() {
380 $this->mOpened = false;
381 if ( $this->mConn ) {
382 return pg_close( $this->mConn );
383 } else {
384 return true;
385 }
386 }
387
388 function doQuery( $sql ) {
389 return $this->mLastResult=pg_query( $this->mConn , $sql);
390 }
391
392 function queryIgnore( $sql, $fname = '' ) {
393 return $this->query( $sql, $fname, true );
394 }
395
396 function freeResult( $res ) {
397 if ( !@pg_free_result( $res ) ) {
398 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
399 }
400 }
401
402 function fetchObject( $res ) {
403 @$row = pg_fetch_object( $res );
404 # FIXME: HACK HACK HACK HACK debug
405
406 # TODO:
407 # hashar : not sure if the following test really trigger if the object
408 # fetching failled.
409 if( pg_last_error($this->mConn) ) {
410 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
411 }
412 return $row;
413 }
414
415 function fetchRow( $res ) {
416 @$row = pg_fetch_array( $res );
417 if( pg_last_error($this->mConn) ) {
418 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
419 }
420 return $row;
421 }
422
423 function numRows( $res ) {
424 @$n = pg_num_rows( $res );
425 if( pg_last_error($this->mConn) ) {
426 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
427 }
428 return $n;
429 }
430 function numFields( $res ) { return pg_num_fields( $res ); }
431 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
432
433 /**
434 * This must be called after nextSequenceVal
435 */
436 function insertId() {
437 return $this->mInsertId;
438 }
439
440 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
441 function lastError() {
442 if ( $this->mConn ) {
443 return pg_last_error();
444 }
445 else {
446 return "No database connection";
447 }
448 }
449 function lastErrno() {
450 return pg_last_error() ? 1 : 0;
451 }
452
453 function affectedRows() {
454 return pg_affected_rows( $this->mLastResult );
455 }
456
457 /**
458 * Returns information about an index
459 * If errors are explicitly ignored, returns NULL on failure
460 */
461 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
462 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
463 $res = $this->query( $sql, $fname );
464 if ( !$res ) {
465 return NULL;
466 }
467
468 while ( $row = $this->fetchObject( $res ) ) {
469 if ( $row->indexname == $index ) {
470 return $row;
471
472 // BUG: !!!! This code needs to be synced up with database.php
473
474 }
475 }
476 return false;
477 }
478
479 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
480 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
481 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
482 $res = $this->query( $sql, $fname );
483 if ( !$res )
484 return NULL;
485 while ($row = $this->fetchObject( $res ))
486 return true;
487 return false;
488
489 }
490
491 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
492 # Postgres doesn't support options
493 # We have a go at faking one of them
494 # TODO: DELAYED, LOW_PRIORITY
495
496 if ( !is_array($options))
497 $options = array($options);
498
499 if ( in_array( 'IGNORE', $options ) )
500 $oldIgnore = $this->ignoreErrors( true );
501
502 # IGNORE is performed using single-row inserts, ignoring errors in each
503 # FIXME: need some way to distiguish between key collision and other types of error
504 $oldIgnore = $this->ignoreErrors( true );
505 if ( !is_array( reset( $a ) ) ) {
506 $a = array( $a );
507 }
508 foreach ( $a as $row ) {
509 parent::insert( $table, $row, $fname, array() );
510 }
511 $this->ignoreErrors( $oldIgnore );
512 $retVal = true;
513
514 if ( in_array( 'IGNORE', $options ) )
515 $this->ignoreErrors( $oldIgnore );
516
517 return $retVal;
518 }
519
520 function tableName( $name ) {
521 # Replace reserved words with better ones
522 switch( $name ) {
523 case 'user':
524 return 'mwuser';
525 case 'text':
526 return 'pagecontent';
527 default:
528 return $name;
529 }
530 }
531
532 /**
533 * Return the next in a sequence, save the value for retrieval via insertId()
534 */
535 function nextSequenceValue( $seqName ) {
536 $safeseq = preg_replace( "/'/", "''", $seqName );
537 $res = $this->query( "SELECT nextval('$safeseq')" );
538 $row = $this->fetchRow( $res );
539 $this->mInsertId = $row[0];
540 $this->freeResult( $res );
541 return $this->mInsertId;
542 }
543
544 /**
545 * Postgres does not have a "USE INDEX" clause, so return an empty string
546 */
547 function useIndexClause( $index ) {
548 return '';
549 }
550
551 # REPLACE query wrapper
552 # Postgres simulates this with a DELETE followed by INSERT
553 # $row is the row to insert, an associative array
554 # $uniqueIndexes is an array of indexes. Each element may be either a
555 # field name or an array of field names
556 #
557 # It may be more efficient to leave off unique indexes which are unlikely to collide.
558 # However if you do this, you run the risk of encountering errors which wouldn't have
559 # occurred in MySQL
560 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
561 $table = $this->tableName( $table );
562
563 if (count($rows)==0) {
564 return;
565 }
566
567 # Single row case
568 if ( !is_array( reset( $rows ) ) ) {
569 $rows = array( $rows );
570 }
571
572 foreach( $rows as $row ) {
573 # Delete rows which collide
574 if ( $uniqueIndexes ) {
575 $sql = "DELETE FROM $table WHERE ";
576 $first = true;
577 foreach ( $uniqueIndexes as $index ) {
578 if ( $first ) {
579 $first = false;
580 $sql .= "(";
581 } else {
582 $sql .= ') OR (';
583 }
584 if ( is_array( $index ) ) {
585 $first2 = true;
586 foreach ( $index as $col ) {
587 if ( $first2 ) {
588 $first2 = false;
589 } else {
590 $sql .= ' AND ';
591 }
592 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
593 }
594 } else {
595 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
596 }
597 }
598 $sql .= ')';
599 $this->query( $sql, $fname );
600 }
601
602 # Now insert the row
603 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
604 $this->makeList( $row, LIST_COMMA ) . ')';
605 $this->query( $sql, $fname );
606 }
607 }
608
609 # DELETE where the condition is a join
610 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
611 if ( !$conds ) {
612 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
613 }
614
615 $delTable = $this->tableName( $delTable );
616 $joinTable = $this->tableName( $joinTable );
617 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
618 if ( $conds != '*' ) {
619 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
620 }
621 $sql .= ')';
622
623 $this->query( $sql, $fname );
624 }
625
626 # Returns the size of a text field, or -1 for "unlimited"
627 function textFieldSize( $table, $field ) {
628 $table = $this->tableName( $table );
629 $sql = "SELECT t.typname as ftype,a.atttypmod as size
630 FROM pg_class c, pg_attribute a, pg_type t
631 WHERE relname='$table' AND a.attrelid=c.oid AND
632 a.atttypid=t.oid and a.attname='$field'";
633 $res =$this->query($sql);
634 $row=$this->fetchObject($res);
635 if ($row->ftype=="varchar") {
636 $size=$row->size-4;
637 } else {
638 $size=$row->size;
639 }
640 $this->freeResult( $res );
641 return $size;
642 }
643
644 function lowPriorityOption() {
645 return '';
646 }
647
648 function limitResult($sql, $limit,$offset) {
649 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
650 }
651
652 /**
653 * Returns an SQL expression for a simple conditional.
654 * Uses CASE on Postgres
655 *
656 * @param string $cond SQL expression which will result in a boolean value
657 * @param string $trueVal SQL expression to return if true
658 * @param string $falseVal SQL expression to return if false
659 * @return string SQL fragment
660 */
661 function conditional( $cond, $trueVal, $falseVal ) {
662 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
663 }
664
665 function wasDeadlock() {
666 return $this->lastErrno() == '40P01';
667 }
668
669 function timestamp( $ts=0 ) {
670 return wfTimestamp(TS_POSTGRES,$ts);
671 }
672
673 /**
674 * Return aggregated value function call
675 */
676 function aggregateValue ($valuedata,$valuename='value') {
677 return $valuedata;
678 }
679
680
681 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
682 # Ignore errors during error handling to avoid infinite recursion
683 $ignore = $this->ignoreErrors( true );
684 ++$this->mErrorCount;
685
686 if ($ignore || $tempIgnore) {
687 wfDebug("SQL ERROR (ignored): $error\n");
688 $this->ignoreErrors( $ignore );
689 }
690 else {
691 $message = "A database error has occurred\n" .
692 "Query: $sql\n" .
693 "Function: $fname\n" .
694 "Error: $errno $error\n";
695 throw new DBUnexpectedError($this, $message);
696 }
697 }
698
699 /**
700 * @return string wikitext of a link to the server software's web site
701 */
702 function getSoftwareLink() {
703 return "[http://www.postgresql.org/ PostgreSQL]";
704 }
705
706 /**
707 * @return string Version information from the database
708 */
709 function getServerVersion() {
710 $res = $this->query( "SELECT version()" );
711 $row = $this->fetchRow( $res );
712 $version = $row[0];
713 $this->freeResult( $res );
714 return $version;
715 }
716
717
718 /**
719 * Query whether a given table exists (in the given schema, or the default mw one if not given)
720 */
721 function tableExists( $table, $schema = false ) {
722 global $wgDBmwschema;
723 if (! $schema )
724 $schema = $wgDBmwschema;
725 $etable = preg_replace("/'/", "''", $table);
726 $eschema = preg_replace("/'/", "''", $schema);
727 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
728 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
729 . "AND c.relkind IN ('r','v')";
730 $res = $this->query( $SQL );
731 $count = $res ? pg_num_rows($res) : 0;
732 if ($res)
733 $this->freeResult( $res );
734 return $count;
735 }
736
737
738 /**
739 * Query whether a given schema exists. Returns the name of the owner
740 */
741 function schemaExists( $schema ) {
742 $eschema = preg_replace("/'/", "''", $schema);
743 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
744 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
745 $res = $this->query( $SQL );
746 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
747 if ($res)
748 $this->freeResult($res);
749 return $owner;
750 }
751
752 /**
753 * Query whether a given column exists in the mediawiki schema
754 */
755 function fieldExists( $table, $field ) {
756 global $wgDBmwschema;
757 $etable = preg_replace("/'/", "''", $table);
758 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
759 $ecol = preg_replace("/'/", "''", $field);
760 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
761 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
762 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
763 $res = $this->query( $SQL );
764 $count = $res ? pg_num_rows($res) : 0;
765 if ($res)
766 $this->freeResult( $res );
767 return $count;
768 }
769
770 function fieldInfo( $table, $field ) {
771 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
772 $type = pg_field_type( $res, 0 );
773 return $type;
774 }
775
776 function begin( $fname = 'DatabasePostgrs::begin' ) {
777 $this->query( 'BEGIN', $fname );
778 $this->mTrxLevel = 1;
779 }
780 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
781 return true;
782 }
783 function commit( $fname = 'DatabasePostgres::commit' ) {
784 $this->query( 'COMMIT', $fname );
785 $this->mTrxLevel = 0;
786 }
787
788 /* Not even sure why this is used in the main codebase... */
789 function limitResultForUpdate($sql, $num) {
790 return $sql;
791 }
792
793 function setup_database() {
794 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
795
796 dbsource( "../maintenance/postgres/tables.sql", $this);
797
798 ## Update version information
799 $mwv = $this->addQuotes($wgVersion);
800 $pgv = $this->addQuotes($this->getServerVersion());
801 $pgu = $this->addQuotes($this->mUser);
802 $mws = $this->addQuotes($wgDBmwschema);
803 $tss = $this->addQuotes($wgDBts2schema);
804 $pgp = $this->addQuotes($wgDBport);
805 $dbn = $this->addQuotes($this->mDBname);
806 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
807
808 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
809 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
810 "ctype = '$ctype' ".
811 "WHERE type = 'Creation'";
812 $this->query($SQL);
813
814 ## Avoid the non-standard "REPLACE INTO" syntax
815 $f = fopen( "../maintenance/interwiki.sql", 'r' );
816 if ($f == false ) {
817 dieout( "<li>Could not find the interwiki.sql file");
818 }
819 ## We simply assume it is already empty as we have just created it
820 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
821 while ( ! feof( $f ) ) {
822 $line = fgets($f,1024);
823 $matches = array();
824 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
825 continue;
826 }
827 $this->query("$SQL $matches[1],$matches[2])");
828 }
829 print " (table interwiki successfully populated)...\n";
830 }
831
832 function encodeBlob($b) {
833 return array('bytea',pg_escape_bytea($b));
834 }
835 function decodeBlob($b) {
836 return pg_unescape_bytea( $b );
837 }
838
839 function strencode( $s ) { ## Should not be called by us
840 return pg_escape_string( $s );
841 }
842
843 function addQuotes( $s ) {
844 if ( is_null( $s ) ) {
845 return 'NULL';
846 } else if (is_array( $s )) { ## Assume it is bytea data
847 return "E'$s[1]'";
848 }
849 return "'" . pg_escape_string($s) . "'";
850 // Unreachable: return "E'" . pg_escape_string($s) . "'";
851 }
852
853 function quote_ident( $s ) {
854 return '"' . preg_replace( '/"/', '""', $s) . '"';
855 }
856
857 /* For now, does nothing */
858 function selectDB( $db ) {
859 return true;
860 }
861
862 /**
863 * Returns an optional USE INDEX clause to go after the table, and a
864 * string to go at the end of the query
865 *
866 * @private
867 *
868 * @param array $options an associative array of options to be turned into
869 * an SQL query, valid keys are listed in the function.
870 * @return array
871 */
872 function makeSelectOptions( $options ) {
873 $tailOpts = '';
874 $startOpts = '';
875
876 $noKeyOptions = array();
877 foreach ( $options as $key => $option ) {
878 if ( is_numeric( $key ) ) {
879 $noKeyOptions[$option] = true;
880 }
881 }
882
883 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
884 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
885
886 if (isset($options['LIMIT'])) {
887 $tailOpts .= $this->limitResult('', $options['LIMIT'],
888 isset($options['OFFSET']) ? $options['OFFSET'] : false);
889 }
890
891 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
892 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
893 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
894
895 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
896 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
897 } else {
898 $useIndex = '';
899 }
900
901 return array( $startOpts, $useIndex, $tailOpts );
902 }
903
904 function ping() {
905 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
906 return true;
907 }
908
909
910 } // end DatabasePostgres class
911
912 ?>