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