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