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