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