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 * 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 = "") {
44 $string = "dbname=$dbname user=$user";
46 $string .= " password=$password";
48 $string .= " host=$host";
51 $string .= " port=$port";
58 * db_connect() - Connect to the database
59 * Notice the global vars that must be set up
60 * Sets up a global $gfconn variable which is used
61 * in other functions in this library.
63 function db_connect() {
64 global $gfconn,$sys_db_use_replication,$sys_dbreaddb,$sys_dbreadhost;
67 // Connect to primary database
69 if (function_exists("pg_pconnect")) {
70 $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')));
72 print("function pg_pconnect doesn't exist: no postgresql interface");
77 // If any replication is configured, connect
79 if ($sys_db_use_replication) {
80 $gfconn2 = pg_pconnect(pg_connectstring($sys_dbreaddb, forge_get_config('database_user'), forge_get_config('database_password'), $sys_dbreadhost, $sys_dbreadport));
86 // Now map the physical database connections to the
87 // "virtual" list that is used to distribute load in db_query()
89 define('SYS_DB_PRIMARY', $gfconn);
90 define('SYS_DB_STATS', $gfconn2);
91 define('SYS_DB_TROVE', $gfconn2);
92 define('SYS_DB_SEARCH', $gfconn2);
94 // Register top-level "finally" handler to abort current
95 // transaction in case of error
96 register_shutdown_function("system_cleanup");
100 * db_connect_if_needed() - Set up the DB connection if it's unset
102 function db_connect_if_needed () {
104 if (!isset ($gfconn)) {
110 * db_query() - Query the database.
112 * @deprecated since 4.8. Use db_query_params() instead!
114 * @param text SQL statement.
115 * @param int How many rows do you want returned.
116 * @param int Of matching rows, return only rows starting here.
117 * @param int ability to spread load to multiple db servers.
118 * @return int result set handle.
120 function db_query($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
121 db_connect_if_needed () ;
125 if (!$limit || !is_numeric($limit) || $limit < 0) {
129 if (!$offset || !is_numeric($offset) || $offset < 0) {
132 $qstring=$qstring." LIMIT $limit OFFSET $offset";
135 //$GLOBALS['G_DEBUGQUERY'] .= $qstring .' |<font size="-2">'.$dbserver.'</font>'. "<p>\n";
136 $res = @pg_query($dbserver,$qstring);
138 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
139 error_log('SQL> '.db_error());
141 //echo "\n<br />|*| [$qstring]: ".db_error();
146 * db_query_from_file() - Query the database, from a file.
148 * @param string File that contains the SQL statements.
149 * @param int How many rows do you want returned.
150 * @param int Of matching rows, return only rows starting here.
151 * @param int ability to spread load to multiple db servers.
152 * @return int result set handle.
154 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
155 db_connect_if_needed () ;
159 $qstring = file_get_contents($file);
161 error_log('db_query_from_file(): Cannot read file $file!');
164 if (!$limit || !is_numeric($limit) || $limit < 0) {
168 if (!$offset || !is_numeric($offset) || $offset < 0) {
171 $qstring=$qstring." LIMIT $limit OFFSET $offset";
173 $res = @pg_query($dbserver,$qstring);
175 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
176 error_log('SQL> '.db_error());
178 //echo "\n<br />|*| [$qstring]: ".db_error();
183 * db_query_params() - Query the database, with parameters
185 * @param text SQL statement.
186 * @param array parameters
187 * @param int How many rows do you want returned.
188 * @param int Of matching rows, return only rows starting here.
189 * @param int ability to spread load to multiple db servers.
190 * @return int result set handle.
192 function db_query_params($qstring,$params,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
193 db_connect_if_needed () ;
197 if (get_magic_quotes_gpc() == true) {
198 $params = array_map('stripslashes',$params);
200 if (!$limit || !is_numeric($limit) || $limit < 0) {
204 if (!$offset || !is_numeric($offset) || $offset < 0) {
207 $qstring=$qstring." LIMIT $limit OFFSET $offset";
210 $res = @pg_query_params($dbserver,$qstring,$params);
212 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
213 error_log('SQL> '.db_error());
219 * db_query_params() - Query the database, with a query+params array
221 * @param array array(query, array(parameters...))
222 * @param int How many rows do you want returned.
223 * @param int Of matching rows, return only rows starting here.
224 * @param int ability to spread load to multiple db servers.
225 * @return int result set handle.
227 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
230 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
234 * db_mquery() - Query the database.
236 * @deprecated since 4.8. Use db_query_params() instead!
238 * @param text SQL statement.
239 * @param int How many rows do you want returned.
240 * @param int Of matching rows, return only rows starting here.
241 * @param int ability to spread load to multiple db servers.
242 * @return int result set handle.
244 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
245 return db_query($qstring, $limit, $offset, $dbserver);
249 * db_more_results() - Check if there are more unprocessed results.
251 * @return bool true if there are more results..
253 function db_more_results() {
258 * db_next_result() - Get the next result from query with multiple statements.
260 * @param string SQL statement
261 * @param int How many rows do you want returned
262 * @param int Of matching rows, return only rows starting here
264 function db_next_result() {
268 /* Current transaction level, private variable */
269 /* FIXME: Having scalar variable for transaction level is
270 no longer correct after multiple database (dbservers) support
271 introduction. However, it is true that in one given PHP
272 script, at most one db is modified, so this works for now. */
273 $_sys_db_transaction_level = 0;
276 * db_begin() - Begin a transaction.
278 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
281 function db_begin($dbserver=SYS_DB_PRIMARY) {
282 global $_sys_db_transaction_level;
284 // start database transaction only for the top-level
285 // programmatical transaction
286 $_sys_db_transaction_level++;
287 if ($_sys_db_transaction_level == 1) {
288 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
295 * db_commit() - Commit a transaction.
297 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
298 * @return true on success/false on failure.
300 function db_commit($dbserver=SYS_DB_PRIMARY) {
301 global $_sys_db_transaction_level;
303 // check for transaction stack underflow
304 if ($_sys_db_transaction_level == 0) {
305 echo "COMMIT underflow<br />";
309 // commit database transaction only when top-level
310 // programmatical transaction ends
311 $_sys_db_transaction_level--;
312 if ($_sys_db_transaction_level == 0) {
313 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
320 * db_rollback() - Rollback a transaction.
322 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
323 * @return true on success/false on failure.
325 function db_rollback($dbserver=SYS_DB_PRIMARY) {
326 global $_sys_db_transaction_level;
328 // check for transaction stack underflow
329 if ($_sys_db_transaction_level == 0) {
330 echo "ROLLBACK underflow<br />";
334 // rollback database transaction only when top-level
335 // programmatical transaction ends
336 $_sys_db_transaction_level--;
337 if ($_sys_db_transaction_level == 0) {
338 return db_query_params ("ROLLBACK", array(), -1, 0, $dbserver);
345 * db_numrows() - Returns the number of rows in this result set.
347 * @param int Query result set handle.
348 * @return int number of rows.
351 function db_numrows($qhandle) {
352 return @pg_numrows($qhandle);
356 * db_free_result() - Frees a database result properly.
358 * @param int Query result set handle.
360 function db_free_result($qhandle) {
361 return @pg_freeresult($qhandle);
365 * db_result() - Returns a field from a result set.
367 * @param int Query result set handle.
368 * @param integer Row number.
369 * @param string Field name.
370 * @return contents of field from database.
372 function db_result($qhandle,$row,$field) {
373 return @pg_result($qhandle,$row,$field);
377 * db_numfields() - Returns the number of fields in this result set.
379 * @param int Query result set handle.
381 function db_numfields($lhandle) {
382 return @pg_numfields($lhandle);
386 * db_fieldname() - Returns the name of a particular field in the result set
388 * @param int Query result set handle.
389 * @param int Column number.
390 * @return text name of the field.
392 function db_fieldname($lhandle,$fnumber) {
393 return @pg_fieldname($lhandle,$fnumber);
397 * db_affected_rows() - Returns the number of rows changed in the last query.
399 * @param int Query result set handle.
400 * @return int number of affected rows.
402 function db_affected_rows($qhandle) {
403 return @pg_cmdtuples($qhandle);
407 * db_fetch_array() - Returns an associative array from
408 * the current row of this database result
410 * @param int Query result set handle.
411 * @return associative array of fieldname/value key pairs.
413 function db_fetch_array($qhandle, $row=false) {
414 return @pg_fetch_array($qhandle);
418 * db_fetch_array_by_row() - Returns an associative array from
419 * the given row of this database result
421 * @param int Query result set handle.
422 * @param int Given row to fetch
423 * @return associative array of fieldname/value key pairs.
425 function db_fetch_array_by_row($qhandle, $row) {
426 return @pg_fetch_array($qhandle, $row);
430 * db_insertid() - Returns the last primary key from an insert.
432 * @param int Query result set handle.
433 * @param string table_name is the name of the table you inserted into.
434 * @param string pkey_field_name is the field name of the primary key.
435 * @param string Server to which original query was made
436 * @return int id of the primary key or 0 on failure.
438 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=SYS_DB_PRIMARY) {
439 $sql="SELECT max($pkey_field_name) AS id FROM $table_name";
441 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
442 if (db_numrows($res) >0) {
443 return db_result($res,0,'id');
445 // echo "No Rows Matched";
452 * db_error() - Returns the last error from the database.
454 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
455 * @return text error message.
457 function db_error($dbserver=SYS_DB_PRIMARY) {
458 return @pg_errormessage($dbserver);
462 * system_cleanup() - In the future, we may wish to do a number
463 * of cleanup functions at script termination.
465 * For now, we just abort any in-process transaction.
467 function system_cleanup() {
468 global $_sys_db_transaction_level;
469 if ($_sys_db_transaction_level > 0) {
470 echo "Open transaction detected!!!";
471 db_query_params ("ROLLBACK", array ());
475 function db_drop_table_if_exists ($tn) {
476 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
479 $count = db_result($rel,0,0);
481 $sql = "DROP TABLE $tn";
482 $rel = db_query_params ($sql, array ());
487 function db_drop_sequence_if_exists ($tn) {
488 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
491 $count = db_result($rel,0,0);
493 $sql = "DROP SEQUENCE $tn";
494 $rel = db_query_params ($sql, array ());
499 function db_int_array_to_any_clause ($arr) {
501 foreach ($arr as $cur) {
502 if (is_numeric($cur)) {
506 $res = '{' . implode (',', $arr2) . '}' ;
510 function db_string_array_to_any_clause ($arr) {
512 foreach ($arr as $cur) {
513 $arr2[] = pg_escape_string ($cur) ;
515 $res = '{"' . implode ('","', $arr2) . '"}' ;
519 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
520 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
521 $old_qpa = array ('', array(), 0) ;
523 $old_sql = $old_qpa[0] ;
524 $old_params = $old_qpa[1] ;
525 $old_max = $old_qpa[2] ;
528 $params = $old_params ;
531 foreach ($new_params as $index => $value) {
532 $i = count ($new_params) - $index ;
533 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
537 $new_sql = str_replace ('$_', '$', $new_sql) ;
541 return array ($sql, $params, $max) ;
544 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
545 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
550 // c-file-style: "bsd"