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