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