3c0a094ae6fbfa48b0c264bf3d51d56e602ef27b
[lhc/web/wiklou.git] / includes / DatabasePostgres.php
1 <?php
2
3 /**
4 * This is the Postgres database abstraction layer.
5 *
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
8 * Database class.
9 *
10 */
11
12 class DatabasePostgres extends Database {
13 var $mInsertId = NULL;
14 var $mLastResult = NULL;
15 var $numeric_version = NULL;
16
17 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
18 $failFunction = false, $flags = 0 )
19 {
20
21 global $wgOut;
22 # Can't get a reference if it hasn't been set yet
23 if ( !isset( $wgOut ) ) {
24 $wgOut = NULL;
25 }
26 $this->mOut =& $wgOut;
27 $this->mFailFunction = $failFunction;
28 $this->mCascadingDeletes = true;
29 $this->mCleanupTriggers = true;
30 $this->mStrictIPs = true;
31 $this->mFlags = $flags;
32 $this->open( $server, $user, $password, $dbName);
33
34 }
35
36 function realTimestamps() {
37 return true;
38 }
39
40 function implicitGroupby() {
41 return false;
42 }
43
44 function searchableIPs() {
45 return true;
46 }
47
48 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
49 $failFunction = false, $flags = 0)
50 {
51 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
52 }
53
54 /**
55 * Usually aborts on failure
56 * If the failFunction is set to a non-zero integer, returns success
57 */
58 function open( $server, $user, $password, $dbName ) {
59 # Test for Postgres support, to avoid suppressed fatal error
60 if ( !function_exists( 'pg_connect' ) ) {
61 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" );
62 }
63
64 global $wgDBport;
65
66 if (!strlen($user)) { ## e.g. the class is being loaded
67 return;
68 }
69
70 $this->close();
71 $this->mServer = $server;
72 $port = $wgDBport;
73 $this->mUser = $user;
74 $this->mPassword = $password;
75 $this->mDBname = $dbName;
76
77 $hstring="";
78 if ($server!=false && $server!="") {
79 $hstring="host=$server ";
80 }
81 if ($port!=false && $port!="") {
82 $hstring .= "port=$port ";
83 }
84
85
86 error_reporting( E_ALL );
87 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
88
89 if ( $this->mConn == false ) {
90 wfDebug( "DB connection error\n" );
91 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
92 wfDebug( $this->lastError()."\n" );
93 return false;
94 }
95
96 $this->mOpened = true;
97 ## If this is the initial connection, setup the schema stuff and possibly create the user
98 if (defined('MEDIAWIKI_INSTALL')) {
99 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
100 $wgDBts2schema;
101
102 print "<li>Checking the version of Postgres...";
103 $version = $this->getServerVersion();
104 $PGMINVER = "8.1";
105 if ($this->numeric_version < $PGMINVER) {
106 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
107 dieout("</ul>");
108 }
109 print "version $this->numeric_version is OK.</li>\n";
110
111 $safeuser = $this->quote_ident($wgDBuser);
112 ## Are we connecting as a superuser for the first time?
113 if ($wgDBsuperuser) {
114 ## Are we really a superuser? Check out our rights
115 $SQL = "SELECT
116 CASE WHEN usesuper IS TRUE THEN
117 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
118 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
119 END AS rights
120 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
121 $rows = $this->numRows($res = $this->doQuery($SQL));
122 if (!$rows) {
123 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
124 dieout('</ul>');
125 }
126 $perms = pg_fetch_result($res, 0, 0);
127
128 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
129 $rows = $this->numRows($this->doQuery($SQL));
130 if ($rows) {
131 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
132 }
133 else {
134 if ($perms != 1 and $perms != 3) {
135 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
136 print 'Please use a different Postgres user.</li>';
137 dieout('</ul>');
138 }
139 print "<li>Creating user <b>$wgDBuser</b>...";
140 $safepass = $this->addQuotes($wgDBpassword);
141 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
142 $this->doQuery($SQL);
143 print "OK</li>\n";
144 }
145 ## User now exists, check out the database
146 if ($dbName != $wgDBname) {
147 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
148 $rows = $this->numRows($this->doQuery($SQL));
149 if ($rows) {
150 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
151 }
152 else {
153 if ($perms < 2) {
154 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
155 print 'Please use a different Postgres user.</li>';
156 dieout('</ul>');
157 }
158 print "<li>Creating database <b>$wgDBname</b>...";
159 $safename = $this->quote_ident($wgDBname);
160 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
161 $this->doQuery($SQL);
162 print "OK</li>\n";
163 ## Hopefully tsearch2 and plpgsql are in template1...
164 }
165
166 ## Reconnect to check out tsearch2 rights for this user
167 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
168 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
169 if ( $this->mConn == false ) {
170 print "<b>FAILED TO CONNECT!</b></li>";
171 dieout("</ul>");
172 }
173 print "OK</li>\n";
174 }
175
176 ## Tsearch2 checks
177 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
178 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
179 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
180 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
181 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
182 dieout("</ul>");
183 }
184 print "OK</li>\n";
185 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
186 foreach (array('cfg','cfgmap','dict','parser') as $table) {
187 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
188 $this->doQuery($SQL);
189 }
190 print "OK</li>\n";
191
192
193 ## Setup the schema for this user if needed
194 $result = $this->schemaExists($wgDBmwschema);
195 $safeschema = $this->quote_ident($wgDBmwschema);
196 if (!$result) {
197 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
198 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
199 if (!$result) {
200 print "<b>FAILED</b>.</li>\n";
201 dieout("</ul>");
202 }
203 print "OK</li>\n";
204 }
205 else {
206 print "<li>Schema already exists, explicitly granting rights...\n";
207 $safeschema2 = $this->addQuotes($wgDBmwschema);
208 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
209 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
210 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
211 "AND p.relkind IN ('r','S','v')\n";
212 $SQL .= "UNION\n";
213 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
214 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
215 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
216 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
217 $res = $this->doQuery($SQL);
218 if (!$res) {
219 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
220 dieout("</ul>");
221 }
222 $this->doQuery("SET search_path = $safeschema");
223 $rows = $this->numRows($res);
224 while ($rows) {
225 $rows--;
226 $this->doQuery(pg_fetch_result($res, $rows, 0));
227 }
228 print "OK</li>";
229 }
230
231 $wgDBsuperuser = '';
232 return true; ## Reconnect as regular user
233
234 } ## end superuser
235
236 if (!defined('POSTGRES_SEARCHPATH')) {
237
238 ## Do we have the basic tsearch2 table?
239 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
240 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
241 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
242 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
243 print " for instructions.</li>\n";
244 dieout("</ul>");
245 }
246 print "OK</li>\n";
247
248 ## Does this user have the rights to the tsearch2 tables?
249 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
250 print "<li>Checking tsearch2 permissions...";
251 ## Let's check all four, just to be safe
252 error_reporting( 0 );
253 $ts2tables = array('cfg','cfgmap','dict','parser');
254 foreach ( $ts2tables AS $tname ) {
255 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
256 $res = $this->doQuery($SQL);
257 if (!$res) {
258 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
259 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
260 dieout("</ul>");
261 }
262 }
263 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
264 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
265 $res = $this->doQuery($SQL);
266 error_reporting( E_ALL );
267 if (!$res) {
268 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
269 dieout("</ul>");
270 }
271 print "OK</li>";
272
273 ## Will the current locale work? Can we force it to?
274 print "<li>Verifying tsearch2 locale with $ctype...";
275 $rows = $this->numRows($res);
276 $resetlocale = 0;
277 if (!$rows) {
278 print "<b>not found</b></li>\n";
279 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
280 $resetlocale = 1;
281 }
282 else {
283 $tsname = pg_fetch_result($res, 0, 0);
284 if ($tsname != 'default') {
285 print "<b>not set to default ($tsname)</b>";
286 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
287 $resetlocale = 1;
288 }
289 }
290 if ($resetlocale) {
291 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
292 $res = $this->doQuery($SQL);
293 if (!$res) {
294 print "<b>FAILED</b>. ";
295 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
296 dieout("</ul>");
297 }
298 print "OK</li>";
299 }
300
301 ## Final test: try out a simple tsearch2 query
302 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
303 $res = $this->doQuery($SQL);
304 if (!$res) {
305 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
306 dieout("</ul>");
307 }
308 print "OK</li>";
309
310 ## Do we have plpgsql installed?
311 print "<li>Checking for Pl/Pgsql ...";
312 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
313 $rows = $this->numRows($this->doQuery($SQL));
314 if ($rows < 1) {
315 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
316 print "not installed. Attempting to install Pl/Pgsql ...";
317 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
318 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
319 $rows = $this->numRows($this->doQuery($SQL));
320 if ($rows >= 1) {
321 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
322 if (!$result) {
323 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
324 dieout("</ul>");
325 }
326 }
327 else {
328 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
329 dieout("</ul>");
330 }
331 }
332 print "OK</li>\n";
333
334 ## Does the schema already exist? Who owns it?
335 $result = $this->schemaExists($wgDBmwschema);
336 if (!$result) {
337 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
338 error_reporting( 0 );
339 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
340 error_reporting( E_ALL );
341 if (!$result) {
342 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
343 "You can try making them the owner of the database, or try creating the schema with a ".
344 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
345 dieout("</ul>");
346 }
347 print "OK</li>\n";
348 }
349 else if ($result != $user) {
350 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
351 }
352 else {
353 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
354 }
355
356 ## Fix up the search paths if needed
357 print "<li>Setting the search path for user \"$user\" ...";
358 $path = $this->quote_ident($wgDBmwschema);
359 if ($wgDBts2schema !== $wgDBmwschema)
360 $path .= ", ". $this->quote_ident($wgDBts2schema);
361 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
362 $path .= ", public";
363 $SQL = "ALTER USER $safeuser SET search_path = $path";
364 $result = pg_query($this->mConn, $SQL);
365 if (!$result) {
366 print "<b>FAILED</b>.</li>\n";
367 dieout("</ul>");
368 }
369 print "OK</li>\n";
370 ## Set for the rest of this session
371 $SQL = "SET search_path = $path";
372 $result = pg_query($this->mConn, $SQL);
373 if (!$result) {
374 print "<li>Failed to set search_path</li>\n";
375 dieout("</ul>");
376 }
377 define( "POSTGRES_SEARCHPATH", $path );
378 }}
379
380 global $wgCommandLineMode;
381 ## If called from the command-line (e.g. importDump), only show errors
382 if ($wgCommandLineMode) {
383 $this->doQuery("SET client_min_messages = 'ERROR'");
384 }
385
386 return $this->mConn;
387 }
388
389 /**
390 * Closes a database connection, if it is open
391 * Returns success, true if already closed
392 */
393 function close() {
394 $this->mOpened = false;
395 if ( $this->mConn ) {
396 return pg_close( $this->mConn );
397 } else {
398 return true;
399 }
400 }
401
402 function doQuery( $sql ) {
403 return $this->mLastResult=pg_query( $this->mConn , $sql);
404 }
405
406 function queryIgnore( $sql, $fname = '' ) {
407 return $this->query( $sql, $fname, true );
408 }
409
410 function freeResult( $res ) {
411 if ( !@pg_free_result( $res ) ) {
412 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
413 }
414 }
415
416 function fetchObject( $res ) {
417 @$row = pg_fetch_object( $res );
418 # FIXME: HACK HACK HACK HACK debug
419
420 # TODO:
421 # hashar : not sure if the following test really trigger if the object
422 # fetching failled.
423 if( pg_last_error($this->mConn) ) {
424 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
425 }
426 return $row;
427 }
428
429 function fetchRow( $res ) {
430 @$row = pg_fetch_array( $res );
431 if( pg_last_error($this->mConn) ) {
432 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
433 }
434 return $row;
435 }
436
437 function numRows( $res ) {
438 @$n = pg_num_rows( $res );
439 if( pg_last_error($this->mConn) ) {
440 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
441 }
442 return $n;
443 }
444 function numFields( $res ) { return pg_num_fields( $res ); }
445 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
446
447 /**
448 * This must be called after nextSequenceVal
449 */
450 function insertId() {
451 return $this->mInsertId;
452 }
453
454 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
455 function lastError() {
456 if ( $this->mConn ) {
457 return pg_last_error();
458 }
459 else {
460 return "No database connection";
461 }
462 }
463 function lastErrno() {
464 return pg_last_error() ? 1 : 0;
465 }
466
467 function affectedRows() {
468 return pg_affected_rows( $this->mLastResult );
469 }
470
471 /**
472 * Returns information about an index
473 * If errors are explicitly ignored, returns NULL on failure
474 */
475 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
476 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
477 $res = $this->query( $sql, $fname );
478 if ( !$res ) {
479 return NULL;
480 }
481
482 while ( $row = $this->fetchObject( $res ) ) {
483 if ( $row->indexname == $index ) {
484 return $row;
485
486 // BUG: !!!! This code needs to be synced up with database.php
487
488 }
489 }
490 return false;
491 }
492
493 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
494 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
495 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
496 $res = $this->query( $sql, $fname );
497 if ( !$res )
498 return NULL;
499 while ($row = $this->fetchObject( $res ))
500 return true;
501 return false;
502
503 }
504
505 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
506 # Postgres doesn't support options
507 # We have a go at faking one of them
508 # TODO: DELAYED, LOW_PRIORITY
509
510 if ( !is_array($options))
511 $options = array($options);
512
513 if ( in_array( 'IGNORE', $options ) )
514 $oldIgnore = $this->ignoreErrors( true );
515
516 # IGNORE is performed using single-row inserts, ignoring errors in each
517 # FIXME: need some way to distiguish between key collision and other types of error
518 $oldIgnore = $this->ignoreErrors( true );
519 if ( !is_array( reset( $a ) ) ) {
520 $a = array( $a );
521 }
522 foreach ( $a as $row ) {
523 parent::insert( $table, $row, $fname, array() );
524 }
525 $this->ignoreErrors( $oldIgnore );
526 $retVal = true;
527
528 if ( in_array( 'IGNORE', $options ) )
529 $this->ignoreErrors( $oldIgnore );
530
531 return $retVal;
532 }
533
534 function tableName( $name ) {
535 # Replace reserved words with better ones
536 switch( $name ) {
537 case 'user':
538 return 'mwuser';
539 case 'text':
540 return 'pagecontent';
541 default:
542 return $name;
543 }
544 }
545
546 /**
547 * Return the next in a sequence, save the value for retrieval via insertId()
548 */
549 function nextSequenceValue( $seqName ) {
550 $safeseq = preg_replace( "/'/", "''", $seqName );
551 $res = $this->query( "SELECT nextval('$safeseq')" );
552 $row = $this->fetchRow( $res );
553 $this->mInsertId = $row[0];
554 $this->freeResult( $res );
555 return $this->mInsertId;
556 }
557
558 /**
559 * Postgres does not have a "USE INDEX" clause, so return an empty string
560 */
561 function useIndexClause( $index ) {
562 return '';
563 }
564
565 # REPLACE query wrapper
566 # Postgres simulates this with a DELETE followed by INSERT
567 # $row is the row to insert, an associative array
568 # $uniqueIndexes is an array of indexes. Each element may be either a
569 # field name or an array of field names
570 #
571 # It may be more efficient to leave off unique indexes which are unlikely to collide.
572 # However if you do this, you run the risk of encountering errors which wouldn't have
573 # occurred in MySQL
574 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
575 $table = $this->tableName( $table );
576
577 if (count($rows)==0) {
578 return;
579 }
580
581 # Single row case
582 if ( !is_array( reset( $rows ) ) ) {
583 $rows = array( $rows );
584 }
585
586 foreach( $rows as $row ) {
587 # Delete rows which collide
588 if ( $uniqueIndexes ) {
589 $sql = "DELETE FROM $table WHERE ";
590 $first = true;
591 foreach ( $uniqueIndexes as $index ) {
592 if ( $first ) {
593 $first = false;
594 $sql .= "(";
595 } else {
596 $sql .= ') OR (';
597 }
598 if ( is_array( $index ) ) {
599 $first2 = true;
600 foreach ( $index as $col ) {
601 if ( $first2 ) {
602 $first2 = false;
603 } else {
604 $sql .= ' AND ';
605 }
606 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
607 }
608 } else {
609 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
610 }
611 }
612 $sql .= ')';
613 $this->query( $sql, $fname );
614 }
615
616 # Now insert the row
617 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
618 $this->makeList( $row, LIST_COMMA ) . ')';
619 $this->query( $sql, $fname );
620 }
621 }
622
623 # DELETE where the condition is a join
624 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
625 if ( !$conds ) {
626 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
627 }
628
629 $delTable = $this->tableName( $delTable );
630 $joinTable = $this->tableName( $joinTable );
631 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
632 if ( $conds != '*' ) {
633 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
634 }
635 $sql .= ')';
636
637 $this->query( $sql, $fname );
638 }
639
640 # Returns the size of a text field, or -1 for "unlimited"
641 function textFieldSize( $table, $field ) {
642 $table = $this->tableName( $table );
643 $sql = "SELECT t.typname as ftype,a.atttypmod as size
644 FROM pg_class c, pg_attribute a, pg_type t
645 WHERE relname='$table' AND a.attrelid=c.oid AND
646 a.atttypid=t.oid and a.attname='$field'";
647 $res =$this->query($sql);
648 $row=$this->fetchObject($res);
649 if ($row->ftype=="varchar") {
650 $size=$row->size-4;
651 } else {
652 $size=$row->size;
653 }
654 $this->freeResult( $res );
655 return $size;
656 }
657
658 function lowPriorityOption() {
659 return '';
660 }
661
662 function limitResult($sql, $limit,$offset) {
663 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
664 }
665
666 /**
667 * Returns an SQL expression for a simple conditional.
668 * Uses CASE on Postgres
669 *
670 * @param string $cond SQL expression which will result in a boolean value
671 * @param string $trueVal SQL expression to return if true
672 * @param string $falseVal SQL expression to return if false
673 * @return string SQL fragment
674 */
675 function conditional( $cond, $trueVal, $falseVal ) {
676 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
677 }
678
679 function wasDeadlock() {
680 return $this->lastErrno() == '40P01';
681 }
682
683 function timestamp( $ts=0 ) {
684 return wfTimestamp(TS_POSTGRES,$ts);
685 }
686
687 /**
688 * Return aggregated value function call
689 */
690 function aggregateValue ($valuedata,$valuename='value') {
691 return $valuedata;
692 }
693
694
695 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
696 # Ignore errors during error handling to avoid infinite recursion
697 $ignore = $this->ignoreErrors( true );
698 ++$this->mErrorCount;
699
700 if ($ignore || $tempIgnore) {
701 wfDebug("SQL ERROR (ignored): $error\n");
702 $this->ignoreErrors( $ignore );
703 }
704 else {
705 $message = "A database error has occurred\n" .
706 "Query: $sql\n" .
707 "Function: $fname\n" .
708 "Error: $errno $error\n";
709 throw new DBUnexpectedError($this, $message);
710 }
711 }
712
713 /**
714 * @return string wikitext of a link to the server software's web site
715 */
716 function getSoftwareLink() {
717 return "[http://www.postgresql.org/ PostgreSQL]";
718 }
719
720 /**
721 * @return string Version information from the database
722 */
723 function getServerVersion() {
724 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
725 $thisver = array();
726 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
727 die("Could not determine the numeric version from $version!");
728 }
729 $this->numeric_version = $thisver[1];
730 return $version;
731 }
732
733
734 /**
735 * Query whether a given table exists (in the given schema, or the default mw one if not given)
736 */
737 function tableExists( $table, $schema = false ) {
738 global $wgDBmwschema;
739 if (! $schema )
740 $schema = $wgDBmwschema;
741 $etable = preg_replace("/'/", "''", $table);
742 $eschema = preg_replace("/'/", "''", $schema);
743 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
744 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
745 . "AND c.relkind IN ('r','v')";
746 $res = $this->query( $SQL );
747 $count = $res ? pg_num_rows($res) : 0;
748 if ($res)
749 $this->freeResult( $res );
750 return $count;
751 }
752
753
754 /**
755 * Query whether a given schema exists. Returns the name of the owner
756 */
757 function schemaExists( $schema ) {
758 $eschema = preg_replace("/'/", "''", $schema);
759 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
760 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
761 $res = $this->query( $SQL );
762 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
763 if ($res)
764 $this->freeResult($res);
765 return $owner;
766 }
767
768 /**
769 * Query whether a given column exists in the mediawiki schema
770 */
771 function fieldExists( $table, $field ) {
772 global $wgDBmwschema;
773 $etable = preg_replace("/'/", "''", $table);
774 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
775 $ecol = preg_replace("/'/", "''", $field);
776 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
777 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
778 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
779 $res = $this->query( $SQL );
780 $count = $res ? pg_num_rows($res) : 0;
781 if ($res)
782 $this->freeResult( $res );
783 return $count;
784 }
785
786 function fieldInfo( $table, $field ) {
787 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
788 $type = pg_field_type( $res, 0 );
789 return $type;
790 }
791
792 function begin( $fname = 'DatabasePostgres::begin' ) {
793 $this->query( 'BEGIN', $fname );
794 $this->mTrxLevel = 1;
795 }
796 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
797 return true;
798 }
799 function commit( $fname = 'DatabasePostgres::commit' ) {
800 $this->query( 'COMMIT', $fname );
801 $this->mTrxLevel = 0;
802 }
803
804 /* Not even sure why this is used in the main codebase... */
805 function limitResultForUpdate($sql, $num) {
806 return $sql;
807 }
808
809 function setup_database() {
810 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
811
812 ## Make sure that we can write to the correct schema
813 ## If not, Postgres will happily and silently go to the next search_path item
814 $SQL = "CREATE TABLE $wgDBmwschema.mw_test_table(a int)";
815 error_reporting( 0 );
816 $res = $this->doQuery($SQL);
817 error_reporting( E_ALL );
818 if (!$res) {
819 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"wgDBmwschema\"</li>\n";
820 dieout("</ul>");
821 }
822
823 dbsource( "../maintenance/postgres/tables.sql", $this);
824
825 ## Version-specific stuff
826 if ($this->numeric_version == 8.1) {
827 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
828 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
829 }
830 else {
831 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
832 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
833 }
834
835 ## Update version information
836 $mwv = $this->addQuotes($wgVersion);
837 $pgv = $this->addQuotes($this->getServerVersion());
838 $pgu = $this->addQuotes($this->mUser);
839 $mws = $this->addQuotes($wgDBmwschema);
840 $tss = $this->addQuotes($wgDBts2schema);
841 $pgp = $this->addQuotes($wgDBport);
842 $dbn = $this->addQuotes($this->mDBname);
843 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
844
845 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
846 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
847 "ctype = '$ctype' ".
848 "WHERE type = 'Creation'";
849 $this->query($SQL);
850
851 ## Avoid the non-standard "REPLACE INTO" syntax
852 $f = fopen( "../maintenance/interwiki.sql", 'r' );
853 if ($f == false ) {
854 dieout( "<li>Could not find the interwiki.sql file");
855 }
856 ## We simply assume it is already empty as we have just created it
857 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
858 while ( ! feof( $f ) ) {
859 $line = fgets($f,1024);
860 $matches = array();
861 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
862 continue;
863 }
864 $this->query("$SQL $matches[1],$matches[2])");
865 }
866 print " (table interwiki successfully populated)...\n";
867 }
868
869 function encodeBlob($b) {
870 return array('bytea',pg_escape_bytea($b));
871 }
872 function decodeBlob($b) {
873 return pg_unescape_bytea( $b );
874 }
875
876 function strencode( $s ) { ## Should not be called by us
877 return pg_escape_string( $s );
878 }
879
880 function addQuotes( $s ) {
881 if ( is_null( $s ) ) {
882 return 'NULL';
883 } else if (is_array( $s )) { ## Assume it is bytea data
884 return "E'$s[1]'";
885 }
886 return "'" . pg_escape_string($s) . "'";
887 // Unreachable: return "E'" . pg_escape_string($s) . "'";
888 }
889
890 function quote_ident( $s ) {
891 return '"' . preg_replace( '/"/', '""', $s) . '"';
892 }
893
894 /* For now, does nothing */
895 function selectDB( $db ) {
896 return true;
897 }
898
899 /**
900 * Returns an optional USE INDEX clause to go after the table, and a
901 * string to go at the end of the query
902 *
903 * @private
904 *
905 * @param array $options an associative array of options to be turned into
906 * an SQL query, valid keys are listed in the function.
907 * @return array
908 */
909 function makeSelectOptions( $options ) {
910 $preLimitTail = $postLimitTail = '';
911 $startOpts = '';
912
913 $noKeyOptions = array();
914 foreach ( $options as $key => $option ) {
915 if ( is_numeric( $key ) ) {
916 $noKeyOptions[$option] = true;
917 }
918 }
919
920 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
921 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
922
923 //if (isset($options['LIMIT'])) {
924 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
925 // isset($options['OFFSET']) ? $options['OFFSET']
926 // : false);
927 //}
928
929 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
930 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
931 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
932
933 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
934 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
935 } else {
936 $useIndex = '';
937 }
938
939 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
940 }
941
942 public function setTimeout( $timeout ) {
943 /// @fixme no-op
944 }
945
946 function ping() {
947 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
948 return true;
949 }
950
951
952 } // end DatabasePostgres class
953
954 ?>