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