3 * FusionForge PostgreSQL connection layer
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2002, GForge, LLC
7 * Copyright 2009, Roland Mas
8 * Copyright (c) 2011, 2012
9 * Thorsten Glaser <t.glaser@tarent.de>
11 * This file is part of FusionForge. FusionForge is free software;
12 * you can redistribute it and/or modify it under the terms of the
13 * GNU General Public License as published by the Free Software
14 * Foundation; either version 2 of the Licence, or (at your option)
17 * FusionForge is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 * pg_connectstring() - builds a postgres connection string.
29 * Combines the supplied arguments into a valid, specific, postgresql
30 * connection string. It only includes the host and port options
31 * if specified. Without those options, it will use the unix domain
32 * sockets to connect to the postgres server on the local machine.
34 * @author Graham Batty graham@sandworm.ca
35 * @param dbname The database to connect to. Required.
36 * @param user The username used to connect. Required
37 * @param password The password used to connect
38 * @param host The hostname to connect to, if not localhost
39 * @param port The port to connect to, if not 5432
40 * @return string The connection string to pass to pg_connect()
43 function pg_connectstring($dbname, $user, $password = "", $host = "", $port = "") {
45 $string = "dbname=$dbname";
47 $string = "dbname=gforge";
50 $string .= " user=$user";
52 $string .= " password=$password";
54 $string .= " host=$host";
57 $string .= " port=$port";
64 * db_connect() - Connect to the database
65 * Notice the global vars that must be set up
66 * Sets up a global $gfconn variable which is used
67 * in other functions in this library.
69 function db_connect() {
70 global $gfconn,$sys_db_use_replication,$sys_dbreaddb,$sys_dbreadhost;
73 // Connect to primary database
75 if (function_exists("pg_pconnect")) {
76 $gfconn = pg_pconnect(pg_connectstring(forge_get_config('database_name'), forge_get_config('database_user'), forge_get_config('database_password'), forge_get_config('database_host'), forge_get_config('database_port')));
78 print forge_get_config ('forge_name')." Could Not Connect to Database: ".db_error();
82 print("function pg_pconnect doesn't exist: no postgresql interface");
87 // If any replication is configured, connect
89 if ($sys_db_use_replication) {
90 $gfconn2 = pg_pconnect(pg_connectstring($sys_dbreaddb, forge_get_config('database_user'), forge_get_config('database_password'), $sys_dbreadhost, $sys_dbreadport));
96 // Now map the physical database connections to the
97 // "virtual" list that is used to distribute load in db_query()
99 define('SYS_DB_PRIMARY', $gfconn);
100 define('SYS_DB_STATS', $gfconn2);
101 define('SYS_DB_TROVE', $gfconn2);
102 define('SYS_DB_SEARCH', $gfconn2);
104 $res = db_query_params ('SELECT set_config($1, $2, false)',
105 array('default_text_search_config',
108 // Register top-level "finally" handler to abort current
109 // transaction in case of error
110 register_shutdown_function("system_cleanup");
114 * db_connect_if_needed() - Set up the DB connection if it's unset
116 function db_connect_if_needed() {
118 if (!isset ($gfconn)) {
123 function db_switcher($dbserver = NULL) {
126 case 'SYS_DB_PRIMARY': {
127 $dbconn = SYS_DB_PRIMARY;
130 case 'SYS_DB_STATS': {
131 $dbconn = SYS_DB_STATS;
134 case 'SYS_DB_TROVE': {
135 $dbconn = SYS_DB_TROVE;
138 case 'SYS_DB_SEARCH': {
139 $dbconn = SYS_DB_SEARCH;
143 // Cope with $dbserver already being a connection
144 if (pg_dbname($dbserver)) {
147 $dbconn = SYS_DB_PRIMARY;
156 * db_query_from_file() - Query the database, from a file.
158 * @param string File that contains the SQL statements.
159 * @param int How many rows do you want returned.
160 * @param int Of matching rows, return only rows starting here.
161 * @param int ability to spread load to multiple db servers.
162 * @return int result set handle.
164 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=NULL) {
165 global $sysdebug_dbquery, $sysdebug_dberrors;
167 db_connect_if_needed();
168 $dbconn = db_switcher($dbserver) ;
173 $qstring = file_get_contents($file);
175 if ($sysdebug_dbquery) {
177 "aborted call of db_query_from_file():",
178 "Cannot read file: " . $file .
179 "\n\n" . debug_string_backtrace());
180 } elseif ($sysdebug_dberrors) {
181 ffDebug("database", "db_query_from_file() aborted (" .
182 "Cannot read file: " . $file . ")");
184 error_log("db_query_from_file(): Cannot read file: " . $file);
188 if (!$limit || !is_numeric($limit) || $limit < 0) {
192 if (!$offset || !is_numeric($offset) || $offset < 0) {
195 $qstring=$qstring." LIMIT $limit OFFSET $offset";
197 $res = @pg_query($dbconn, $qstring);
199 if ($sysdebug_dbquery) {
201 "successful call of db_query_from_file(), SQL: " .
202 $qstring, debug_string_backtrace());
204 } elseif ($sysdebug_dbquery || $sysdebug_dberrors) {
205 ffDebug("database", "db_query_from_file() failed (" .
206 db_error($dbserver) . "), SQL: " . $qstring,
207 $sysdebug_dbquery ? debug_string_backtrace() : false);
209 error_log('SQL: ' . preg_replace('/\n\t+/', ' ', $qstring));
210 error_log('SQL> ' . db_error($dbserver));
216 * db_query_params() - Query the database, with parameters
218 * @param text SQL statement.
219 * @param array parameters
220 * @param int How many rows do you want returned.
221 * @param int Of matching rows, return only rows starting here.
222 * @param int ability to spread load to multiple db servers.
223 * @return int result set handle.
225 function db_query_params($qstring, $params, $limit = '-1', $offset = 0, $dbserver = NULL) {
226 global $sysdebug_dbquery, $sysdebug_dberrors;
228 db_connect_if_needed();
229 $dbconn = db_switcher($dbserver) ;
234 if (!$limit || !is_numeric($limit) || $limit < 0) {
238 if (!$offset || !is_numeric($offset) || $offset < 0) {
241 $qstring=$qstring." LIMIT $limit OFFSET $offset";
244 $res = @pg_query_params($dbconn, $qstring, $params);
246 if ($sysdebug_dbquery) {
248 "successful call of db_query_params():",
249 debug_string_backtrace());
251 } elseif ($sysdebug_dbquery) {
252 ffDebug("database", "failed call of db_query_params():",
253 db_error($dbserver) . "\n\n" . debug_string_backtrace());
254 } elseif ($sysdebug_dberrors) {
255 ffDebug("database", "db_query_params() failed (" .
256 db_error($dbserver) . "), SQL: " . $qstring,
257 print_r(array("params" => $params), 1));
259 error_log('SQL: ' . preg_replace('/\n\t+/', ' ', $qstring));
260 error_log('SQL> ' . db_error($dbserver));
266 * db_query_qpa() - Query the database, with a query+params array
268 * @param array array(query, array(parameters...))
269 * @param int How many rows do you want returned.
270 * @param int Of matching rows, return only rows starting here.
271 * @param int ability to spread load to multiple db servers.
272 * @return int result set handle.
274 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=NULL) {
277 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
281 * db_mquery() - Query the database.
283 * @deprecated since 4.8. Use db_query_params() instead!
285 * @param text SQL statement.
286 * @param int How many rows do you want returned.
287 * @param int Of matching rows, return only rows starting here.
288 * @param int ability to spread load to multiple db servers.
289 * @return int result set handle.
291 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=NULL) {
292 return db_query($qstring, $limit, $offset, $dbserver);
296 * db_more_results() - Check if there are more unprocessed results.
298 * @return bool true if there are more results..
300 function db_more_results() {
305 * db_next_result() - Get the next result from query with multiple statements.
307 * @param string SQL statement
308 * @param int How many rows do you want returned
309 * @param int Of matching rows, return only rows starting here
311 function db_next_result() {
315 /* Current transaction level, private variable */
316 /* FIXME: Having scalar variable for transaction level is
317 no longer correct after multiple database (dbservers) support
318 introduction. However, it is true that in one given PHP
319 script, at most one db is modified, so this works for now. */
320 $_sys_db_transaction_level = 0;
323 * db_begin() - Begin a transaction.
325 * @param constant Database server ('SYS_DB_PRIMARY', 'SYS_DB_STATS', 'SYS_DB_TROVE', 'SYS_DB_SEARCH')
328 function db_begin($dbserver = NULL) {
329 global $_sys_db_transaction_level;
331 // start database transaction only for the top-level
332 // programmatical transaction
333 $_sys_db_transaction_level++;
334 if ($_sys_db_transaction_level == 1) {
335 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
342 * db_commit() - Commit a transaction.
344 * @param constant Database server ('SYS_DB_PRIMARY', 'SYS_DB_STATS', 'SYS_DB_TROVE', 'SYS_DB_SEARCH')
345 * @return true on success/false on failure.
347 function db_commit($dbserver = NULL) {
348 global $_sys_db_transaction_level;
350 // check for transaction stack underflow
351 if ($_sys_db_transaction_level == 0) {
352 echo "COMMIT underflow<br />";
356 // commit database transaction only when top-level
357 // programmatical transaction ends
358 $_sys_db_transaction_level--;
359 if ($_sys_db_transaction_level == 0) {
360 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
367 * db_rollback() - Rollback a transaction.
369 * @param constant Database server ('SYS_DB_PRIMARY', 'SYS_DB_STATS', 'SYS_DB_TROVE', 'SYS_DB_SEARCH')
370 * @return true on success/false on failure.
372 function db_rollback($dbserver = NULL) {
373 global $_sys_db_transaction_level;
375 // check for transaction stack underflow
376 if ($_sys_db_transaction_level == 0) {
377 echo "ROLLBACK underflow<br />";
381 // rollback database transaction only when top-level
382 // programmatical transaction ends
383 $_sys_db_transaction_level--;
384 if ($_sys_db_transaction_level == 0) {
385 return db_query_params ("ROLLBACK", array(), -1, 0, $dbserver);
392 * db_numrows() - Returns the number of rows in this result set.
394 * @param int Query result set handle.
395 * @return int number of rows.
398 function db_numrows($qhandle) {
399 return @pg_num_rows($qhandle);
403 * db_free_result() - Frees a database result properly.
405 * @param int Query result set handle.
407 function db_free_result($qhandle) {
408 return @pg_free_result($qhandle);
412 * db_result() - Returns a field from a result set.
414 * @param int Query result set handle.
415 * @param integer Row number.
416 * @param string Field name.
417 * @return contents of field from database.
419 function db_result($qhandle,$row,$field) {
420 return @pg_fetch_result($qhandle,$row,$field);
424 * db_numfields() - Returns the number of fields in this result set.
426 * @param int Query result set handle.
428 function db_numfields($lhandle) {
429 return @pg_num_fields($lhandle);
433 * db_fieldname() - Returns the name of a particular field in the result set
435 * @param int Query result set handle.
436 * @param int Column number.
437 * @return text name of the field.
439 function db_fieldname($lhandle,$fnumber) {
440 return @pg_field_name($lhandle,$fnumber);
444 * db_affected_rows() - Returns the number of rows changed in the last query.
446 * @param int Query result set handle.
447 * @return int number of affected rows.
449 function db_affected_rows($qhandle) {
450 return @pg_affected_rows($qhandle);
454 * db_fetch_array() - Returns an associative array from
455 * the current row of this database result
457 * @param int Query result set handle.
458 * @return associative array of fieldname/value key pairs.
460 function db_fetch_array($qhandle, $row=false) {
461 return @pg_fetch_array($qhandle);
465 * db_fetch_array_by_row() - Returns an associative array from
466 * the given row of this database result
468 * @param int Query result set handle.
469 * @param int Given row to fetch
470 * @return associative array of fieldname/value key pairs.
472 function db_fetch_array_by_row($qhandle, $row) {
473 return @pg_fetch_array($qhandle, $row);
477 * db_insertid() - Returns the last primary key from an insert.
479 * @param int Query result set handle.
480 * @param string table_name is the name of the table you inserted into.
481 * @param string pkey_field_name is the field name of the primary key.
482 * @param string Server to which original query was made
483 * @return int id of the primary key or 0 on failure.
485 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=NULL) {
486 $sql = "SELECT max($pkey_field_name) AS id FROM $table_name";
487 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
488 if (db_numrows($res) >0) {
489 return db_result($res,0,'id');
496 * db_error() - Returns the last error from the database.
498 * @param constant Database server ('DB_PRIMARY', 'DB_STATS', 'DB_TROVE', 'DB_SEARCH')
499 * @return text error message.
501 function db_error($dbserver=NULL) {
502 $dbconn = db_switcher($dbserver);
504 return pg_last_error($dbconn);
508 * system_cleanup() - In the future, we may wish to do a number
509 * of cleanup functions at script termination.
511 * For now, we just abort any in-process transaction.
513 function system_cleanup() {
514 global $_sys_db_transaction_level;
515 if ($_sys_db_transaction_level > 0) {
516 echo "Open transaction detected!!!";
517 db_query_params ("ROLLBACK", array ());
521 function db_check_foo_exists ($name, $t) {
522 $res = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
528 $count = db_result($res,0,0);
529 return ($count != 0);
532 function db_check_table_exists ($name) {
533 return db_check_foo_exists($name, 'r');
536 function db_check_sequence_exists ($name) {
537 return db_check_foo_exists($name, 'S');
540 function db_check_view_exists ($name) {
541 return db_check_foo_exists($name, 'v');
544 function db_check_index_exists ($name) {
545 return db_check_foo_exists($name, 'i');
548 function db_drop_table_if_exists ($name, $cascade=false) {
549 if (!db_check_table_exists($name)) {
552 $sql = "DROP TABLE $name";
556 $res = db_query_params ($sql, array ());
564 function db_drop_sequence_if_exists ($name) {
565 if (!db_check_sequence_exists($name)) {
568 $sql = "DROP SEQUENCE $name";
569 $res = db_query_params ($sql, array ());
577 function db_drop_view_if_exists ($name) {
578 if (!db_check_view_exists($name)) {
581 $sql = "DROP VIEW $name";
582 $res = db_query_params ($sql, array ());
590 function db_drop_index_if_exists ($name) {
591 if (!db_check_index_exists($name)) {
594 $sql = "DROP INDEX $name";
595 $res = db_query_params ($sql, array ());
603 function db_bump_sequence_to ($seqname, $target) {
605 while ($current < $target) {
606 $res = db_query_params('SELECT nextval($1)',
608 if (!$res || db_numrows($res) != 1) {
612 $current = db_result($res,0,0);
616 function db_int_array_to_any_clause ($arr) {
618 foreach ($arr as $cur) {
619 if (is_numeric($cur)) {
623 $res = '{' . implode (',', $arr2) . '}' ;
627 function db_string_array_to_any_clause ($arr) {
629 foreach ($arr as $cur) {
630 $arr2[] = pg_escape_string ($cur) ;
632 $res = '{"' . implode ('","', $arr2) . '"}' ;
637 * db_construct_qpa() - Constructs a query+params array to be used by db_query_qpa()
638 * Can be called several times in a row to extend the query, until db_query_qpa will be finally invoked.
640 * @param array $old_qpa array(SQL query, array(parameters...), oldmax) of previous calls
641 * @param string $new_sql SQL instructions added to the query
642 * @param array $new_params new params matching the new query instructions
643 * @return array array(SQL query, array(parameters...), newmax)
645 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
647 // can be invoked for the first time, starting with no previous query
648 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
649 $old_qpa = array ('', array(), 0) ;
651 $old_sql = $old_qpa[0] ;
652 $old_params = $old_qpa[1] ;
653 $old_max = $old_qpa[2] ;
656 $params = $old_params ;
659 // renumber the $n params substitution placeholders to be able to concatenate
660 foreach ($new_params as $index => $value) {
661 $i = count ($new_params) - $index ;
662 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
666 $new_sql = str_replace ('$_', '$', $new_sql) ;
670 return array ($sql, $params, $max) ;
673 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
674 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
677 function db_query_to_string ($sql, $params = array()) {
678 $sql = preg_replace('/\n/',' ',$sql);
679 $sql = preg_replace('/\t/',' ',$sql);
680 $sql = preg_replace('/\s+/',' ',$sql);
681 foreach ($params as $index => $value) {
682 $sql = preg_replace('/\\$'.($index+1).'(?!\d)/', "'".$value."'", $sql);
687 function db_qpa_to_string ($qpa) {
688 return db_query_to_string($qpa[0], $qpa[1]);
693 // c-file-style: "bsd"