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