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