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