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