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