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