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.
11 * FusionForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published
13 * by the Free Software Foundation; either version 2 of the License,
14 * or (at your option) any later version.
16 * FusionForge is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with FusionForge; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
28 * Current row for each result set
30 * @var array $sys_db_row_pointer
32 $sys_db_row_pointer=array(); //current row for each result set
35 * pg_connectstring() - builds a postgres connection string.
36 * Combines the supplied arguments into a valid, specific, postgresql
37 * connection string. It only includes the host and port options
38 * if specified. Without those options, it will use the unix domain
39 * sockets to connect to the postgres server on the local machine.
41 * @author Graham Batty graham@sandworm.ca
42 * @param dbname The database to connect to. Required.
43 * @param user The username used to connect. Required
44 * @param password The password used to connect
45 * @param host The hostname to connect to, if not localhost
46 * @param port The port to connect to, if not 5432
47 * @return string The connection string to pass to pg_connect()
50 function pg_connectstring($dbname, $user, $password = "", $host = "", $port = "") {
51 $string = "dbname=$dbname user=$user";
53 $string .= " password=$password";
55 $string .= " host=$host";
58 $string .= " port=$port";
65 * db_connect() - Connect to the database
66 * Notice the global vars that must be set up
67 * Sets up a global $gfconn variable which is used
68 * in other functions in this library.
70 function db_connect() {
71 global $gfconn,$sys_db_use_replication,$sys_dbreaddb,$sys_dbreadhost;
74 // Connect to primary database
76 if (function_exists("pg_pconnect")) {
77 $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')));
79 print("function pg_pconnect doesn't exist: no postgresql interface");
84 // If any replication is configured, connect
86 if ($sys_db_use_replication) {
87 $gfconn2 = pg_pconnect(pg_connectstring($sys_dbreaddb, forge_get_config('database_user'), forge_get_config('database_password'), $sys_dbreadhost, $sys_dbreadport));
93 // Now map the physical database connections to the
94 // "virtual" list that is used to distribute load in db_query()
96 define('SYS_DB_PRIMARY', $gfconn);
97 define('SYS_DB_STATS', $gfconn2);
98 define('SYS_DB_TROVE', $gfconn2);
99 define('SYS_DB_SEARCH', $gfconn2);
101 // Register top-level "finally" handler to abort current
102 // transaction in case of error
103 register_shutdown_function("system_cleanup");
107 * db_query() - Query the database.
109 * @deprecated since 4.8. Use db_query_params() instead!
111 * @param text SQL statement.
112 * @param int How many rows do you want returned.
113 * @param int Of matching rows, return only rows starting here.
114 * @param int ability to spread load to multiple db servers.
115 * @return int result set handle.
117 function db_query($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
121 if (!$limit || !is_numeric($limit) || $limit < 0) {
125 if (!$offset || !is_numeric($offset) || $offset < 0) {
128 $qstring=$qstring." LIMIT $limit OFFSET $offset";
131 //$GLOBALS['G_DEBUGQUERY'] .= $qstring .' |<font size="-2">'.$dbserver.'</font>'. "<p>\n";
132 $res = @pg_query($dbserver,$qstring);
134 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
135 error_log('SQL> '.db_error());
137 //echo "\n<br />|*| [$qstring]: ".db_error();
142 * db_query_from_file() - Query the database, from a file.
144 * @param string File that contains the SQL statements.
145 * @param int How many rows do you want returned.
146 * @param int Of matching rows, return only rows starting here.
147 * @param int ability to spread load to multiple db servers.
148 * @return int result set handle.
150 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
154 $qstring = file_get_contents($file);
156 error_log('db_query_from_file(): Cannot read file $file!');
159 if (!$limit || !is_numeric($limit) || $limit < 0) {
163 if (!$offset || !is_numeric($offset) || $offset < 0) {
166 $qstring=$qstring." LIMIT $limit OFFSET $offset";
168 $res = @pg_query($dbserver,$qstring);
170 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
171 error_log('SQL> '.db_error());
173 //echo "\n<br />|*| [$qstring]: ".db_error();
178 * db_query_params() - Query the database, with parameters
180 * @param text SQL statement.
181 * @param array parameters
182 * @param int How many rows do you want returned.
183 * @param int Of matching rows, return only rows starting here.
184 * @param int ability to spread load to multiple db servers.
185 * @return int result set handle.
187 function db_query_params($qstring,$params,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
191 if (get_magic_quotes_gpc() == true) {
192 $params = array_map('stripslashes',$params);
194 if (!$limit || !is_numeric($limit) || $limit < 0) {
198 if (!$offset || !is_numeric($offset) || $offset < 0) {
201 $qstring=$qstring." LIMIT $limit OFFSET $offset";
204 $res = @pg_query_params($dbserver,$qstring,$params);
206 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
207 error_log('SQL> '.db_error());
213 * db_query_params() - Query the database, with a query+params array
215 * @param array array(query, array(parameters...))
216 * @param int How many rows do you want returned.
217 * @param int Of matching rows, return only rows starting here.
218 * @param int ability to spread load to multiple db servers.
219 * @return int result set handle.
221 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
224 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
228 * db_mquery() - Query the database.
230 * @deprecated since 4.8. Use db_query_params() instead!
232 * @param text SQL statement.
233 * @param int How many rows do you want returned.
234 * @param int Of matching rows, return only rows starting here.
235 * @param int ability to spread load to multiple db servers.
236 * @return int result set handle.
238 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
239 return db_query($qstring, $limit, $offset, $dbserver);
243 * db_more_results() - Check if there are more unprocessed results.
245 * @return bool true if there are more results..
247 function db_more_results() {
252 * db_next_result() - Get the next result from query with multiple statements.
254 * @param string SQL statement
255 * @param int How many rows do you want returned
256 * @param int Of matching rows, return only rows starting here
258 function db_next_result() {
262 /* Current transaction level, private variable */
263 /* FIXME: Having scalar variable for transaction level is
264 no longer correct after multiple database (dbservers) support
265 introduction. However, it is true that in one given PHP
266 script, at most one db is modified, so this works for now. */
267 $_sys_db_transaction_level = 0;
270 * db_begin() - Begin a transaction.
272 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
275 function db_begin($dbserver=SYS_DB_PRIMARY) {
276 global $_sys_db_transaction_level;
278 // start database transaction only for the top-level
279 // programmatical transaction
280 $_sys_db_transaction_level++;
281 if ($_sys_db_transaction_level == 1) {
282 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
289 * db_commit() - Commit a transaction.
291 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
292 * @return true on success/false on failure.
294 function db_commit($dbserver=SYS_DB_PRIMARY) {
295 global $_sys_db_transaction_level;
297 // check for transaction stack underflow
298 if ($_sys_db_transaction_level == 0) {
299 echo "COMMIT underflow<br />";
303 // commit database transaction only when top-level
304 // programmatical transaction ends
305 $_sys_db_transaction_level--;
306 if ($_sys_db_transaction_level == 0) {
307 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
314 * db_rollback() - Rollback a transaction.
316 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
317 * @return true on success/false on failure.
319 function db_rollback($dbserver=SYS_DB_PRIMARY) {
320 global $_sys_db_transaction_level;
322 // check for transaction stack underflow
323 if ($_sys_db_transaction_level == 0) {
324 echo "ROLLBACK underflow<br />";
328 // rollback database transaction only when top-level
329 // programmatical transaction ends
330 $_sys_db_transaction_level--;
331 if ($_sys_db_transaction_level == 0) {
332 return db_query_params ("ROLLBACK", array(), -1, 0, $dbserver);
339 * db_numrows() - Returns the number of rows in this result set.
341 * @param int Query result set handle.
342 * @return int number of rows.
345 function db_numrows($qhandle) {
346 return @pg_numrows($qhandle);
350 * db_free_result() - Frees a database result properly.
352 * @param int Query result set handle.
354 function db_free_result($qhandle) {
355 return @pg_freeresult($qhandle);
359 * db_reset_result() - Reset is useful for db_fetch_array
360 * sometimes you need to start over.
362 * @param int Query result set handle.
363 * @param integer Row number.
366 function db_reset_result($qhandle,$row=0) {
367 global $sys_db_row_pointer;
368 return $sys_db_row_pointer[$qhandle]=$row;
372 * db_result() - Returns a field from a result set.
374 * @param int Query result set handle.
375 * @param integer Row number.
376 * @param string Field name.
377 * @return contents of field from database.
379 function db_result($qhandle,$row,$field) {
380 return @pg_result($qhandle,$row,$field);
384 * db_numfields() - Returns the number of fields in this result set.
386 * @param int Query result set handle.
388 function db_numfields($lhandle) {
389 return @pg_numfields($lhandle);
393 * db_fieldname() - Returns the name of a particular field in the result set
395 * @param int Query result set handle.
396 * @param int Column number.
397 * @return text name of the field.
399 function db_fieldname($lhandle,$fnumber) {
400 return @pg_fieldname($lhandle,$fnumber);
404 * db_affected_rows() - Returns the number of rows changed in the last query.
406 * @param int Query result set handle.
407 * @return int number of affected rows.
409 function db_affected_rows($qhandle) {
410 return @pg_cmdtuples($qhandle);
414 * db_fetch_array() - Returns an associative array from
415 * the current row of this database result
416 * Use db_reset_result to seek a particular row.
418 * @param int Query result set handle.
419 * @return associative array of fieldname/value key pairs.
421 function db_fetch_array($qhandle) {
422 global $sys_db_row_pointer;
423 if(!isset($sys_db_row_pointer[$qhandle])) {
424 $sys_db_row_pointer[$qhandle] = 0;
426 $sys_db_row_pointer[$qhandle]++;
427 return @pg_fetch_array($qhandle,($sys_db_row_pointer[$qhandle]-1));
431 * db_insertid() - Returns the last primary key from an insert.
433 * @param int Query result set handle.
434 * @param string table_name is the name of the table you inserted into.
435 * @param string pkey_field_name is the field name of the primary key.
436 * @param string Server to which original query was made
437 * @return int id of the primary key or 0 on failure.
439 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=SYS_DB_PRIMARY) {
440 $sql="SELECT max($pkey_field_name) AS id FROM $table_name";
442 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
443 if (db_numrows($res) >0) {
444 return db_result($res,0,'id');
446 // echo "No Rows Matched";
453 * db_error() - Returns the last error from the database.
455 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
456 * @return text error message.
458 function db_error($dbserver=SYS_DB_PRIMARY) {
459 return @pg_errormessage($dbserver);
463 * system_cleanup() - In the future, we may wish to do a number
464 * of cleanup functions at script termination.
466 * For now, we just abort any in-process transaction.
468 function system_cleanup() {
469 global $_sys_db_transaction_level;
470 if ($_sys_db_transaction_level > 0) {
471 echo "Open transaction detected!!!";
472 db_query_params ("ROLLBACK", array ());
476 function db_drop_table_if_exists ($tn) {
477 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
480 $count = db_result($rel,0,0);
482 $sql = "DROP TABLE $tn";
483 $rel = db_query_params ($sql, array ());
488 function db_drop_sequence_if_exists ($tn) {
489 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
492 $count = db_result($rel,0,0);
494 $sql = "DROP SEQUENCE $tn";
495 $rel = db_query_params ($sql, array ());
500 function db_int_array_to_any_clause ($arr) {
502 foreach ($arr as $cur) {
503 if (is_numeric($cur)) {
507 $res = '{' . implode (',', $arr2) . '}' ;
511 function db_string_array_to_any_clause ($arr) {
513 foreach ($arr as $cur) {
514 $arr2[] = pg_escape_string ($cur) ;
516 $res = '{"' . implode ('","', $arr2) . '"}' ;
520 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
521 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
522 $old_qpa = array ('', array(), 0) ;
524 $old_sql = $old_qpa[0] ;
525 $old_params = $old_qpa[1] ;
526 $old_max = $old_qpa[2] ;
529 $params = $old_params ;
532 foreach ($new_params as $index => $value) {
533 $i = count ($new_params) - $index ;
534 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
538 $new_sql = str_replace ('$_', '$', $new_sql) ;
542 return array ($sql, $params, $max) ;
545 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
546 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
551 // c-file-style: "bsd"