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