Ignore all but errors when importing.
[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 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
250 dieout("</ul>");
251 }
252 print "OK</li>\n";
253
254 ## Does the schema already exist? Who owns it?
255 $result = $this->schemaExists($wgDBmwschema);
256 if (!$result) {
257 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
258 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
259 if (!$result) {
260 print "<b>FAILED</b>.</li>\n";
261 dieout("</ul>");
262 }
263 print "OK</li>\n";
264 }
265 else if ($result != $user) {
266 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
267 }
268 else {
269 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
270 }
271
272 ## Fix up the search paths if needed
273 print "<li>Setting the search path for user \"$user\" ...";
274 $path = $this->quote_ident($wgDBmwschema);
275 if ($wgDBts2schema !== $wgDBmwschema)
276 $path .= ", ". $this->quote_ident($wgDBts2schema);
277 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
278 $path .= ", public";
279 $SQL = "ALTER USER $safeuser SET search_path = $path";
280 $result = pg_query($this->mConn, $SQL);
281 if (!$result) {
282 print "<b>FAILED</b>.</li>\n";
283 dieout("</ul>");
284 }
285 print "OK</li>\n";
286 ## Set for the rest of this session
287 $SQL = "SET search_path = $path";
288 $result = pg_query($this->mConn, $SQL);
289 if (!$result) {
290 print "<li>Failed to set search_path</li>\n";
291 dieout("</ul>");
292 }
293 define( "POSTGRES_SEARCHPATH", $path );
294 }}
295
296 global $wgCommandLineMode;
297 ## If called from the command-line (e.g. importDump), only show errors
298 if ($wgCommandLineMode) {
299 $this->doQuery("SET client_min_messages = 'ERROR'");
300 }
301
302 return $this->mConn;
303 }
304
305 /**
306 * Closes a database connection, if it is open
307 * Returns success, true if already closed
308 */
309 function close() {
310 $this->mOpened = false;
311 if ( $this->mConn ) {
312 return pg_close( $this->mConn );
313 } else {
314 return true;
315 }
316 }
317
318 function doQuery( $sql ) {
319 return $this->mLastResult=pg_query( $this->mConn , $sql);
320 }
321
322 function queryIgnore( $sql, $fname = '' ) {
323 return $this->query( $sql, $fname, true );
324 }
325
326 function freeResult( $res ) {
327 if ( !@pg_free_result( $res ) ) {
328 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
329 }
330 }
331
332 function fetchObject( $res ) {
333 @$row = pg_fetch_object( $res );
334 # FIXME: HACK HACK HACK HACK debug
335
336 # TODO:
337 # hashar : not sure if the following test really trigger if the object
338 # fetching failled.
339 if( pg_last_error($this->mConn) ) {
340 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
341 }
342 return $row;
343 }
344
345 function fetchRow( $res ) {
346 @$row = pg_fetch_array( $res );
347 if( pg_last_error($this->mConn) ) {
348 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
349 }
350 return $row;
351 }
352
353 function numRows( $res ) {
354 @$n = pg_num_rows( $res );
355 if( pg_last_error($this->mConn) ) {
356 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
357 }
358 return $n;
359 }
360 function numFields( $res ) { return pg_num_fields( $res ); }
361 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
362
363 /**
364 * This must be called after nextSequenceVal
365 */
366 function insertId() {
367 return $this->mInsertId;
368 }
369
370 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
371 function lastError() {
372 if ( $this->mConn ) {
373 return pg_last_error();
374 }
375 else {
376 return "No database connection";
377 }
378 }
379 function lastErrno() {
380 return pg_last_error() ? 1 : 0;
381 }
382
383 function affectedRows() {
384 return pg_affected_rows( $this->mLastResult );
385 }
386
387 /**
388 * Returns information about an index
389 * If errors are explicitly ignored, returns NULL on failure
390 */
391 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
392 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
393 $res = $this->query( $sql, $fname );
394 if ( !$res ) {
395 return NULL;
396 }
397
398 while ( $row = $this->fetchObject( $res ) ) {
399 if ( $row->indexname == $index ) {
400 return $row;
401 }
402 }
403 return false;
404 }
405
406 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
407 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
408 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
409 $res = $this->query( $sql, $fname );
410 if ( !$res )
411 return NULL;
412 while ($row = $this->fetchObject( $res ))
413 return true;
414 return false;
415
416 }
417
418 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
419 # Postgres doesn't support options
420 # We have a go at faking one of them
421 # TODO: DELAYED, LOW_PRIORITY
422
423 if ( !is_array($options))
424 $options = array($options);
425
426 if ( in_array( 'IGNORE', $options ) )
427 $oldIgnore = $this->ignoreErrors( true );
428
429 # IGNORE is performed using single-row inserts, ignoring errors in each
430 # FIXME: need some way to distiguish between key collision and other types of error
431 $oldIgnore = $this->ignoreErrors( true );
432 if ( !is_array( reset( $a ) ) ) {
433 $a = array( $a );
434 }
435 foreach ( $a as $row ) {
436 parent::insert( $table, $row, $fname, array() );
437 }
438 $this->ignoreErrors( $oldIgnore );
439 $retVal = true;
440
441 if ( in_array( 'IGNORE', $options ) )
442 $this->ignoreErrors( $oldIgnore );
443
444 return $retVal;
445 }
446
447 function tableName( $name ) {
448 # Replace reserved words with better ones
449 switch( $name ) {
450 case 'user':
451 return 'mwuser';
452 case 'text':
453 return 'pagecontent';
454 default:
455 return $name;
456 }
457 }
458
459 /**
460 * Return the next in a sequence, save the value for retrieval via insertId()
461 */
462 function nextSequenceValue( $seqName ) {
463 $safeseq = preg_replace( "/'/", "''", $seqName );
464 $res = $this->query( "SELECT nextval('$safeseq')" );
465 $row = $this->fetchRow( $res );
466 $this->mInsertId = $row[0];
467 $this->freeResult( $res );
468 return $this->mInsertId;
469 }
470
471 /**
472 * Postgres does not have a "USE INDEX" clause, so return an empty string
473 */
474 function useIndexClause( $index ) {
475 return '';
476 }
477
478 # REPLACE query wrapper
479 # Postgres simulates this with a DELETE followed by INSERT
480 # $row is the row to insert, an associative array
481 # $uniqueIndexes is an array of indexes. Each element may be either a
482 # field name or an array of field names
483 #
484 # It may be more efficient to leave off unique indexes which are unlikely to collide.
485 # However if you do this, you run the risk of encountering errors which wouldn't have
486 # occurred in MySQL
487 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
488 $table = $this->tableName( $table );
489
490 if (count($rows)==0) {
491 return;
492 }
493
494 # Single row case
495 if ( !is_array( reset( $rows ) ) ) {
496 $rows = array( $rows );
497 }
498
499 foreach( $rows as $row ) {
500 # Delete rows which collide
501 if ( $uniqueIndexes ) {
502 $sql = "DELETE FROM $table WHERE ";
503 $first = true;
504 foreach ( $uniqueIndexes as $index ) {
505 if ( $first ) {
506 $first = false;
507 $sql .= "(";
508 } else {
509 $sql .= ') OR (';
510 }
511 if ( is_array( $index ) ) {
512 $first2 = true;
513 foreach ( $index as $col ) {
514 if ( $first2 ) {
515 $first2 = false;
516 } else {
517 $sql .= ' AND ';
518 }
519 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
520 }
521 } else {
522 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
523 }
524 }
525 $sql .= ')';
526 $this->query( $sql, $fname );
527 }
528
529 # Now insert the row
530 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
531 $this->makeList( $row, LIST_COMMA ) . ')';
532 $this->query( $sql, $fname );
533 }
534 }
535
536 # DELETE where the condition is a join
537 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
538 if ( !$conds ) {
539 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
540 }
541
542 $delTable = $this->tableName( $delTable );
543 $joinTable = $this->tableName( $joinTable );
544 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
545 if ( $conds != '*' ) {
546 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
547 }
548 $sql .= ')';
549
550 $this->query( $sql, $fname );
551 }
552
553 # Returns the size of a text field, or -1 for "unlimited"
554 function textFieldSize( $table, $field ) {
555 $table = $this->tableName( $table );
556 $sql = "SELECT t.typname as ftype,a.atttypmod as size
557 FROM pg_class c, pg_attribute a, pg_type t
558 WHERE relname='$table' AND a.attrelid=c.oid AND
559 a.atttypid=t.oid and a.attname='$field'";
560 $res =$this->query($sql);
561 $row=$this->fetchObject($res);
562 if ($row->ftype=="varchar") {
563 $size=$row->size-4;
564 } else {
565 $size=$row->size;
566 }
567 $this->freeResult( $res );
568 return $size;
569 }
570
571 function lowPriorityOption() {
572 return '';
573 }
574
575 function limitResult($sql, $limit,$offset) {
576 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
577 }
578
579 /**
580 * Returns an SQL expression for a simple conditional.
581 * Uses CASE on Postgres
582 *
583 * @param string $cond SQL expression which will result in a boolean value
584 * @param string $trueVal SQL expression to return if true
585 * @param string $falseVal SQL expression to return if false
586 * @return string SQL fragment
587 */
588 function conditional( $cond, $trueVal, $falseVal ) {
589 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
590 }
591
592 # FIXME: actually detecting deadlocks might be nice
593 function wasDeadlock() {
594 return false;
595 }
596
597 function timestamp( $ts=0 ) {
598 return wfTimestamp(TS_POSTGRES,$ts);
599 }
600
601 /**
602 * Return aggregated value function call
603 */
604 function aggregateValue ($valuedata,$valuename='value') {
605 return $valuedata;
606 }
607
608
609 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
610 $message = "A database error has occurred\n" .
611 "Query: $sql\n" .
612 "Function: $fname\n" .
613 "Error: $errno $error\n";
614 throw new DBUnexpectedError($this, $message);
615 }
616
617 /**
618 * @return string wikitext of a link to the server software's web site
619 */
620 function getSoftwareLink() {
621 return "[http://www.postgresql.org/ PostgreSQL]";
622 }
623
624 /**
625 * @return string Version information from the database
626 */
627 function getServerVersion() {
628 $res = $this->query( "SELECT version()" );
629 $row = $this->fetchRow( $res );
630 $version = $row[0];
631 $this->freeResult( $res );
632 return $version;
633 }
634
635
636 /**
637 * Query whether a given table exists (in the given schema, or the default mw one if not given)
638 */
639 function tableExists( $table, $schema = false ) {
640 global $wgDBmwschema;
641 if (! $schema )
642 $schema = $wgDBmwschema;
643 $etable = preg_replace("/'/", "''", $table);
644 $eschema = preg_replace("/'/", "''", $schema);
645 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
646 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
647 $res = $this->query( $SQL );
648 $count = $res ? pg_num_rows($res) : 0;
649 if ($res)
650 $this->freeResult( $res );
651 return $count;
652 }
653
654
655 /**
656 * Query whether a given schema exists. Returns the name of the owner
657 */
658 function schemaExists( $schema ) {
659 $eschema = preg_replace("/'/", "''", $schema);
660 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
661 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
662 $res = $this->query( $SQL );
663 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
664 if ($res)
665 $this->freeResult($res);
666 return $owner;
667 }
668
669 /**
670 * Query whether a given column exists in the mediawiki schema
671 */
672 function fieldExists( $table, $field ) {
673 global $wgDBmwschema;
674 $etable = preg_replace("/'/", "''", $table);
675 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
676 $ecol = preg_replace("/'/", "''", $field);
677 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
678 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
679 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
680 $res = $this->query( $SQL );
681 $count = $res ? pg_num_rows($res) : 0;
682 if ($res)
683 $this->freeResult( $res );
684 return $count;
685 }
686
687 function fieldInfo( $table, $field ) {
688 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
689 $type = pg_field_type( $res, 0 );
690 return $type;
691 }
692
693 function begin( $fname = 'DatabasePostgrs::begin' ) {
694 $this->query( 'BEGIN', $fname );
695 $this->mTrxLevel = 1;
696 }
697 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
698 return true;
699 }
700 function commit( $fname = 'DatabasePostgres::commit' ) {
701 $this->query( 'COMMIT', $fname );
702 $this->mTrxLevel = 0;
703 }
704
705 /* Not even sure why this is used in the main codebase... */
706 function limitResultForUpdate($sql, $num) {
707 return $sql;
708 }
709
710 function setup_database() {
711 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
712
713 dbsource( "../maintenance/postgres/tables.sql", $this);
714
715 ## Update version information
716 $mwv = $this->addQuotes($wgVersion);
717 $pgv = $this->addQuotes($this->getServerVersion());
718 $pgu = $this->addQuotes($this->mUser);
719 $mws = $this->addQuotes($wgDBmwschema);
720 $tss = $this->addQuotes($wgDBts2schema);
721 $pgp = $this->addQuotes($wgDBport);
722 $dbn = $this->addQuotes($this->mDBname);
723
724 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
725 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
726 "WHERE type = 'Creation'";
727 $this->query($SQL);
728
729 ## Avoid the non-standard "REPLACE INTO" syntax
730 $f = fopen( "../maintenance/interwiki.sql", 'r' );
731 if ($f == false ) {
732 dieout( "<li>Could not find the interwiki.sql file");
733 }
734 ## We simply assume it is already empty as we have just created it
735 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
736 while ( ! feof( $f ) ) {
737 $line = fgets($f,1024);
738 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
739 continue;
740 }
741 $yesno = $matches[2]; ## ? "'true'" : "'false'";
742 $this->query("$SQL $matches[1],$matches[2])");
743 }
744 print " (table interwiki successfully populated)...\n";
745 }
746
747 function encodeBlob($b) {
748 return array('bytea',pg_escape_bytea($b));
749 }
750 function decodeBlob($b) {
751 return pg_unescape_bytea( $b );
752 }
753
754 function strencode( $s ) { ## Should not be called by us
755 return pg_escape_string( $s );
756 }
757
758 function addQuotes( $s ) {
759 if ( is_null( $s ) ) {
760 return 'NULL';
761 } else if (is_array( $s )) { ## Assume it is bytea data
762 return "E'$s[1]'";
763 }
764 return "'" . pg_escape_string($s) . "'";
765 return "E'" . pg_escape_string($s) . "'";
766 }
767
768 function quote_ident( $s ) {
769 return '"' . preg_replace( '/"/', '""', $s) . '"';
770 }
771
772 }
773
774 ?>