3 * FusionForge PostgreSQL connection layer
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2002, GForge, LLC
7 * Copyright 2009, Roland Mas
9 * This file is part of FusionForge. FusionForge is free software;
10 * you can redistribute it and/or modify it under the terms of the
11 * GNU General Public License as published by the Free Software
12 * Foundation; either version 2 of the Licence, or (at your option)
15 * FusionForge is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * pg_connectstring() - builds a postgres connection string.
27 * Combines the supplied arguments into a valid, specific, postgresql
28 * connection string. It only includes the host and port options
29 * if specified. Without those options, it will use the unix domain
30 * sockets to connect to the postgres server on the local machine.
32 * @author Graham Batty graham@sandworm.ca
33 * @param dbname The database to connect to. Required.
34 * @param user The username used to connect. Required
35 * @param password The password used to connect
36 * @param host The hostname to connect to, if not localhost
37 * @param port The port to connect to, if not 5432
38 * @return string The connection string to pass to pg_connect()
41 function pg_connectstring($dbname, $user, $password = "", $host = "", $port = "") {
43 $string = "dbname=$dbname";
45 $string = "dbname=gforge";
48 $string .= " user=$user";
50 $string .= " password=$password";
52 $string .= " host=$host";
55 $string .= " port=$port";
62 * db_connect() - Connect to the database
63 * Notice the global vars that must be set up
64 * Sets up a global $gfconn variable which is used
65 * in other functions in this library.
67 function db_connect() {
68 global $gfconn,$sys_db_use_replication,$sys_dbreaddb,$sys_dbreadhost;
71 // Connect to primary database
73 if (function_exists("pg_pconnect")) {
74 $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')));
76 print forge_get_config ('forge_name')." Could Not Connect to Database: ".db_error();
80 print("function pg_pconnect doesn't exist: no postgresql interface");
85 // If any replication is configured, connect
87 if ($sys_db_use_replication) {
88 $gfconn2 = pg_pconnect(pg_connectstring($sys_dbreaddb, forge_get_config('database_user'), forge_get_config('database_password'), $sys_dbreadhost, $sys_dbreadport));
94 // Now map the physical database connections to the
95 // "virtual" list that is used to distribute load in db_query()
97 define('SYS_DB_PRIMARY', $gfconn);
98 define('SYS_DB_STATS', $gfconn2);
99 define('SYS_DB_TROVE', $gfconn2);
100 define('SYS_DB_SEARCH', $gfconn2);
102 // Register top-level "finally" handler to abort current
103 // transaction in case of error
104 register_shutdown_function("system_cleanup");
108 * db_connect_if_needed() - Set up the DB connection if it's unset
110 function db_connect_if_needed () {
112 if (!isset ($gfconn)) {
117 function db_switcher($dbserver=NULL) {
120 case 'SYS_DB_PRIMARY':
121 $dbconn = SYS_DB_PRIMARY ;
124 $dbconn = SYS_DB_STATS ;
127 $dbconn = SYS_DB_TROVE ;
129 case 'SYS_DB_SEARCH':
130 $dbconn = SYS_DB_SEARCH ;
133 // Cope with $dbserver already being a connection
134 if (pg_dbname($dbserver)) {
137 $dbconn = SYS_DB_PRIMARY ;
145 * db_query() - Query the database.
147 * @deprecated since 4.8. Use db_query_params() instead!
149 * @param text SQL statement.
150 * @param int How many rows do you want returned.
151 * @param int Of matching rows, return only rows starting here.
152 * @param int ability to spread load to multiple db servers.
153 * @return int result set handle.
155 function db_query($qstring,$limit='-1',$offset=0,$dbserver=NULL) {
156 global $sysdebug_dbquery;
158 db_connect_if_needed () ;
159 $dbconn = db_switcher($dbserver) ;
164 if (!$limit || !is_numeric($limit) || $limit < 0) {
168 if (!$offset || !is_numeric($offset) || $offset < 0) {
171 $qstring=$qstring." LIMIT $limit OFFSET $offset";
174 if ($sysdebug_dbquery) {
175 ffDebug('trace', "tracing call of db_query():\n",
176 debug_string_backtrace());
179 $res = @pg_query($dbconn,$qstring);
181 error_log('SQL: ' . preg_replace('/\n\t+/', ' ',$qstring));
182 error_log('SQL> ' . db_error($dbconn));
188 * db_query_from_file() - Query the database, from a file.
190 * @param string File that contains the SQL statements.
191 * @param int How many rows do you want returned.
192 * @param int Of matching rows, return only rows starting here.
193 * @param int ability to spread load to multiple db servers.
194 * @return int result set handle.
196 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=NULL) {
197 db_connect_if_needed () ;
198 $dbconn = db_switcher($dbserver) ;
203 $qstring = file_get_contents($file);
205 error_log('db_query_from_file(): Cannot read file $file!');
208 if (!$limit || !is_numeric($limit) || $limit < 0) {
212 if (!$offset || !is_numeric($offset) || $offset < 0) {
215 $qstring=$qstring." LIMIT $limit OFFSET $offset";
217 $res = @pg_query($dbconn,$qstring);
219 error_log('SQL: ' . preg_replace('/\n\t+/', ' ',$qstring));
220 error_log('SQL> ' . db_error($dbserver));
226 * db_query_params() - Query the database, with parameters
228 * @param text SQL statement.
229 * @param array parameters
230 * @param int How many rows do you want returned.
231 * @param int Of matching rows, return only rows starting here.
232 * @param int ability to spread load to multiple db servers.
233 * @return int result set handle.
235 function db_query_params($qstring,$params,$limit='-1',$offset=0,$dbserver=NULL) {
236 global $sysdebug_dbquery;
238 db_connect_if_needed () ;
239 $dbconn = db_switcher($dbserver) ;
244 if (!$limit || !is_numeric($limit) || $limit < 0) {
248 if (!$offset || !is_numeric($offset) || $offset < 0) {
251 $qstring=$qstring." LIMIT $limit OFFSET $offset";
254 if ($sysdebug_dbquery) {
255 ffDebug('trace', "tracing call of db_query_params():\n",
256 debug_string_backtrace());
259 $res = @pg_query_params($dbconn,$qstring,$params);
261 error_log('SQL: ' . preg_replace('/\n\t+/', ' ',$qstring));
262 error_log('SQL> '.db_error($dbserver));
268 * db_query_qpa() - Query the database, with a query+params array
270 * @param array array(query, array(parameters...))
271 * @param int How many rows do you want returned.
272 * @param int Of matching rows, return only rows starting here.
273 * @param int ability to spread load to multiple db servers.
274 * @return int result set handle.
276 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=NULL) {
279 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
283 * db_mquery() - Query the database.
285 * @deprecated since 4.8. Use db_query_params() instead!
287 * @param text SQL statement.
288 * @param int How many rows do you want returned.
289 * @param int Of matching rows, return only rows starting here.
290 * @param int ability to spread load to multiple db servers.
291 * @return int result set handle.
293 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=NULL) {
294 return db_query($qstring, $limit, $offset, $dbserver);
298 * db_more_results() - Check if there are more unprocessed results.
300 * @return bool true if there are more results..
302 function db_more_results() {
307 * db_next_result() - Get the next result from query with multiple statements.
309 * @param string SQL statement
310 * @param int How many rows do you want returned
311 * @param int Of matching rows, return only rows starting here
313 function db_next_result() {
317 /* Current transaction level, private variable */
318 /* FIXME: Having scalar variable for transaction level is
319 no longer correct after multiple database (dbservers) support
320 introduction. However, it is true that in one given PHP
321 script, at most one db is modified, so this works for now. */
322 $_sys_db_transaction_level = 0;
325 * db_begin() - Begin a transaction.
327 * @param constant Database server ('DB_PRIMARY', 'DB_STATS', 'DB_TROVE', 'DB_SEARCH')
330 function db_begin($dbserver=NULL) {
331 global $_sys_db_transaction_level;
333 // start database transaction only for the top-level
334 // programmatical transaction
335 $_sys_db_transaction_level++;
336 if ($_sys_db_transaction_level == 1) {
337 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
344 * db_commit() - Commit a transaction.
346 * @param constant Database server ('DB_PRIMARY', 'DB_STATS', 'DB_TROVE', 'DB_SEARCH')
347 * @return true on success/false on failure.
349 function db_commit($dbserver=NULL) {
350 global $_sys_db_transaction_level;
352 // check for transaction stack underflow
353 if ($_sys_db_transaction_level == 0) {
354 echo "COMMIT underflow<br />";
358 // commit database transaction only when top-level
359 // programmatical transaction ends
360 $_sys_db_transaction_level--;
361 if ($_sys_db_transaction_level == 0) {
362 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
369 * db_rollback() - Rollback a transaction.
371 * @param constant Database server ('DB_PRIMARY', 'DB_STATS', 'DB_TROVE', 'DB_SEARCH')
372 * @return true on success/false on failure.
374 function db_rollback($dbserver=NULL) {
375 global $_sys_db_transaction_level;
377 // check for transaction stack underflow
378 if ($_sys_db_transaction_level == 0) {
379 echo "ROLLBACK underflow<br />";
383 // rollback database transaction only when top-level
384 // programmatical transaction ends
385 $_sys_db_transaction_level--;
386 if ($_sys_db_transaction_level == 0) {
387 return db_query_params ("ROLLBACK", array(), -1, 0, $dbserver);
394 * db_numrows() - Returns the number of rows in this result set.
396 * @param int Query result set handle.
397 * @return int number of rows.
400 function db_numrows($qhandle) {
401 return @pg_numrows($qhandle);
405 * db_free_result() - Frees a database result properly.
407 * @param int Query result set handle.
409 function db_free_result($qhandle) {
410 return @pg_freeresult($qhandle);
414 * db_result() - Returns a field from a result set.
416 * @param int Query result set handle.
417 * @param integer Row number.
418 * @param string Field name.
419 * @return contents of field from database.
421 function db_result($qhandle,$row,$field) {
422 return @pg_result($qhandle,$row,$field);
426 * db_numfields() - Returns the number of fields in this result set.
428 * @param int Query result set handle.
430 function db_numfields($lhandle) {
431 return @pg_numfields($lhandle);
435 * db_fieldname() - Returns the name of a particular field in the result set
437 * @param int Query result set handle.
438 * @param int Column number.
439 * @return text name of the field.
441 function db_fieldname($lhandle,$fnumber) {
442 return @pg_fieldname($lhandle,$fnumber);
446 * db_affected_rows() - Returns the number of rows changed in the last query.
448 * @param int Query result set handle.
449 * @return int number of affected rows.
451 function db_affected_rows($qhandle) {
452 return @pg_cmdtuples($qhandle);
456 * db_fetch_array() - Returns an associative array from
457 * the current row of this database result
459 * @param int Query result set handle.
460 * @return associative array of fieldname/value key pairs.
462 function db_fetch_array($qhandle, $row=false) {
463 return @pg_fetch_array($qhandle);
467 * db_fetch_array_by_row() - Returns an associative array from
468 * the given row of this database result
470 * @param int Query result set handle.
471 * @param int Given row to fetch
472 * @return associative array of fieldname/value key pairs.
474 function db_fetch_array_by_row($qhandle, $row) {
475 return @pg_fetch_array($qhandle, $row);
479 * db_insertid() - Returns the last primary key from an insert.
481 * @param int Query result set handle.
482 * @param string table_name is the name of the table you inserted into.
483 * @param string pkey_field_name is the field name of the primary key.
484 * @param string Server to which original query was made
485 * @return int id of the primary key or 0 on failure.
487 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=NULL) {
488 $sql = "SELECT max($pkey_field_name) AS id FROM $table_name";
489 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
490 if (db_numrows($res) >0) {
491 return db_result($res,0,'id');
498 * db_error() - Returns the last error from the database.
500 * @param constant Database server ('DB_PRIMARY', 'DB_STATS', 'DB_TROVE', 'DB_SEARCH')
501 * @return text error message.
503 function db_error($dbserver=NULL) {
504 $dbconn = db_switcher($dbserver);
506 return pg_last_error($dbconn);
510 * system_cleanup() - In the future, we may wish to do a number
511 * of cleanup functions at script termination.
513 * For now, we just abort any in-process transaction.
515 function system_cleanup() {
516 global $_sys_db_transaction_level;
517 if ($_sys_db_transaction_level > 0) {
518 echo "Open transaction detected!!!";
519 db_query_params ("ROLLBACK", array ());
523 function db_drop_table_if_exists ($tn) {
524 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
527 $count = db_result($rel,0,0);
529 $sql = "DROP TABLE $tn";
530 $rel = db_query_params ($sql, array ());
535 function db_drop_sequence_if_exists ($tn) {
536 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
539 $count = db_result($rel,0,0);
541 $sql = "DROP SEQUENCE $tn";
542 $rel = db_query_params ($sql, array ());
547 function db_int_array_to_any_clause ($arr) {
549 foreach ($arr as $cur) {
550 if (is_numeric($cur)) {
554 $res = '{' . implode (',', $arr2) . '}' ;
558 function db_string_array_to_any_clause ($arr) {
560 foreach ($arr as $cur) {
561 $arr2[] = pg_escape_string ($cur) ;
563 $res = '{"' . implode ('","', $arr2) . '"}' ;
567 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
568 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
569 $old_qpa = array ('', array(), 0) ;
571 $old_sql = $old_qpa[0] ;
572 $old_params = $old_qpa[1] ;
573 $old_max = $old_qpa[2] ;
576 $params = $old_params ;
579 foreach ($new_params as $index => $value) {
580 $i = count ($new_params) - $index ;
581 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
585 $new_sql = str_replace ('$_', '$', $new_sql) ;
589 return array ($sql, $params, $max) ;
592 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
593 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
598 // c-file-style: "bsd"