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