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