e85cc874d7c116978bef9196fb685aa886424065
[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 $this->mFailFunction = $failFunction;
82 $this->mFlags = $flags;
83 $this->open( $server, $user, $password, $dbName);
84
85 }
86
87 function cascadingDeletes() {
88 return true;
89 }
90 function cleanupTriggers() {
91 return true;
92 }
93 function strictIPs() {
94 return true;
95 }
96 function realTimestamps() {
97 return true;
98 }
99 function implicitGroupby() {
100 return false;
101 }
102 function implicitOrderby() {
103 return false;
104 }
105 function searchableIPs() {
106 return true;
107 }
108 function functionalIndexes() {
109 return true;
110 }
111
112 function hasConstraint( $name ) {
113 global $wgDBmwschema;
114 $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) ."'";
115 return $this->numRows($res = $this->doQuery($SQL));
116 }
117
118 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
119 {
120 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
121 }
122
123 /**
124 * Usually aborts on failure
125 * If the failFunction is set to a non-zero integer, returns success
126 */
127 function open( $server, $user, $password, $dbName ) {
128 # Test for Postgres support, to avoid suppressed fatal error
129 if ( !function_exists( 'pg_connect' ) ) {
130 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" );
131 }
132
133 global $wgDBport;
134
135 $this->close();
136 $this->mServer = $server;
137 $this->mPort = $port = $wgDBport;
138 $this->mUser = $user;
139 $this->mPassword = $password;
140 $this->mDBname = $dbName;
141
142 $connectVars = array(
143 'dbname' => $dbName,
144 'user' => $user,
145 'password' => $password );
146 if ($server!=false && $server!="") {
147 $connectVars['host'] = $server;
148 }
149 if ($port!=false && $port!="") {
150 $connectVars['port'] = $port;
151 }
152 $connectString = $this->makeConnectionString( $connectVars );
153
154 $this->installErrorHandler();
155 $this->mConn = pg_connect( $connectString );
156 $phpError = $this->restoreErrorHandler();
157
158 if ( $this->mConn == false ) {
159 wfDebug( "DB connection error\n" );
160 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
161 wfDebug( $this->lastError()."\n" );
162 if ( !$this->mFailFunction ) {
163 throw new DBConnectionError( $this, $phpError );
164 } else {
165 return false;
166 }
167 }
168
169 $this->mOpened = true;
170
171 global $wgCommandLineMode;
172 ## If called from the command-line (e.g. importDump), only show errors
173 if ($wgCommandLineMode) {
174 $this->doQuery("SET client_min_messages = 'ERROR'");
175 }
176
177 global $wgDBmwschema, $wgDBts2schema;
178 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
179 && $wgDBmwschema !== 'mediawiki'
180 && preg_match( '/^\w+$/', $wgDBmwschema )
181 && preg_match( '/^\w+$/', $wgDBts2schema )
182 ) {
183 $safeschema = $this->quote_ident($wgDBmwschema);
184 $safeschema2 = $this->quote_ident($wgDBts2schema);
185 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
186 }
187
188 return $this->mConn;
189 }
190
191 function makeConnectionString( $vars ) {
192 $s = '';
193 foreach ( $vars as $name => $value ) {
194 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
195 }
196 return $s;
197 }
198
199
200 function initial_setup($password, $dbName) {
201 // If this is the initial connection, setup the schema stuff and possibly create the user
202 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
203
204 print "<li>Checking the version of Postgres...";
205 $version = $this->getServerVersion();
206 $PGMINVER = '8.1';
207 if ($version < $PGMINVER) {
208 print "<b>FAILED</b>. Required version is $PGMINVER. You have $version</li>\n";
209 dieout("</ul>");
210 }
211 print "version $this->numeric_version is OK.</li>\n";
212
213 $safeuser = $this->quote_ident($wgDBuser);
214 // Are we connecting as a superuser for the first time?
215 if ($wgDBsuperuser) {
216 // Are we really a superuser? Check out our rights
217 $SQL = "SELECT
218 CASE WHEN usesuper IS TRUE THEN
219 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
220 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
221 END AS rights
222 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
223 $rows = $this->numRows($res = $this->doQuery($SQL));
224 if (!$rows) {
225 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
226 dieout('</ul>');
227 }
228 $perms = pg_fetch_result($res, 0, 0);
229
230 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
231 $rows = $this->numRows($this->doQuery($SQL));
232 if ($rows) {
233 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
234 }
235 else {
236 if ($perms != 1 and $perms != 3) {
237 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
238 print 'Please use a different Postgres user.</li>';
239 dieout('</ul>');
240 }
241 print "<li>Creating user <b>$wgDBuser</b>...";
242 $safepass = $this->addQuotes($wgDBpassword);
243 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
244 $this->doQuery($SQL);
245 print "OK</li>\n";
246 }
247 // User now exists, check out the database
248 if ($dbName != $wgDBname) {
249 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
250 $rows = $this->numRows($this->doQuery($SQL));
251 if ($rows) {
252 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
253 }
254 else {
255 if ($perms < 2) {
256 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
257 print 'Please use a different Postgres user.</li>';
258 dieout('</ul>');
259 }
260 print "<li>Creating database <b>$wgDBname</b>...";
261 $safename = $this->quote_ident($wgDBname);
262 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
263 $this->doQuery($SQL);
264 print "OK</li>\n";
265 // Hopefully tsearch2 and plpgsql are in template1...
266 }
267
268 // Reconnect to check out tsearch2 rights for this user
269 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
270
271 $hstring="";
272 if ($this->mServer!=false && $this->mServer!="") {
273 $hstring="host=$this->mServer ";
274 }
275 if ($this->mPort!=false && $this->mPort!="") {
276 $hstring .= "port=$this->mPort ";
277 }
278
279 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
280 if ( $this->mConn == false ) {
281 print "<b>FAILED TO CONNECT!</b></li>";
282 dieout("</ul>");
283 }
284 print "OK</li>\n";
285 }
286
287 if ($this->numeric_version < 8.3) {
288 // Tsearch2 checks
289 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
290 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
291 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
292 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
293 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
294 dieout("</ul>");
295 }
296 print "OK</li>\n";
297 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
298 foreach (array('cfg','cfgmap','dict','parser') as $table) {
299 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
300 $this->doQuery($SQL);
301 }
302 print "OK</li>\n";
303 }
304
305 // Setup the schema for this user if needed
306 $result = $this->schemaExists($wgDBmwschema);
307 $safeschema = $this->quote_ident($wgDBmwschema);
308 if (!$result) {
309 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
310 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
311 if (!$result) {
312 print "<b>FAILED</b>.</li>\n";
313 dieout("</ul>");
314 }
315 print "OK</li>\n";
316 }
317 else {
318 print "<li>Schema already exists, explicitly granting rights...\n";
319 $safeschema2 = $this->addQuotes($wgDBmwschema);
320 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
321 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
322 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
323 "AND p.relkind IN ('r','S','v')\n";
324 $SQL .= "UNION\n";
325 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
326 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
327 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
328 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
329 $res = $this->doQuery($SQL);
330 if (!$res) {
331 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
332 dieout("</ul>");
333 }
334 $this->doQuery("SET search_path = $safeschema");
335 $rows = $this->numRows($res);
336 while ($rows) {
337 $rows--;
338 $this->doQuery(pg_fetch_result($res, $rows, 0));
339 }
340 print "OK</li>";
341 }
342
343 // Install plpgsql if needed
344 $this->setup_plpgsql();
345
346 $wgDBsuperuser = '';
347 return true; // Reconnect as regular user
348
349 } // end superuser
350
351 if (!defined('POSTGRES_SEARCHPATH')) {
352
353 if ($this->numeric_version < 8.3) {
354 // Do we have the basic tsearch2 table?
355 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
356 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
357 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
358 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
359 print " for instructions.</li>\n";
360 dieout("</ul>");
361 }
362 print "OK</li>\n";
363
364 // Does this user have the rights to the tsearch2 tables?
365 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
366 print "<li>Checking tsearch2 permissions...";
367 // Let's check all four, just to be safe
368 error_reporting( 0 );
369 $ts2tables = array('cfg','cfgmap','dict','parser');
370 $safetsschema = $this->quote_ident($wgDBts2schema);
371 foreach ( $ts2tables AS $tname ) {
372 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
373 $res = $this->doQuery($SQL);
374 if (!$res) {
375 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
376 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
377 dieout("</ul>");
378 }
379 }
380 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
381 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
382 $res = $this->doQuery($SQL);
383 error_reporting( E_ALL );
384 if (!$res) {
385 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
386 dieout("</ul>");
387 }
388 print "OK</li>";
389
390 // Will the current locale work? Can we force it to?
391 print "<li>Verifying tsearch2 locale with $ctype...";
392 $rows = $this->numRows($res);
393 $resetlocale = 0;
394 if (!$rows) {
395 print "<b>not found</b></li>\n";
396 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
397 $resetlocale = 1;
398 }
399 else {
400 $tsname = pg_fetch_result($res, 0, 0);
401 if ($tsname != 'default') {
402 print "<b>not set to default ($tsname)</b>";
403 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
404 $resetlocale = 1;
405 }
406 }
407 if ($resetlocale) {
408 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
409 $res = $this->doQuery($SQL);
410 if (!$res) {
411 print "<b>FAILED</b>. ";
412 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
413 dieout("</ul>");
414 }
415 print "OK</li>";
416 }
417
418 // Final test: try out a simple tsearch2 query
419 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
420 $res = $this->doQuery($SQL);
421 if (!$res) {
422 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
423 dieout("</ul>");
424 }
425 print "OK</li>";
426 }
427
428 // Install plpgsql if needed
429 $this->setup_plpgsql();
430
431 // Does the schema already exist? Who owns it?
432 $result = $this->schemaExists($wgDBmwschema);
433 if (!$result) {
434 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
435 error_reporting( 0 );
436 $safeschema = $this->quote_ident($wgDBmwschema);
437 $result = $this->doQuery("CREATE SCHEMA $safeschema");
438 error_reporting( E_ALL );
439 if (!$result) {
440 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
441 "You can try making them the owner of the database, or try creating the schema with a ".
442 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
443 dieout("</ul>");
444 }
445 print "OK</li>\n";
446 }
447 else if ($result != $wgDBuser) {
448 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
449 }
450 else {
451 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
452 }
453
454 // Always return GMT time to accomodate the existing integer-based timestamp assumption
455 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
456 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
457 $result = pg_query($this->mConn, $SQL);
458 if (!$result) {
459 print "<b>FAILED</b>.</li>\n";
460 dieout("</ul>");
461 }
462 print "OK</li>\n";
463 // Set for the rest of this session
464 $SQL = "SET timezone = 'GMT'";
465 $result = pg_query($this->mConn, $SQL);
466 if (!$result) {
467 print "<li>Failed to set timezone</li>\n";
468 dieout("</ul>");
469 }
470
471 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
472 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
473 $result = pg_query($this->mConn, $SQL);
474 if (!$result) {
475 print "<b>FAILED</b>.</li>\n";
476 dieout("</ul>");
477 }
478 print "OK</li>\n";
479 // Set for the rest of this session
480 $SQL = "SET datestyle = 'ISO, YMD'";
481 $result = pg_query($this->mConn, $SQL);
482 if (!$result) {
483 print "<li>Failed to set datestyle</li>\n";
484 dieout("</ul>");
485 }
486
487 // Fix up the search paths if needed
488 print "<li>Setting the search path for user \"$wgDBuser\" ...";
489 $path = $this->quote_ident($wgDBmwschema);
490 if ($wgDBts2schema !== $wgDBmwschema)
491 $path .= ", ". $this->quote_ident($wgDBts2schema);
492 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
493 $path .= ", public";
494 $SQL = "ALTER USER $safeuser SET search_path = $path";
495 $result = pg_query($this->mConn, $SQL);
496 if (!$result) {
497 print "<b>FAILED</b>.</li>\n";
498 dieout("</ul>");
499 }
500 print "OK</li>\n";
501 // Set for the rest of this session
502 $SQL = "SET search_path = $path";
503 $result = pg_query($this->mConn, $SQL);
504 if (!$result) {
505 print "<li>Failed to set search_path</li>\n";
506 dieout("</ul>");
507 }
508 define( "POSTGRES_SEARCHPATH", $path );
509 }
510 }
511
512
513 function setup_plpgsql() {
514 print "<li>Checking for Pl/Pgsql ...";
515 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
516 $rows = $this->numRows($this->doQuery($SQL));
517 if ($rows < 1) {
518 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
519 print "not installed. Attempting to install Pl/Pgsql ...";
520 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
521 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
522 $rows = $this->numRows($this->doQuery($SQL));
523 if ($rows >= 1) {
524 $olde = error_reporting(0);
525 error_reporting($olde - E_WARNING);
526 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
527 error_reporting($olde);
528 if (!$result) {
529 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
530 dieout("</ul>");
531 }
532 }
533 else {
534 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
535 dieout("</ul>");
536 }
537 }
538 print "OK</li>\n";
539 }
540
541
542 /**
543 * Closes a database connection, if it is open
544 * Returns success, true if already closed
545 */
546 function close() {
547 $this->mOpened = false;
548 if ( $this->mConn ) {
549 return pg_close( $this->mConn );
550 } else {
551 return true;
552 }
553 }
554
555 function doQuery( $sql ) {
556 if (function_exists('mb_convert_encoding')) {
557 $sql = mb_convert_encoding($sql,'UTF-8');
558 }
559 $this->mLastResult = pg_query( $this->mConn, $sql);
560 $this->mAffectedRows = NULL; // use pg_affected_rows(mLastResult)
561 return $this->mLastResult;
562 }
563
564 function queryIgnore( $sql, $fname = '' ) {
565 return $this->query( $sql, $fname, true );
566 }
567
568 function freeResult( $res ) {
569 if ( $res instanceof ResultWrapper ) {
570 $res = $res->result;
571 }
572 if ( !@pg_free_result( $res ) ) {
573 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
574 }
575 }
576
577 function fetchObject( $res ) {
578 if ( $res instanceof ResultWrapper ) {
579 $res = $res->result;
580 }
581 @$row = pg_fetch_object( $res );
582 # FIXME: HACK HACK HACK HACK debug
583
584 # TODO:
585 # hashar : not sure if the following test really trigger if the object
586 # fetching failed.
587 if( pg_last_error($this->mConn) ) {
588 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
589 }
590 return $row;
591 }
592
593 function fetchRow( $res ) {
594 if ( $res instanceof ResultWrapper ) {
595 $res = $res->result;
596 }
597 @$row = pg_fetch_array( $res );
598 if( pg_last_error($this->mConn) ) {
599 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
600 }
601 return $row;
602 }
603
604 function numRows( $res ) {
605 if ( $res instanceof ResultWrapper ) {
606 $res = $res->result;
607 }
608 @$n = pg_num_rows( $res );
609 if( pg_last_error($this->mConn) ) {
610 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
611 }
612 return $n;
613 }
614 function numFields( $res ) {
615 if ( $res instanceof ResultWrapper ) {
616 $res = $res->result;
617 }
618 return pg_num_fields( $res );
619 }
620 function fieldName( $res, $n ) {
621 if ( $res instanceof ResultWrapper ) {
622 $res = $res->result;
623 }
624 return pg_field_name( $res, $n );
625 }
626
627 /**
628 * This must be called after nextSequenceVal
629 */
630 function insertId() {
631 return $this->mInsertId;
632 }
633
634 function dataSeek( $res, $row ) {
635 if ( $res instanceof ResultWrapper ) {
636 $res = $res->result;
637 }
638 return pg_result_seek( $res, $row );
639 }
640
641 function lastError() {
642 if ( $this->mConn ) {
643 return pg_last_error();
644 }
645 else {
646 return "No database connection";
647 }
648 }
649 function lastErrno() {
650 return pg_last_error() ? 1 : 0;
651 }
652
653 function affectedRows() {
654 if ( !is_null( $this->mAffectedRows ) ) {
655 // Forced result for simulated queries
656 return $this->mAffectedRows;
657 }
658 if( empty( $this->mLastResult ) )
659 return 0;
660 return pg_affected_rows( $this->mLastResult );
661 }
662
663 /**
664 * Estimate rows in dataset
665 * Returns estimated count, based on EXPLAIN output
666 * This is not necessarily an accurate estimate, so use sparingly
667 * Returns -1 if count cannot be found
668 * Takes same arguments as Database::select()
669 */
670
671 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
672 $options['EXPLAIN'] = true;
673 $res = $this->select( $table, $vars, $conds, $fname, $options );
674 $rows = -1;
675 if ( $res ) {
676 $row = $this->fetchRow( $res );
677 $count = array();
678 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
679 $rows = $count[1];
680 }
681 $this->freeResult($res);
682 }
683 return $rows;
684 }
685
686
687 /**
688 * Returns information about an index
689 * If errors are explicitly ignored, returns NULL on failure
690 */
691 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
692 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
693 $res = $this->query( $sql, $fname );
694 if ( !$res ) {
695 return NULL;
696 }
697 while ( $row = $this->fetchObject( $res ) ) {
698 if ( $row->indexname == $index ) {
699 return $row;
700 }
701 }
702 return false;
703 }
704
705 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
706 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
707 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
708 $res = $this->query( $sql, $fname );
709 if ( !$res )
710 return NULL;
711 while ($row = $this->fetchObject( $res ))
712 return true;
713 return false;
714
715 }
716
717 /**
718 * INSERT wrapper, inserts an array into a table
719 *
720 * $args may be a single associative array, or an array of these with numeric keys,
721 * for multi-row insert (Postgres version 8.2 and above only).
722 *
723 * @param array $table String: Name of the table to insert to.
724 * @param array $args Array: Items to insert into the table.
725 * @param array $fname String: Name of the function, for profiling
726 * @param mixed $options String or Array. Valid options: IGNORE
727 *
728 * @return bool Success of insert operation. IGNORE always returns true.
729 */
730 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
731 global $wgDBversion;
732
733 if ( !count( $args ) ) {
734 return true;
735 }
736
737 $table = $this->tableName( $table );
738 if (! isset( $wgDBversion ) ) {
739 $wgDBversion = $this->getServerVersion();
740 }
741
742 if ( !is_array( $options ) )
743 $options = array( $options );
744
745 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
746 $multi = true;
747 $keys = array_keys( $args[0] );
748 }
749 else {
750 $multi = false;
751 $keys = array_keys( $args );
752 }
753
754 // If IGNORE is set, we use savepoints to emulate mysql's behavior
755 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
756
757 // If we are not in a transaction, we need to be for savepoint trickery
758 $didbegin = 0;
759 if ( $ignore ) {
760 if (! $this->mTrxLevel) {
761 $this->begin();
762 $didbegin = 1;
763 }
764 $olde = error_reporting( 0 );
765 // For future use, we may want to track the number of actual inserts
766 // Right now, insert (all writes) simply return true/false
767 $numrowsinserted = 0;
768 }
769
770 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
771
772 if ( $multi ) {
773 if ( $wgDBversion >= 8.2 && !$ignore ) {
774 $first = true;
775 foreach ( $args as $row ) {
776 if ( $first ) {
777 $first = false;
778 } else {
779 $sql .= ',';
780 }
781 $sql .= '(' . $this->makeList( $row ) . ')';
782 }
783 $res = (bool)$this->query( $sql, $fname, $ignore );
784 }
785 else {
786 $res = true;
787 $origsql = $sql;
788 foreach ( $args as $row ) {
789 $tempsql = $origsql;
790 $tempsql .= '(' . $this->makeList( $row ) . ')';
791
792 if ( $ignore ) {
793 pg_query($this->mConn, "SAVEPOINT $ignore");
794 }
795
796 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
797
798 if ( $ignore ) {
799 $bar = pg_last_error();
800 if ($bar != false) {
801 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
802 }
803 else {
804 pg_query( $this->mConn, "RELEASE $ignore" );
805 $numrowsinserted++;
806 }
807 }
808
809 // If any of them fail, we fail overall for this function call
810 // Note that this will be ignored if IGNORE is set
811 if (! $tempres)
812 $res = false;
813 }
814 }
815 }
816 else {
817 // Not multi, just a lone insert
818 if ( $ignore ) {
819 pg_query($this->mConn, "SAVEPOINT $ignore");
820 }
821
822 $sql .= '(' . $this->makeList( $args ) . ')';
823 $res = (bool)$this->query( $sql, $fname, $ignore );
824 if ( $ignore ) {
825 $bar = pg_last_error();
826 if ($bar != false) {
827 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
828 }
829 else {
830 pg_query( $this->mConn, "RELEASE $ignore" );
831 $numrowsinserted++;
832 }
833 }
834 }
835 if ( $ignore ) {
836 $olde = error_reporting( $olde );
837 if ($didbegin) {
838 $this->commit();
839 }
840
841 // Set the affected row count for the whole operation
842 $this->mAffectedRows = $numrowsinserted;
843
844 // IGNORE always returns true
845 return true;
846 }
847
848
849 return $res;
850
851 }
852
853 function tableName( $name ) {
854 # Replace reserved words with better ones
855 switch( $name ) {
856 case 'user':
857 return 'mwuser';
858 case 'text':
859 return 'pagecontent';
860 default:
861 return $name;
862 }
863 }
864
865 /**
866 * Return the next in a sequence, save the value for retrieval via insertId()
867 */
868 function nextSequenceValue( $seqName ) {
869 $safeseq = preg_replace( "/'/", "''", $seqName );
870 $res = $this->query( "SELECT nextval('$safeseq')" );
871 $row = $this->fetchRow( $res );
872 $this->mInsertId = $row[0];
873 $this->freeResult( $res );
874 return $this->mInsertId;
875 }
876
877 /**
878 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
879 */
880 function currentSequenceValue( $seqName ) {
881 $safeseq = preg_replace( "/'/", "''", $seqName );
882 $res = $this->query( "SELECT currval('$safeseq')" );
883 $row = $this->fetchRow( $res );
884 $currval = $row[0];
885 $this->freeResult( $res );
886 return $currval;
887 }
888
889 /**
890 * Postgres does not have a "USE INDEX" clause, so return an empty string
891 */
892 function useIndexClause( $index ) {
893 return '';
894 }
895
896 # REPLACE query wrapper
897 # Postgres simulates this with a DELETE followed by INSERT
898 # $row is the row to insert, an associative array
899 # $uniqueIndexes is an array of indexes. Each element may be either a
900 # field name or an array of field names
901 #
902 # It may be more efficient to leave off unique indexes which are unlikely to collide.
903 # However if you do this, you run the risk of encountering errors which wouldn't have
904 # occurred in MySQL
905 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
906 $table = $this->tableName( $table );
907
908 if (count($rows)==0) {
909 return;
910 }
911
912 # Single row case
913 if ( !is_array( reset( $rows ) ) ) {
914 $rows = array( $rows );
915 }
916
917 foreach( $rows as $row ) {
918 # Delete rows which collide
919 if ( $uniqueIndexes ) {
920 $sql = "DELETE FROM $table WHERE ";
921 $first = true;
922 foreach ( $uniqueIndexes as $index ) {
923 if ( $first ) {
924 $first = false;
925 $sql .= "(";
926 } else {
927 $sql .= ') OR (';
928 }
929 if ( is_array( $index ) ) {
930 $first2 = true;
931 foreach ( $index as $col ) {
932 if ( $first2 ) {
933 $first2 = false;
934 } else {
935 $sql .= ' AND ';
936 }
937 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
938 }
939 } else {
940 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
941 }
942 }
943 $sql .= ')';
944 $this->query( $sql, $fname );
945 }
946
947 # Now insert the row
948 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
949 $this->makeList( $row, LIST_COMMA ) . ')';
950 $this->query( $sql, $fname );
951 }
952 }
953
954 # DELETE where the condition is a join
955 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
956 if ( !$conds ) {
957 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
958 }
959
960 $delTable = $this->tableName( $delTable );
961 $joinTable = $this->tableName( $joinTable );
962 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
963 if ( $conds != '*' ) {
964 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
965 }
966 $sql .= ')';
967
968 $this->query( $sql, $fname );
969 }
970
971 # Returns the size of a text field, or -1 for "unlimited"
972 function textFieldSize( $table, $field ) {
973 $table = $this->tableName( $table );
974 $sql = "SELECT t.typname as ftype,a.atttypmod as size
975 FROM pg_class c, pg_attribute a, pg_type t
976 WHERE relname='$table' AND a.attrelid=c.oid AND
977 a.atttypid=t.oid and a.attname='$field'";
978 $res =$this->query($sql);
979 $row=$this->fetchObject($res);
980 if ($row->ftype=="varchar") {
981 $size=$row->size-4;
982 } else {
983 $size=$row->size;
984 }
985 $this->freeResult( $res );
986 return $size;
987 }
988
989 function lowPriorityOption() {
990 return '';
991 }
992
993 function limitResult($sql, $limit, $offset=false) {
994 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
995 }
996
997 /**
998 * Returns an SQL expression for a simple conditional.
999 * Uses CASE on Postgres
1000 *
1001 * @param string $cond SQL expression which will result in a boolean value
1002 * @param string $trueVal SQL expression to return if true
1003 * @param string $falseVal SQL expression to return if false
1004 * @return string SQL fragment
1005 */
1006 function conditional( $cond, $trueVal, $falseVal ) {
1007 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1008 }
1009
1010 function wasDeadlock() {
1011 return $this->lastErrno() == '40P01';
1012 }
1013
1014 function timestamp( $ts=0 ) {
1015 return wfTimestamp(TS_POSTGRES,$ts);
1016 }
1017
1018 /**
1019 * Return aggregated value function call
1020 */
1021 function aggregateValue ($valuedata,$valuename='value') {
1022 return $valuedata;
1023 }
1024
1025
1026 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1027 // Ignore errors during error handling to avoid infinite recursion
1028 $ignore = $this->ignoreErrors( true );
1029 $this->mErrorCount++;
1030
1031 if ($ignore || $tempIgnore) {
1032 wfDebug("SQL ERROR (ignored): $error\n");
1033 $this->ignoreErrors( $ignore );
1034 }
1035 else {
1036 $message = "A database error has occurred\n" .
1037 "Query: $sql\n" .
1038 "Function: $fname\n" .
1039 "Error: $errno $error\n";
1040 throw new DBUnexpectedError($this, $message);
1041 }
1042 }
1043
1044 /**
1045 * @return string wikitext of a link to the server software's web site
1046 */
1047 function getSoftwareLink() {
1048 return "[http://www.postgresql.org/ PostgreSQL]";
1049 }
1050
1051 /**
1052 * @return string Version information from the database
1053 */
1054 function getServerVersion() {
1055 $versionInfo = pg_version( $this->mConn );
1056 return $versionInfo['server'];
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