Localization update for he.
[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 __construct($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( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $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 }
730 return $rows;
731 }
732
733
734 /**
735 * Returns information about an index
736 * If errors are explicitly ignored, returns NULL on failure
737 */
738 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
739 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
740 $res = $this->query( $sql, $fname );
741 if ( !$res ) {
742 return null;
743 }
744 while ( $row = $this->fetchObject( $res ) ) {
745 if ( $row->indexname == $this->indexName( $index ) ) {
746 return $row;
747 }
748 }
749 return false;
750 }
751
752 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
753 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
754 " AND indexdef LIKE 'CREATE UNIQUE%(" .
755 $this->strencode( $this->indexName( $index ) ) .
756 ")'";
757 $res = $this->query( $sql, $fname );
758 if ( !$res )
759 return null;
760 while ($row = $this->fetchObject( $res ))
761 return true;
762 return false;
763
764 }
765
766 /**
767 * INSERT wrapper, inserts an array into a table
768 *
769 * $args may be a single associative array, or an array of these with numeric keys,
770 * for multi-row insert (Postgres version 8.2 and above only).
771 *
772 * @param $table String: Name of the table to insert to.
773 * @param $args Array: Items to insert into the table.
774 * @param $fname String: Name of the function, for profiling
775 * @param $options String or Array. Valid options: IGNORE
776 *
777 * @return bool Success of insert operation. IGNORE always returns true.
778 */
779 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
780 if ( !count( $args ) ) {
781 return true;
782 }
783
784 $table = $this->tableName( $table );
785 if (! isset( $this->numeric_version ) ) {
786 $this->getServerVersion();
787 }
788
789 if ( !is_array( $options ) )
790 $options = array( $options );
791
792 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
793 $multi = true;
794 $keys = array_keys( $args[0] );
795 }
796 else {
797 $multi = false;
798 $keys = array_keys( $args );
799 }
800
801 // If IGNORE is set, we use savepoints to emulate mysql's behavior
802 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
803
804 // If we are not in a transaction, we need to be for savepoint trickery
805 $didbegin = 0;
806 if ( $ignore ) {
807 if (! $this->mTrxLevel) {
808 $this->begin();
809 $didbegin = 1;
810 }
811 $olde = error_reporting( 0 );
812 // For future use, we may want to track the number of actual inserts
813 // Right now, insert (all writes) simply return true/false
814 $numrowsinserted = 0;
815 }
816
817 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
818
819 if ( $multi ) {
820 if ( $this->numeric_version >= 8.2 && !$ignore ) {
821 $first = true;
822 foreach ( $args as $row ) {
823 if ( $first ) {
824 $first = false;
825 } else {
826 $sql .= ',';
827 }
828 $sql .= '(' . $this->makeList( $row ) . ')';
829 }
830 $res = (bool)$this->query( $sql, $fname, $ignore );
831 }
832 else {
833 $res = true;
834 $origsql = $sql;
835 foreach ( $args as $row ) {
836 $tempsql = $origsql;
837 $tempsql .= '(' . $this->makeList( $row ) . ')';
838
839 if ( $ignore ) {
840 pg_query($this->mConn, "SAVEPOINT $ignore");
841 }
842
843 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
844
845 if ( $ignore ) {
846 $bar = pg_last_error();
847 if ($bar != false) {
848 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
849 }
850 else {
851 pg_query( $this->mConn, "RELEASE $ignore" );
852 $numrowsinserted++;
853 }
854 }
855
856 // If any of them fail, we fail overall for this function call
857 // Note that this will be ignored if IGNORE is set
858 if (! $tempres)
859 $res = false;
860 }
861 }
862 }
863 else {
864 // Not multi, just a lone insert
865 if ( $ignore ) {
866 pg_query($this->mConn, "SAVEPOINT $ignore");
867 }
868
869 $sql .= '(' . $this->makeList( $args ) . ')';
870 $res = (bool)$this->query( $sql, $fname, $ignore );
871 if ( $ignore ) {
872 $bar = pg_last_error();
873 if ($bar != false) {
874 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
875 }
876 else {
877 pg_query( $this->mConn, "RELEASE $ignore" );
878 $numrowsinserted++;
879 }
880 }
881 }
882 if ( $ignore ) {
883 $olde = error_reporting( $olde );
884 if ($didbegin) {
885 $this->commit();
886 }
887
888 // Set the affected row count for the whole operation
889 $this->mAffectedRows = $numrowsinserted;
890
891 // IGNORE always returns true
892 return true;
893 }
894
895
896 return $res;
897
898 }
899
900 /**
901 * INSERT SELECT wrapper
902 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
903 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
904 * $conds may be "*" to copy the whole table
905 * srcTable may be an array of tables.
906 * @todo FIXME: implement this a little better (seperate select/insert)?
907 */
908 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
909 $insertOptions = array(), $selectOptions = array() )
910 {
911 $destTable = $this->tableName( $destTable );
912
913 // If IGNORE is set, we use savepoints to emulate mysql's behavior
914 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
915
916 if( is_array( $insertOptions ) ) {
917 $insertOptions = implode( ' ', $insertOptions );
918 }
919 if( !is_array( $selectOptions ) ) {
920 $selectOptions = array( $selectOptions );
921 }
922 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
923 if( is_array( $srcTable ) ) {
924 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
925 } else {
926 $srcTable = $this->tableName( $srcTable );
927 }
928
929 // If we are not in a transaction, we need to be for savepoint trickery
930 $didbegin = 0;
931 if ( $ignore ) {
932 if( !$this->mTrxLevel ) {
933 $this->begin();
934 $didbegin = 1;
935 }
936 $olde = error_reporting( 0 );
937 $numrowsinserted = 0;
938 pg_query( $this->mConn, "SAVEPOINT $ignore");
939 }
940
941 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
942 " SELECT $startOpts " . implode( ',', $varMap ) .
943 " FROM $srcTable $useIndex";
944
945 if ( $conds != '*') {
946 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
947 }
948
949 $sql .= " $tailOpts";
950
951 $res = (bool)$this->query( $sql, $fname, $ignore );
952 if( $ignore ) {
953 $bar = pg_last_error();
954 if( $bar != false ) {
955 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
956 } else {
957 pg_query( $this->mConn, "RELEASE $ignore" );
958 $numrowsinserted++;
959 }
960 $olde = error_reporting( $olde );
961 if( $didbegin ) {
962 $this->commit();
963 }
964
965 // Set the affected row count for the whole operation
966 $this->mAffectedRows = $numrowsinserted;
967
968 // IGNORE always returns true
969 return true;
970 }
971
972 return $res;
973 }
974
975 function tableName( $name ) {
976 # Replace reserved words with better ones
977 switch( $name ) {
978 case 'user':
979 return 'mwuser';
980 case 'text':
981 return 'pagecontent';
982 default:
983 return $name;
984 }
985 }
986
987 /**
988 * Return the next in a sequence, save the value for retrieval via insertId()
989 */
990 function nextSequenceValue( $seqName ) {
991 $safeseq = preg_replace( "/'/", "''", $seqName );
992 $res = $this->query( "SELECT nextval('$safeseq')" );
993 $row = $this->fetchRow( $res );
994 $this->mInsertId = $row[0];
995 return $this->mInsertId;
996 }
997
998 /**
999 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1000 */
1001 function currentSequenceValue( $seqName ) {
1002 $safeseq = preg_replace( "/'/", "''", $seqName );
1003 $res = $this->query( "SELECT currval('$safeseq')" );
1004 $row = $this->fetchRow( $res );
1005 $currval = $row[0];
1006 return $currval;
1007 }
1008
1009 # REPLACE query wrapper
1010 # Postgres simulates this with a DELETE followed by INSERT
1011 # $row is the row to insert, an associative array
1012 # $uniqueIndexes is an array of indexes. Each element may be either a
1013 # field name or an array of field names
1014 #
1015 # It may be more efficient to leave off unique indexes which are unlikely to collide.
1016 # However if you do this, you run the risk of encountering errors which wouldn't have
1017 # occurred in MySQL
1018 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1019 $table = $this->tableName( $table );
1020
1021 if (count($rows)==0) {
1022 return;
1023 }
1024
1025 # Single row case
1026 if ( !is_array( reset( $rows ) ) ) {
1027 $rows = array( $rows );
1028 }
1029
1030 foreach( $rows as $row ) {
1031 # Delete rows which collide
1032 if ( $uniqueIndexes ) {
1033 $sql = "DELETE FROM $table WHERE ";
1034 $first = true;
1035 foreach ( $uniqueIndexes as $index ) {
1036 if ( $first ) {
1037 $first = false;
1038 $sql .= "(";
1039 } else {
1040 $sql .= ') OR (';
1041 }
1042 if ( is_array( $index ) ) {
1043 $first2 = true;
1044 foreach ( $index as $col ) {
1045 if ( $first2 ) {
1046 $first2 = false;
1047 } else {
1048 $sql .= ' AND ';
1049 }
1050 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1051 }
1052 } else {
1053 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1054 }
1055 }
1056 $sql .= ')';
1057 $this->query( $sql, $fname );
1058 }
1059
1060 # Now insert the row
1061 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
1062 $this->makeList( $row, LIST_COMMA ) . ')';
1063 $this->query( $sql, $fname );
1064 }
1065 }
1066
1067 # DELETE where the condition is a join
1068 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1069 if ( !$conds ) {
1070 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1071 }
1072
1073 $delTable = $this->tableName( $delTable );
1074 $joinTable = $this->tableName( $joinTable );
1075 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1076 if ( $conds != '*' ) {
1077 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1078 }
1079 $sql .= ')';
1080
1081 $this->query( $sql, $fname );
1082 }
1083
1084 # Returns the size of a text field, or -1 for "unlimited"
1085 function textFieldSize( $table, $field ) {
1086 $table = $this->tableName( $table );
1087 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1088 FROM pg_class c, pg_attribute a, pg_type t
1089 WHERE relname='$table' AND a.attrelid=c.oid AND
1090 a.atttypid=t.oid and a.attname='$field'";
1091 $res =$this->query($sql);
1092 $row=$this->fetchObject($res);
1093 if ($row->ftype=="varchar") {
1094 $size=$row->size-4;
1095 } else {
1096 $size=$row->size;
1097 }
1098 return $size;
1099 }
1100
1101 function limitResult($sql, $limit, $offset=false) {
1102 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
1103 }
1104
1105 function wasDeadlock() {
1106 return $this->lastErrno() == '40P01';
1107 }
1108
1109 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1110 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1111 }
1112
1113 function timestamp( $ts=0 ) {
1114 return wfTimestamp(TS_POSTGRES,$ts);
1115 }
1116
1117 /**
1118 * Return aggregated value function call
1119 */
1120 function aggregateValue ($valuedata,$valuename='value') {
1121 return $valuedata;
1122 }
1123
1124
1125 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1126 // Ignore errors during error handling to avoid infinite recursion
1127 $ignore = $this->ignoreErrors( true );
1128 $this->mErrorCount++;
1129
1130 if ($ignore || $tempIgnore) {
1131 wfDebug("SQL ERROR (ignored): $error\n");
1132 $this->ignoreErrors( $ignore );
1133 }
1134 else {
1135 $message = "A database error has occurred\n" .
1136 "Query: $sql\n" .
1137 "Function: $fname\n" .
1138 "Error: $errno $error\n";
1139 throw new DBUnexpectedError($this, $message);
1140 }
1141 }
1142
1143 /**
1144 * @return string wikitext of a link to the server software's web site
1145 */
1146 public static function getSoftwareLink() {
1147 return "[http://www.postgresql.org/ PostgreSQL]";
1148 }
1149
1150 /**
1151 * @return string Version information from the database
1152 */
1153 function getServerVersion() {
1154 if ( !isset( $this->numeric_version ) ) {
1155 $versionInfo = pg_version( $this->mConn );
1156 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1157 // Old client, abort install
1158 $this->numeric_version = '7.3 or earlier';
1159 } elseif ( isset( $versionInfo['server'] ) ) {
1160 // Normal client
1161 $this->numeric_version = $versionInfo['server'];
1162 } else {
1163 // Bug 16937: broken pgsql extension from PHP<5.3
1164 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1165 }
1166 }
1167 return $this->numeric_version;
1168 }
1169
1170 /**
1171 * Query whether a given relation exists (in the given schema, or the
1172 * default mw one if not given)
1173 */
1174 function relationExists( $table, $types, $schema = false ) {
1175 global $wgDBmwschema;
1176 if ( !is_array( $types ) )
1177 $types = array( $types );
1178 if ( !$schema )
1179 $schema = $wgDBmwschema;
1180 $etable = $this->addQuotes( $table );
1181 $eschema = $this->addQuotes( $schema );
1182 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1183 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1184 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1185 $res = $this->query( $SQL );
1186 $count = $res ? $res->numRows() : 0;
1187 return $count ? true : false;
1188 }
1189
1190 /*
1191 * For backward compatibility, this function checks both tables and
1192 * views.
1193 */
1194 function tableExists( $table, $schema = false ) {
1195 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1196 }
1197
1198 function sequenceExists( $sequence, $schema = false ) {
1199 return $this->relationExists( $sequence, 'S', $schema );
1200 }
1201
1202 function triggerExists( $table, $trigger ) {
1203 global $wgDBmwschema;
1204
1205 $q = <<<SQL
1206 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1207 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1208 AND tgrelid=pg_class.oid
1209 AND nspname=%s AND relname=%s AND tgname=%s
1210 SQL;
1211 $res = $this->query(sprintf($q,
1212 $this->addQuotes($wgDBmwschema),
1213 $this->addQuotes($table),
1214 $this->addQuotes($trigger)));
1215 if (!$res)
1216 return null;
1217 $rows = $res->numRows();
1218 return $rows;
1219 }
1220
1221 function ruleExists( $table, $rule ) {
1222 global $wgDBmwschema;
1223 $exists = $this->selectField("pg_rules", "rulename",
1224 array( "rulename" => $rule,
1225 "tablename" => $table,
1226 "schemaname" => $wgDBmwschema ) );
1227 return $exists === $rule;
1228 }
1229
1230 function constraintExists( $table, $constraint ) {
1231 global $wgDBmwschema;
1232 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1233 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1234 $this->addQuotes($wgDBmwschema),
1235 $this->addQuotes($table),
1236 $this->addQuotes($constraint));
1237 $res = $this->query($SQL);
1238 if (!$res)
1239 return null;
1240 $rows = $res->numRows();
1241 return $rows;
1242 }
1243
1244 /**
1245 * Query whether a given schema exists. Returns the name of the owner
1246 */
1247 function schemaExists( $schema ) {
1248 $eschema = preg_replace("/'/", "''", $schema);
1249 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1250 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1251 $res = $this->query( $SQL );
1252 if ( $res && $res->numRows() ) {
1253 $row = $res->fetchObject();
1254 $owner = $row->rolname;
1255 } else {
1256 $owner = false;
1257 }
1258 return $owner;
1259 }
1260
1261 function fieldInfo( $table, $field ) {
1262 return PostgresField::fromText($this, $table, $field);
1263 }
1264
1265 /**
1266 * pg_field_type() wrapper
1267 */
1268 function fieldType( $res, $index ) {
1269 if ( $res instanceof ResultWrapper ) {
1270 $res = $res->result;
1271 }
1272 return pg_field_type( $res, $index );
1273 }
1274
1275 /* Not even sure why this is used in the main codebase... */
1276 function limitResultForUpdate( $sql, $num ) {
1277 return $sql;
1278 }
1279
1280 function setup_database() {
1281 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1282
1283 // Make sure that we can write to the correct schema
1284 // If not, Postgres will happily and silently go to the next search_path item
1285 $ctest = "mediawiki_test_table";
1286 $safeschema = $this->quote_ident($wgDBmwschema);
1287 if ($this->tableExists($ctest, $wgDBmwschema)) {
1288 $this->doQuery("DROP TABLE $safeschema.$ctest");
1289 }
1290 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1291 $olde = error_reporting( 0 );
1292 $res = $this->doQuery($SQL);
1293 error_reporting( $olde );
1294 if (!$res) {
1295 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1296 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1297 dieout(""); # Will close the main list <ul> and finish the page.
1298 }
1299 $this->doQuery("DROP TABLE $safeschema.$ctest");
1300
1301 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1302 if ($res === true) {
1303 print " done.</li>\n";
1304 } else {
1305 print " <b>FAILED</b></li>\n";
1306 dieout( htmlspecialchars( $res ) );
1307 }
1308
1309 ## Update version information
1310 $mwv = $this->addQuotes($wgVersion);
1311 $pgv = $this->addQuotes($this->getServerVersion());
1312 $pgu = $this->addQuotes($this->mUser);
1313 $mws = $this->addQuotes($wgDBmwschema);
1314 $tss = $this->addQuotes($wgDBts2schema);
1315 $pgp = $this->addQuotes($wgDBport);
1316 $dbn = $this->addQuotes($this->mDBname);
1317 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1318
1319 echo "<li>Populating interwiki table... ";
1320 ## Avoid the non-standard "REPLACE INTO" syntax
1321 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1322 if ( !$f ) {
1323 print "<b>FAILED</b></li>";
1324 dieout( "Could not find the interwiki.sql file" );
1325 }
1326 ## We simply assume it is already empty as we have just created it
1327 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1328 while ( ! feof( $f ) ) {
1329 $line = fgets($f,1024);
1330 $matches = array();
1331 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1332 continue;
1333 }
1334 $this->query("$SQL $matches[1],$matches[2])");
1335 }
1336 print " successfully populated.</li>\n";
1337
1338 $this->doQuery("COMMIT");
1339 }
1340
1341 function encodeBlob( $b ) {
1342 return new Blob ( pg_escape_bytea( $this->mConn, $b ) ) ;
1343 }
1344
1345 function decodeBlob( $b ) {
1346 if ($b instanceof Blob) {
1347 $b = $b->fetch();
1348 }
1349 return pg_unescape_bytea( $b );
1350 }
1351
1352 function strencode( $s ) { ## Should not be called by us
1353 return pg_escape_string( $this->mConn, $s );
1354 }
1355
1356 function addQuotes( $s ) {
1357 if ( is_null( $s ) ) {
1358 return 'NULL';
1359 } else if ( is_bool( $s ) ) {
1360 return intval( $s );
1361 } else if ($s instanceof Blob) {
1362 return "'".$s->fetch($s)."'";
1363 }
1364 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1365 }
1366
1367 function quote_ident( $s ) {
1368 return '"' . preg_replace( '/"/', '""', $s) . '"';
1369 }
1370
1371 /**
1372 * Postgres specific version of replaceVars.
1373 * Calls the parent version in Database.php
1374 *
1375 * @private
1376 *
1377 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1378 *
1379 * @return string SQL string
1380 */
1381 protected function replaceVars( $ins ) {
1382
1383 $ins = parent::replaceVars( $ins );
1384
1385 if ($this->numeric_version >= 8.3) {
1386 // Thanks for not providing backwards-compatibility, 8.3
1387 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1388 }
1389
1390 if ($this->numeric_version <= 8.1) { // Our minimum version
1391 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1392 }
1393
1394 return $ins;
1395 }
1396
1397 /**
1398 * Various select options
1399 *
1400 * @private
1401 *
1402 * @param $options Array: an associative array of options to be turned into
1403 * an SQL query, valid keys are listed in the function.
1404 * @return array
1405 */
1406 function makeSelectOptions( $options ) {
1407 $preLimitTail = $postLimitTail = '';
1408 $startOpts = $useIndex = '';
1409
1410 $noKeyOptions = array();
1411 foreach ( $options as $key => $option ) {
1412 if ( is_numeric( $key ) ) {
1413 $noKeyOptions[$option] = true;
1414 }
1415 }
1416
1417 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1418 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1419 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1420
1421 //if (isset($options['LIMIT'])) {
1422 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1423 // isset($options['OFFSET']) ? $options['OFFSET']
1424 // : false);
1425 //}
1426
1427 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1428 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1429 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1430
1431 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1432 }
1433
1434 function setFakeMaster( $enabled = true ) {}
1435
1436 function getDBname() {
1437 return $this->mDBname;
1438 }
1439
1440 function getServer() {
1441 return $this->mServer;
1442 }
1443
1444 function buildConcat( $stringList ) {
1445 return implode( ' || ', $stringList );
1446 }
1447
1448 public function getSearchEngine() {
1449 return "SearchPostgres";
1450 }
1451 } // end DatabasePostgres class