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