Fixed bug 15148, total breakage of Special:BlockIP on PostgreSQL:
[lhc/web/wiklou.git] / includes / db / DatabasePostgres.php
1 <?php
2 /**
3 * @ingroup Database
4 * @file
5 * This is the Postgres database abstraction layer.
6 *
7 */
8 class PostgresField {
9 private $name, $tablename, $type, $nullable, $max_length;
10
11 static function fromText($db, $table, $field) {
12 global $wgDBmwschema;
13
14 $q = <<<END
15 SELECT
16 CASE WHEN typname = 'int2' THEN 'smallint'
17 WHEN typname = 'int4' THEN 'integer'
18 WHEN typname = 'int8' THEN 'bigint'
19 WHEN typname = 'bpchar' THEN 'char'
20 ELSE typname END AS typname,
21 attnotnull, attlen
22 FROM pg_class, pg_namespace, pg_attribute, pg_type
23 WHERE relnamespace=pg_namespace.oid
24 AND relkind='r'
25 AND attrelid=pg_class.oid
26 AND atttypid=pg_type.oid
27 AND nspname=%s
28 AND relname=%s
29 AND attname=%s;
30 END;
31 $res = $db->query(sprintf($q,
32 $db->addQuotes($wgDBmwschema),
33 $db->addQuotes($table),
34 $db->addQuotes($field)));
35 $row = $db->fetchObject($res);
36 if (!$row)
37 return null;
38 $n = new PostgresField;
39 $n->type = $row->typname;
40 $n->nullable = ($row->attnotnull == 'f');
41 $n->name = $field;
42 $n->tablename = $table;
43 $n->max_length = $row->attlen;
44 return $n;
45 }
46
47 function name() {
48 return $this->name;
49 }
50
51 function tableName() {
52 return $this->tablename;
53 }
54
55 function type() {
56 return $this->type;
57 }
58
59 function nullable() {
60 return $this->nullable;
61 }
62
63 function maxLength() {
64 return $this->max_length;
65 }
66 }
67
68 /**
69 * @ingroup Database
70 */
71 class DatabasePostgres extends Database {
72 var $mInsertId = NULL;
73 var $mLastResult = NULL;
74 var $numeric_version = NULL;
75 var $mAffectedRows = NULL;
76
77 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
78 $failFunction = false, $flags = 0 )
79 {
80
81 global $wgOut;
82 # Can't get a reference if it hasn't been set yet
83 if ( !isset( $wgOut ) ) {
84 $wgOut = NULL;
85 }
86 $this->mOut =& $wgOut;
87 $this->mFailFunction = $failFunction;
88 $this->mFlags = $flags;
89 $this->open( $server, $user, $password, $dbName);
90
91 }
92
93 function cascadingDeletes() {
94 return true;
95 }
96 function cleanupTriggers() {
97 return true;
98 }
99 function strictIPs() {
100 return true;
101 }
102 function realTimestamps() {
103 return true;
104 }
105 function implicitGroupby() {
106 return false;
107 }
108 function implicitOrderby() {
109 return false;
110 }
111 function searchableIPs() {
112 return true;
113 }
114 function functionalIndexes() {
115 return true;
116 }
117
118 function hasConstraint( $name ) {
119 global $wgDBmwschema;
120 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" . pg_escape_string( $name ) . "' AND n.nspname = '" . pg_escape_string($wgDBmwschema) ."'";
121 return $this->numRows($res = $this->doQuery($SQL));
122 }
123
124 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
125 {
126 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
127 }
128
129 /**
130 * Usually aborts on failure
131 * If the failFunction is set to a non-zero integer, returns success
132 */
133 function open( $server, $user, $password, $dbName ) {
134 # Test for Postgres support, to avoid suppressed fatal error
135 if ( !function_exists( 'pg_connect' ) ) {
136 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" );
137 }
138
139 global $wgDBport;
140
141 if (!strlen($user)) { ## e.g. the class is being loaded
142 return;
143 }
144
145 $this->close();
146 $this->mServer = $server;
147 $this->mPort = $port = $wgDBport;
148 $this->mUser = $user;
149 $this->mPassword = $password;
150 $this->mDBname = $dbName;
151
152 $hstring="";
153 if ($server!=false && $server!="") {
154 $hstring="host=$server ";
155 }
156 if ($port!=false && $port!="") {
157 $hstring .= "port=$port ";
158 }
159
160 error_reporting( E_ALL );
161 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
162
163 if ( $this->mConn == false ) {
164 wfDebug( "DB connection error\n" );
165 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
166 wfDebug( $this->lastError()."\n" );
167 return false;
168 }
169
170 $this->mOpened = true;
171
172 global $wgCommandLineMode;
173 ## If called from the command-line (e.g. importDump), only show errors
174 if ($wgCommandLineMode) {
175 $this->doQuery("SET client_min_messages = 'ERROR'");
176 }
177
178 global $wgDBmwschema, $wgDBts2schema;
179 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
180 && $wgDBmwschema !== 'mediawiki'
181 && preg_match( '/^\w+$/', $wgDBmwschema )
182 && preg_match( '/^\w+$/', $wgDBts2schema )
183 ) {
184 $safeschema = $this->quote_ident($wgDBmwschema);
185 $safeschema2 = $this->quote_ident($wgDBts2schema);
186 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
187 }
188
189 return $this->mConn;
190 }
191
192
193 function initial_setup($password, $dbName) {
194 // If this is the initial connection, setup the schema stuff and possibly create the user
195 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
196
197 print "<li>Checking the version of Postgres...";
198 $version = $this->getServerVersion();
199 $PGMINVER = '8.1';
200 if ($this->numeric_version < $PGMINVER) {
201 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
202 dieout("</ul>");
203 }
204 print "version $this->numeric_version is OK.</li>\n";
205
206 $safeuser = $this->quote_ident($wgDBuser);
207 // Are we connecting as a superuser for the first time?
208 if ($wgDBsuperuser) {
209 // Are we really a superuser? Check out our rights
210 $SQL = "SELECT
211 CASE WHEN usesuper IS TRUE THEN
212 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
213 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
214 END AS rights
215 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
216 $rows = $this->numRows($res = $this->doQuery($SQL));
217 if (!$rows) {
218 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
219 dieout('</ul>');
220 }
221 $perms = pg_fetch_result($res, 0, 0);
222
223 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
224 $rows = $this->numRows($this->doQuery($SQL));
225 if ($rows) {
226 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
227 }
228 else {
229 if ($perms != 1 and $perms != 3) {
230 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
231 print 'Please use a different Postgres user.</li>';
232 dieout('</ul>');
233 }
234 print "<li>Creating user <b>$wgDBuser</b>...";
235 $safepass = $this->addQuotes($wgDBpassword);
236 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
237 $this->doQuery($SQL);
238 print "OK</li>\n";
239 }
240 // User now exists, check out the database
241 if ($dbName != $wgDBname) {
242 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
243 $rows = $this->numRows($this->doQuery($SQL));
244 if ($rows) {
245 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
246 }
247 else {
248 if ($perms < 2) {
249 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
250 print 'Please use a different Postgres user.</li>';
251 dieout('</ul>');
252 }
253 print "<li>Creating database <b>$wgDBname</b>...";
254 $safename = $this->quote_ident($wgDBname);
255 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
256 $this->doQuery($SQL);
257 print "OK</li>\n";
258 // Hopefully tsearch2 and plpgsql are in template1...
259 }
260
261 // Reconnect to check out tsearch2 rights for this user
262 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
263
264 $hstring="";
265 if ($this->mServer!=false && $this->mServer!="") {
266 $hstring="host=$this->mServer ";
267 }
268 if ($this->mPort!=false && $this->mPort!="") {
269 $hstring .= "port=$this->mPort ";
270 }
271
272 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
273 if ( $this->mConn == false ) {
274 print "<b>FAILED TO CONNECT!</b></li>";
275 dieout("</ul>");
276 }
277 print "OK</li>\n";
278 }
279
280 if ($this->numeric_version < 8.3) {
281 // Tsearch2 checks
282 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
283 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
284 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
285 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
286 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
287 dieout("</ul>");
288 }
289 print "OK</li>\n";
290 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
291 foreach (array('cfg','cfgmap','dict','parser') as $table) {
292 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
293 $this->doQuery($SQL);
294 }
295 print "OK</li>\n";
296 }
297
298 // Setup the schema for this user if needed
299 $result = $this->schemaExists($wgDBmwschema);
300 $safeschema = $this->quote_ident($wgDBmwschema);
301 if (!$result) {
302 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
303 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
304 if (!$result) {
305 print "<b>FAILED</b>.</li>\n";
306 dieout("</ul>");
307 }
308 print "OK</li>\n";
309 }
310 else {
311 print "<li>Schema already exists, explicitly granting rights...\n";
312 $safeschema2 = $this->addQuotes($wgDBmwschema);
313 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
314 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
315 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
316 "AND p.relkind IN ('r','S','v')\n";
317 $SQL .= "UNION\n";
318 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
319 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
320 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
321 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
322 $res = $this->doQuery($SQL);
323 if (!$res) {
324 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
325 dieout("</ul>");
326 }
327 $this->doQuery("SET search_path = $safeschema");
328 $rows = $this->numRows($res);
329 while ($rows) {
330 $rows--;
331 $this->doQuery(pg_fetch_result($res, $rows, 0));
332 }
333 print "OK</li>";
334 }
335
336 // Install plpgsql if needed
337 $this->setup_plpgsql();
338
339 $wgDBsuperuser = '';
340 return true; // Reconnect as regular user
341
342 } // end superuser
343
344 if (!defined('POSTGRES_SEARCHPATH')) {
345
346 if ($this->numeric_version < 8.3) {
347 // Do we have the basic tsearch2 table?
348 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
349 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
350 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
351 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
352 print " for instructions.</li>\n";
353 dieout("</ul>");
354 }
355 print "OK</li>\n";
356
357 // Does this user have the rights to the tsearch2 tables?
358 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
359 print "<li>Checking tsearch2 permissions...";
360 // Let's check all four, just to be safe
361 error_reporting( 0 );
362 $ts2tables = array('cfg','cfgmap','dict','parser');
363 $safetsschema = $this->quote_ident($wgDBts2schema);
364 foreach ( $ts2tables AS $tname ) {
365 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
366 $res = $this->doQuery($SQL);
367 if (!$res) {
368 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
369 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
370 dieout("</ul>");
371 }
372 }
373 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
374 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
375 $res = $this->doQuery($SQL);
376 error_reporting( E_ALL );
377 if (!$res) {
378 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
379 dieout("</ul>");
380 }
381 print "OK</li>";
382
383 // Will the current locale work? Can we force it to?
384 print "<li>Verifying tsearch2 locale with $ctype...";
385 $rows = $this->numRows($res);
386 $resetlocale = 0;
387 if (!$rows) {
388 print "<b>not found</b></li>\n";
389 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
390 $resetlocale = 1;
391 }
392 else {
393 $tsname = pg_fetch_result($res, 0, 0);
394 if ($tsname != 'default') {
395 print "<b>not set to default ($tsname)</b>";
396 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
397 $resetlocale = 1;
398 }
399 }
400 if ($resetlocale) {
401 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
402 $res = $this->doQuery($SQL);
403 if (!$res) {
404 print "<b>FAILED</b>. ";
405 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
406 dieout("</ul>");
407 }
408 print "OK</li>";
409 }
410
411 // Final test: try out a simple tsearch2 query
412 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
413 $res = $this->doQuery($SQL);
414 if (!$res) {
415 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
416 dieout("</ul>");
417 }
418 print "OK</li>";
419 }
420
421 // Install plpgsql if needed
422 $this->setup_plpgsql();
423
424 // Does the schema already exist? Who owns it?
425 $result = $this->schemaExists($wgDBmwschema);
426 if (!$result) {
427 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
428 error_reporting( 0 );
429 $safeschema = $this->quote_ident($wgDBmwschema);
430 $result = $this->doQuery("CREATE SCHEMA $safeschema");
431 error_reporting( E_ALL );
432 if (!$result) {
433 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
434 "You can try making them the owner of the database, or try creating the schema with a ".
435 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
436 dieout("</ul>");
437 }
438 print "OK</li>\n";
439 }
440 else if ($result != $wgDBuser) {
441 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
442 }
443 else {
444 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
445 }
446
447 // Always return GMT time to accomodate the existing integer-based timestamp assumption
448 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
449 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
450 $result = pg_query($this->mConn, $SQL);
451 if (!$result) {
452 print "<b>FAILED</b>.</li>\n";
453 dieout("</ul>");
454 }
455 print "OK</li>\n";
456 // Set for the rest of this session
457 $SQL = "SET timezone = 'GMT'";
458 $result = pg_query($this->mConn, $SQL);
459 if (!$result) {
460 print "<li>Failed to set timezone</li>\n";
461 dieout("</ul>");
462 }
463
464 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
465 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
466 $result = pg_query($this->mConn, $SQL);
467 if (!$result) {
468 print "<b>FAILED</b>.</li>\n";
469 dieout("</ul>");
470 }
471 print "OK</li>\n";
472 // Set for the rest of this session
473 $SQL = "SET datestyle = 'ISO, YMD'";
474 $result = pg_query($this->mConn, $SQL);
475 if (!$result) {
476 print "<li>Failed to set datestyle</li>\n";
477 dieout("</ul>");
478 }
479
480 // Fix up the search paths if needed
481 print "<li>Setting the search path for user \"$wgDBuser\" ...";
482 $path = $this->quote_ident($wgDBmwschema);
483 if ($wgDBts2schema !== $wgDBmwschema)
484 $path .= ", ". $this->quote_ident($wgDBts2schema);
485 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
486 $path .= ", public";
487 $SQL = "ALTER USER $safeuser SET search_path = $path";
488 $result = pg_query($this->mConn, $SQL);
489 if (!$result) {
490 print "<b>FAILED</b>.</li>\n";
491 dieout("</ul>");
492 }
493 print "OK</li>\n";
494 // Set for the rest of this session
495 $SQL = "SET search_path = $path";
496 $result = pg_query($this->mConn, $SQL);
497 if (!$result) {
498 print "<li>Failed to set search_path</li>\n";
499 dieout("</ul>");
500 }
501 define( "POSTGRES_SEARCHPATH", $path );
502 }
503 }
504
505
506 function setup_plpgsql() {
507 print "<li>Checking for Pl/Pgsql ...";
508 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
509 $rows = $this->numRows($this->doQuery($SQL));
510 if ($rows < 1) {
511 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
512 print "not installed. Attempting to install Pl/Pgsql ...";
513 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
514 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
515 $rows = $this->numRows($this->doQuery($SQL));
516 if ($rows >= 1) {
517 $olde = error_reporting(0);
518 error_reporting($olde - E_WARNING);
519 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
520 error_reporting($olde);
521 if (!$result) {
522 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
523 dieout("</ul>");
524 }
525 }
526 else {
527 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
528 dieout("</ul>");
529 }
530 }
531 print "OK</li>\n";
532 }
533
534
535 /**
536 * Closes a database connection, if it is open
537 * Returns success, true if already closed
538 */
539 function close() {
540 $this->mOpened = false;
541 if ( $this->mConn ) {
542 return pg_close( $this->mConn );
543 } else {
544 return true;
545 }
546 }
547
548 function doQuery( $sql ) {
549 if (function_exists('mb_convert_encoding')) {
550 $sql = mb_convert_encoding($sql,'UTF-8');
551 }
552 $this->mLastResult = pg_query( $this->mConn, $sql);
553 $this->mAffectedRows = NULL; // use pg_affected_rows(mLastResult)
554 return $this->mLastResult;
555 }
556
557 function queryIgnore( $sql, $fname = '' ) {
558 return $this->query( $sql, $fname, true );
559 }
560
561 function freeResult( $res ) {
562 if ( $res instanceof ResultWrapper ) {
563 $res = $res->result;
564 }
565 if ( !@pg_free_result( $res ) ) {
566 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
567 }
568 }
569
570 function fetchObject( $res ) {
571 if ( $res instanceof ResultWrapper ) {
572 $res = $res->result;
573 }
574 @$row = pg_fetch_object( $res );
575 # FIXME: HACK HACK HACK HACK debug
576
577 # TODO:
578 # hashar : not sure if the following test really trigger if the object
579 # fetching failed.
580 if( pg_last_error($this->mConn) ) {
581 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
582 }
583 return $row;
584 }
585
586 function fetchRow( $res ) {
587 if ( $res instanceof ResultWrapper ) {
588 $res = $res->result;
589 }
590 @$row = pg_fetch_array( $res );
591 if( pg_last_error($this->mConn) ) {
592 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
593 }
594 return $row;
595 }
596
597 function numRows( $res ) {
598 if ( $res instanceof ResultWrapper ) {
599 $res = $res->result;
600 }
601 @$n = pg_num_rows( $res );
602 if( pg_last_error($this->mConn) ) {
603 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
604 }
605 return $n;
606 }
607 function numFields( $res ) {
608 if ( $res instanceof ResultWrapper ) {
609 $res = $res->result;
610 }
611 return pg_num_fields( $res );
612 }
613 function fieldName( $res, $n ) {
614 if ( $res instanceof ResultWrapper ) {
615 $res = $res->result;
616 }
617 return pg_field_name( $res, $n );
618 }
619
620 /**
621 * This must be called after nextSequenceVal
622 */
623 function insertId() {
624 return $this->mInsertId;
625 }
626
627 function dataSeek( $res, $row ) {
628 if ( $res instanceof ResultWrapper ) {
629 $res = $res->result;
630 }
631 return pg_result_seek( $res, $row );
632 }
633
634 function lastError() {
635 if ( $this->mConn ) {
636 return pg_last_error();
637 }
638 else {
639 return "No database connection";
640 }
641 }
642 function lastErrno() {
643 return pg_last_error() ? 1 : 0;
644 }
645
646 function affectedRows() {
647 if ( !is_null( $this->mAffectedRows ) ) {
648 // Forced result for simulated queries
649 return $this->mAffectedRows;
650 }
651 if( empty( $this->mLastResult ) )
652 return 0;
653 return pg_affected_rows( $this->mLastResult );
654 }
655
656 /**
657 * Estimate rows in dataset
658 * Returns estimated count, based on EXPLAIN output
659 * This is not necessarily an accurate estimate, so use sparingly
660 * Returns -1 if count cannot be found
661 * Takes same arguments as Database::select()
662 */
663
664 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
665 $options['EXPLAIN'] = true;
666 $res = $this->select( $table, $vars, $conds, $fname, $options );
667 $rows = -1;
668 if ( $res ) {
669 $row = $this->fetchRow( $res );
670 $count = array();
671 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
672 $rows = $count[1];
673 }
674 $this->freeResult($res);
675 }
676 return $rows;
677 }
678
679
680 /**
681 * Returns information about an index
682 * If errors are explicitly ignored, returns NULL on failure
683 */
684 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
685 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
686 $res = $this->query( $sql, $fname );
687 if ( !$res ) {
688 return NULL;
689 }
690 while ( $row = $this->fetchObject( $res ) ) {
691 if ( $row->indexname == $index ) {
692 return $row;
693 }
694 }
695 return false;
696 }
697
698 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
699 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
700 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
701 $res = $this->query( $sql, $fname );
702 if ( !$res )
703 return NULL;
704 while ($row = $this->fetchObject( $res ))
705 return true;
706 return false;
707
708 }
709
710 /**
711 * INSERT wrapper, inserts an array into a table
712 *
713 * $args may be a single associative array, or an array of these with numeric keys,
714 * for multi-row insert (Postgres version 8.2 and above only).
715 *
716 * @param array $table String: Name of the table to insert to.
717 * @param array $args Array: Items to insert into the table.
718 * @param array $fname String: Name of the function, for profiling
719 * @param mixed $options String or Array. Valid options: IGNORE
720 *
721 * @return bool Success of insert operation. IGNORE always returns true.
722 */
723 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
724 global $wgDBversion;
725
726 if ( !count( $args ) ) {
727 return true;
728 }
729
730 $table = $this->tableName( $table );
731 if (! isset( $wgDBversion ) ) {
732 $this->getServerVersion();
733 $wgDBversion = $this->numeric_version;
734 }
735
736 if ( !is_array( $options ) )
737 $options = array( $options );
738
739 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
740 $multi = true;
741 $keys = array_keys( $args[0] );
742 }
743 else {
744 $multi = false;
745 $keys = array_keys( $args );
746 }
747
748 // If IGNORE is set, we use savepoints to emulate mysql's behavior
749 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
750
751 // If we are not in a transaction, we need to be for savepoint trickery
752 $didbegin = 0;
753 if ( $ignore ) {
754 if (! $this->mTrxLevel) {
755 $this->begin();
756 $didbegin = 1;
757 }
758 $olde = error_reporting( 0 );
759 // For future use, we may want to track the number of actual inserts
760 // Right now, insert (all writes) simply return true/false
761 $numrowsinserted = 0;
762 }
763
764 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
765
766 if ( $multi ) {
767 if ( $wgDBversion >= 8.2 && !$ignore ) {
768 $first = true;
769 foreach ( $args as $row ) {
770 if ( $first ) {
771 $first = false;
772 } else {
773 $sql .= ',';
774 }
775 $sql .= '(' . $this->makeList( $row ) . ')';
776 }
777 $res = (bool)$this->query( $sql, $fname, $ignore );
778 }
779 else {
780 $res = true;
781 $origsql = $sql;
782 foreach ( $args as $row ) {
783 $tempsql = $origsql;
784 $tempsql .= '(' . $this->makeList( $row ) . ')';
785
786 if ( $ignore ) {
787 pg_query($this->mConn, "SAVEPOINT $ignore");
788 }
789
790 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
791
792 if ( $ignore ) {
793 $bar = pg_last_error();
794 if ($bar != false) {
795 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
796 }
797 else {
798 pg_query( $this->mConn, "RELEASE $ignore" );
799 $numrowsinserted++;
800 }
801 }
802
803 // If any of them fail, we fail overall for this function call
804 // Note that this will be ignored if IGNORE is set
805 if (! $tempres)
806 $res = false;
807 }
808 }
809 }
810 else {
811 // Not multi, just a lone insert
812 if ( $ignore ) {
813 pg_query($this->mConn, "SAVEPOINT $ignore");
814 }
815
816 $sql .= '(' . $this->makeList( $args ) . ')';
817 $res = (bool)$this->query( $sql, $fname, $ignore );
818 if ( $ignore ) {
819 $bar = pg_last_error();
820 if ($bar != false) {
821 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
822 }
823 else {
824 pg_query( $this->mConn, "RELEASE $ignore" );
825 $numrowsinserted++;
826 }
827 }
828 }
829 if ( $ignore ) {
830 $olde = error_reporting( $olde );
831 if ($didbegin) {
832 $this->commit();
833 }
834
835 // Set the affected row count for the whole operation
836 $this->mAffectedRows = $numrowsinserted;
837
838 // IGNORE always returns true
839 return true;
840 }
841
842
843 return $res;
844
845 }
846
847 function tableName( $name ) {
848 # Replace reserved words with better ones
849 switch( $name ) {
850 case 'user':
851 return 'mwuser';
852 case 'text':
853 return 'pagecontent';
854 default:
855 return $name;
856 }
857 }
858
859 /**
860 * Return the next in a sequence, save the value for retrieval via insertId()
861 */
862 function nextSequenceValue( $seqName ) {
863 $safeseq = preg_replace( "/'/", "''", $seqName );
864 $res = $this->query( "SELECT nextval('$safeseq')" );
865 $row = $this->fetchRow( $res );
866 $this->mInsertId = $row[0];
867 $this->freeResult( $res );
868 return $this->mInsertId;
869 }
870
871 /**
872 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
873 */
874 function currentSequenceValue( $seqName ) {
875 $safeseq = preg_replace( "/'/", "''", $seqName );
876 $res = $this->query( "SELECT currval('$safeseq')" );
877 $row = $this->fetchRow( $res );
878 $currval = $row[0];
879 $this->freeResult( $res );
880 return $currval;
881 }
882
883 /**
884 * Postgres does not have a "USE INDEX" clause, so return an empty string
885 */
886 function useIndexClause( $index ) {
887 return '';
888 }
889
890 # REPLACE query wrapper
891 # Postgres simulates this with a DELETE followed by INSERT
892 # $row is the row to insert, an associative array
893 # $uniqueIndexes is an array of indexes. Each element may be either a
894 # field name or an array of field names
895 #
896 # It may be more efficient to leave off unique indexes which are unlikely to collide.
897 # However if you do this, you run the risk of encountering errors which wouldn't have
898 # occurred in MySQL
899 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
900 $table = $this->tableName( $table );
901
902 if (count($rows)==0) {
903 return;
904 }
905
906 # Single row case
907 if ( !is_array( reset( $rows ) ) ) {
908 $rows = array( $rows );
909 }
910
911 foreach( $rows as $row ) {
912 # Delete rows which collide
913 if ( $uniqueIndexes ) {
914 $sql = "DELETE FROM $table WHERE ";
915 $first = true;
916 foreach ( $uniqueIndexes as $index ) {
917 if ( $first ) {
918 $first = false;
919 $sql .= "(";
920 } else {
921 $sql .= ') OR (';
922 }
923 if ( is_array( $index ) ) {
924 $first2 = true;
925 foreach ( $index as $col ) {
926 if ( $first2 ) {
927 $first2 = false;
928 } else {
929 $sql .= ' AND ';
930 }
931 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
932 }
933 } else {
934 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
935 }
936 }
937 $sql .= ')';
938 $this->query( $sql, $fname );
939 }
940
941 # Now insert the row
942 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
943 $this->makeList( $row, LIST_COMMA ) . ')';
944 $this->query( $sql, $fname );
945 }
946 }
947
948 # DELETE where the condition is a join
949 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
950 if ( !$conds ) {
951 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
952 }
953
954 $delTable = $this->tableName( $delTable );
955 $joinTable = $this->tableName( $joinTable );
956 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
957 if ( $conds != '*' ) {
958 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
959 }
960 $sql .= ')';
961
962 $this->query( $sql, $fname );
963 }
964
965 # Returns the size of a text field, or -1 for "unlimited"
966 function textFieldSize( $table, $field ) {
967 $table = $this->tableName( $table );
968 $sql = "SELECT t.typname as ftype,a.atttypmod as size
969 FROM pg_class c, pg_attribute a, pg_type t
970 WHERE relname='$table' AND a.attrelid=c.oid AND
971 a.atttypid=t.oid and a.attname='$field'";
972 $res =$this->query($sql);
973 $row=$this->fetchObject($res);
974 if ($row->ftype=="varchar") {
975 $size=$row->size-4;
976 } else {
977 $size=$row->size;
978 }
979 $this->freeResult( $res );
980 return $size;
981 }
982
983 function lowPriorityOption() {
984 return '';
985 }
986
987 function limitResult($sql, $limit, $offset=false) {
988 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
989 }
990
991 /**
992 * Returns an SQL expression for a simple conditional.
993 * Uses CASE on Postgres
994 *
995 * @param string $cond SQL expression which will result in a boolean value
996 * @param string $trueVal SQL expression to return if true
997 * @param string $falseVal SQL expression to return if false
998 * @return string SQL fragment
999 */
1000 function conditional( $cond, $trueVal, $falseVal ) {
1001 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1002 }
1003
1004 function wasDeadlock() {
1005 return $this->lastErrno() == '40P01';
1006 }
1007
1008 function timestamp( $ts=0 ) {
1009 return wfTimestamp(TS_POSTGRES,$ts);
1010 }
1011
1012 /**
1013 * Return aggregated value function call
1014 */
1015 function aggregateValue ($valuedata,$valuename='value') {
1016 return $valuedata;
1017 }
1018
1019
1020 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1021 // Ignore errors during error handling to avoid infinite recursion
1022 $ignore = $this->ignoreErrors( true );
1023 $this->mErrorCount++;
1024
1025 if ($ignore || $tempIgnore) {
1026 wfDebug("SQL ERROR (ignored): $error\n");
1027 $this->ignoreErrors( $ignore );
1028 }
1029 else {
1030 $message = "A database error has occurred\n" .
1031 "Query: $sql\n" .
1032 "Function: $fname\n" .
1033 "Error: $errno $error\n";
1034 throw new DBUnexpectedError($this, $message);
1035 }
1036 }
1037
1038 /**
1039 * @return string wikitext of a link to the server software's web site
1040 */
1041 function getSoftwareLink() {
1042 return "[http://www.postgresql.org/ PostgreSQL]";
1043 }
1044
1045 /**
1046 * @return string Version information from the database
1047 */
1048 function getServerVersion() {
1049 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
1050 $thisver = array();
1051 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
1052 die("Could not determine the numeric version from $version!");
1053 }
1054 $this->numeric_version = $thisver[1];
1055 return $version;
1056 }
1057
1058
1059 /**
1060 * Query whether a given relation exists (in the given schema, or the
1061 * default mw one if not given)
1062 */
1063 function relationExists( $table, $types, $schema = false ) {
1064 global $wgDBmwschema;
1065 if (!is_array($types))
1066 $types = array($types);
1067 if (! $schema )
1068 $schema = $wgDBmwschema;
1069 $etable = $this->addQuotes($table);
1070 $eschema = $this->addQuotes($schema);
1071 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1072 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1073 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1074 $res = $this->query( $SQL );
1075 $count = $res ? $res->numRows() : 0;
1076 if ($res)
1077 $this->freeResult( $res );
1078 return $count ? true : false;
1079 }
1080
1081 /*
1082 * For backward compatibility, this function checks both tables and
1083 * views.
1084 */
1085 function tableExists ($table, $schema = false) {
1086 return $this->relationExists($table, array('r', 'v'), $schema);
1087 }
1088
1089 function sequenceExists ($sequence, $schema = false) {
1090 return $this->relationExists($sequence, 'S', $schema);
1091 }
1092
1093 function triggerExists($table, $trigger) {
1094 global $wgDBmwschema;
1095
1096 $q = <<<END
1097 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1098 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1099 AND tgrelid=pg_class.oid
1100 AND nspname=%s AND relname=%s AND tgname=%s
1101 END;
1102 $res = $this->query(sprintf($q,
1103 $this->addQuotes($wgDBmwschema),
1104 $this->addQuotes($table),
1105 $this->addQuotes($trigger)));
1106 if (!$res)
1107 return NULL;
1108 $rows = $res->numRows();
1109 $this->freeResult($res);
1110 return $rows;
1111 }
1112
1113 function ruleExists($table, $rule) {
1114 global $wgDBmwschema;
1115 $exists = $this->selectField("pg_rules", "rulename",
1116 array( "rulename" => $rule,
1117 "tablename" => $table,
1118 "schemaname" => $wgDBmwschema));
1119 return $exists === $rule;
1120 }
1121
1122 function constraintExists($table, $constraint) {
1123 global $wgDBmwschema;
1124 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1125 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1126 $this->addQuotes($wgDBmwschema),
1127 $this->addQuotes($table),
1128 $this->addQuotes($constraint));
1129 $res = $this->query($SQL);
1130 if (!$res)
1131 return NULL;
1132 $rows = $res->numRows();
1133 $this->freeResult($res);
1134 return $rows;
1135 }
1136
1137 /**
1138 * Query whether a given schema exists. Returns the name of the owner
1139 */
1140 function schemaExists( $schema ) {
1141 $eschema = preg_replace("/'/", "''", $schema);
1142 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1143 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1144 $res = $this->query( $SQL );
1145 if ( $res && $res->numRows() ) {
1146 $row = $res->fetchObject();
1147 $owner = $row->rolname;
1148 } else {
1149 $owner = false;
1150 }
1151 if ($res)
1152 $this->freeResult($res);
1153 return $owner;
1154 }
1155
1156 /**
1157 * Query whether a given column exists in the mediawiki schema
1158 */
1159 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1160 global $wgDBmwschema;
1161 $etable = preg_replace("/'/", "''", $table);
1162 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1163 $ecol = preg_replace("/'/", "''", $field);
1164 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1165 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1166 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1167 $res = $this->query( $SQL, $fname );
1168 $count = $res ? $res->numRows() : 0;
1169 if ($res)
1170 $this->freeResult( $res );
1171 return $count;
1172 }
1173
1174 function fieldInfo( $table, $field ) {
1175 return PostgresField::fromText($this, $table, $field);
1176 }
1177
1178 /**
1179 * pg_field_type() wrapper
1180 */
1181 function fieldType( $res, $index ) {
1182 if ( $res instanceof ResultWrapper ) {
1183 $res = $res->result;
1184 }
1185 return pg_field_type( $res, $index );
1186 }
1187
1188 function begin( $fname = 'DatabasePostgres::begin' ) {
1189 $this->query( 'BEGIN', $fname );
1190 $this->mTrxLevel = 1;
1191 }
1192 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1193 return true;
1194 }
1195 function commit( $fname = 'DatabasePostgres::commit' ) {
1196 $this->query( 'COMMIT', $fname );
1197 $this->mTrxLevel = 0;
1198 }
1199
1200 /* Not even sure why this is used in the main codebase... */
1201 function limitResultForUpdate($sql, $num) {
1202 return $sql;
1203 }
1204
1205 function setup_database() {
1206 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1207
1208 // Make sure that we can write to the correct schema
1209 // If not, Postgres will happily and silently go to the next search_path item
1210 $ctest = "mediawiki_test_table";
1211 $safeschema = $this->quote_ident($wgDBmwschema);
1212 if ($this->tableExists($ctest, $wgDBmwschema)) {
1213 $this->doQuery("DROP TABLE $safeschema.$ctest");
1214 }
1215 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1216 $olde = error_reporting( 0 );
1217 $res = $this->doQuery($SQL);
1218 error_reporting( $olde );
1219 if (!$res) {
1220 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1221 dieout("</ul>");
1222 }
1223 $this->doQuery("DROP TABLE $safeschema.$ctest");
1224
1225 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1226
1227 ## Update version information
1228 $mwv = $this->addQuotes($wgVersion);
1229 $pgv = $this->addQuotes($this->getServerVersion());
1230 $pgu = $this->addQuotes($this->mUser);
1231 $mws = $this->addQuotes($wgDBmwschema);
1232 $tss = $this->addQuotes($wgDBts2schema);
1233 $pgp = $this->addQuotes($wgDBport);
1234 $dbn = $this->addQuotes($this->mDBname);
1235 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1236
1237 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1238 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1239 "ctype = '$ctype' ".
1240 "WHERE type = 'Creation'";
1241 $this->query($SQL);
1242
1243 ## Avoid the non-standard "REPLACE INTO" syntax
1244 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1245 if ($f == false ) {
1246 dieout( "<li>Could not find the interwiki.sql file");
1247 }
1248 ## We simply assume it is already empty as we have just created it
1249 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1250 while ( ! feof( $f ) ) {
1251 $line = fgets($f,1024);
1252 $matches = array();
1253 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1254 continue;
1255 }
1256 $this->query("$SQL $matches[1],$matches[2])");
1257 }
1258 print " (table interwiki successfully populated)...\n";
1259
1260 $this->doQuery("COMMIT");
1261 }
1262
1263 function encodeBlob( $b ) {
1264 return new Blob ( pg_escape_bytea( $b ) ) ;
1265 }
1266
1267 function decodeBlob( $b ) {
1268 if ($b instanceof Blob) {
1269 $b = $b->fetch();
1270 }
1271 return pg_unescape_bytea( $b );
1272 }
1273
1274 function strencode( $s ) { ## Should not be called by us
1275 return pg_escape_string( $s );
1276 }
1277
1278 function addQuotes( $s ) {
1279 if ( is_null( $s ) ) {
1280 return 'NULL';
1281 } else if ( is_bool( $s ) ) {
1282 return intval( $s );
1283 } else if ($s instanceof Blob) {
1284 return "'".$s->fetch($s)."'";
1285 }
1286 return "'" . pg_escape_string($s) . "'";
1287 }
1288
1289 function quote_ident( $s ) {
1290 return '"' . preg_replace( '/"/', '""', $s) . '"';
1291 }
1292
1293 /* For now, does nothing */
1294 function selectDB( $db ) {
1295 return true;
1296 }
1297
1298 /**
1299 * Postgres specific version of replaceVars.
1300 * Calls the parent version in Database.php
1301 *
1302 * @private
1303 *
1304 * @param string $com SQL string, read from a stream (usually tables.sql)
1305 *
1306 * @return string SQL string
1307 */
1308 protected function replaceVars( $ins ) {
1309
1310 $ins = parent::replaceVars( $ins );
1311
1312 if ($this->numeric_version >= 8.3) {
1313 // Thanks for not providing backwards-compatibility, 8.3
1314 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1315 }
1316
1317 if ($this->numeric_version <= 8.1) { // Our minimum version
1318 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1319 }
1320
1321 return $ins;
1322 }
1323
1324 /**
1325 * Various select options
1326 *
1327 * @private
1328 *
1329 * @param array $options an associative array of options to be turned into
1330 * an SQL query, valid keys are listed in the function.
1331 * @return array
1332 */
1333 function makeSelectOptions( $options ) {
1334 $preLimitTail = $postLimitTail = '';
1335 $startOpts = $useIndex = '';
1336
1337 $noKeyOptions = array();
1338 foreach ( $options as $key => $option ) {
1339 if ( is_numeric( $key ) ) {
1340 $noKeyOptions[$option] = true;
1341 }
1342 }
1343
1344 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1345 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1346 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1347
1348 //if (isset($options['LIMIT'])) {
1349 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1350 // isset($options['OFFSET']) ? $options['OFFSET']
1351 // : false);
1352 //}
1353
1354 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1355 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1356 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1357
1358 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1359 }
1360
1361 public function setTimeout( $timeout ) {
1362 // @todo fixme no-op
1363 }
1364
1365 function ping() {
1366 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1367 return true;
1368 }
1369
1370 /**
1371 * How lagged is this slave?
1372 *
1373 */
1374 public function getLag() {
1375 # Not implemented for PostgreSQL
1376 return false;
1377 }
1378
1379 function setFakeSlaveLag( $lag ) {}
1380 function setFakeMaster( $enabled = true ) {}
1381
1382 function getDBname() {
1383 return $this->mDBname;
1384 }
1385
1386 function getServer() {
1387 return $this->mServer;
1388 }
1389
1390 function buildConcat( $stringList ) {
1391 return implode( ' || ', $stringList );
1392 }
1393
1394 /* These are not used yet, but we know we don't want the default version */
1395
1396 public function lock( $lockName, $method ) {
1397 return true;
1398 }
1399 public function unlock( $lockName, $method ) {
1400 return true;
1401 }
1402
1403 public function getSearchEngine() {
1404 return "SearchPostgres";
1405 }
1406
1407 } // end DatabasePostgres class