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