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