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