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