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_query() - Query the database.
102 * @deprecated since 4.8. Use db_query_params() instead!
104 * @param text SQL statement.
105 * @param int How many rows do you want returned.
106 * @param int Of matching rows, return only rows starting here.
107 * @param int ability to spread load to multiple db servers.
108 * @return int result set handle.
110 function db_query($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
114 if (!$limit || !is_numeric($limit) || $limit < 0) {
118 if (!$offset || !is_numeric($offset) || $offset < 0) {
121 $qstring=$qstring." LIMIT $limit OFFSET $offset";
124 //$GLOBALS['G_DEBUGQUERY'] .= $qstring .' |<font size="-2">'.$dbserver.'</font>'. "<p>\n";
125 $res = @pg_query($dbserver,$qstring);
127 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
128 error_log('SQL> '.db_error());
130 //echo "\n<br />|*| [$qstring]: ".db_error();
135 * db_query_from_file() - Query the database, from a file.
137 * @param string File that contains the SQL statements.
138 * @param int How many rows do you want returned.
139 * @param int Of matching rows, return only rows starting here.
140 * @param int ability to spread load to multiple db servers.
141 * @return int result set handle.
143 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
147 $qstring = file_get_contents($file);
149 error_log('db_query_from_file(): Cannot read file $file!');
152 if (!$limit || !is_numeric($limit) || $limit < 0) {
156 if (!$offset || !is_numeric($offset) || $offset < 0) {
159 $qstring=$qstring." LIMIT $limit OFFSET $offset";
161 $res = @pg_query($dbserver,$qstring);
163 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
164 error_log('SQL> '.db_error());
166 //echo "\n<br />|*| [$qstring]: ".db_error();
171 * db_query_params() - Query the database, with parameters
173 * @param text SQL statement.
174 * @param array parameters
175 * @param int How many rows do you want returned.
176 * @param int Of matching rows, return only rows starting here.
177 * @param int ability to spread load to multiple db servers.
178 * @return int result set handle.
180 function db_query_params($qstring,$params,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
184 if (get_magic_quotes_gpc() == true) {
185 $params = array_map('stripslashes',$params);
187 if (!$limit || !is_numeric($limit) || $limit < 0) {
191 if (!$offset || !is_numeric($offset) || $offset < 0) {
194 $qstring=$qstring." LIMIT $limit OFFSET $offset";
197 $res = @pg_query_params($dbserver,$qstring,$params);
199 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
200 error_log('SQL> '.db_error());
206 * db_query_params() - Query the database, with a query+params array
208 * @param array array(query, array(parameters...))
209 * @param int How many rows do you want returned.
210 * @param int Of matching rows, return only rows starting here.
211 * @param int ability to spread load to multiple db servers.
212 * @return int result set handle.
214 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
217 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
221 * db_mquery() - Query the database.
223 * @deprecated since 4.8. Use db_query_params() instead!
225 * @param text SQL statement.
226 * @param int How many rows do you want returned.
227 * @param int Of matching rows, return only rows starting here.
228 * @param int ability to spread load to multiple db servers.
229 * @return int result set handle.
231 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
232 return db_query($qstring, $limit, $offset, $dbserver);
236 * db_more_results() - Check if there are more unprocessed results.
238 * @return bool true if there are more results..
240 function db_more_results() {
245 * db_next_result() - Get the next result from query with multiple statements.
247 * @param string SQL statement
248 * @param int How many rows do you want returned
249 * @param int Of matching rows, return only rows starting here
251 function db_next_result() {
255 /* Current transaction level, private variable */
256 /* FIXME: Having scalar variable for transaction level is
257 no longer correct after multiple database (dbservers) support
258 introduction. However, it is true that in one given PHP
259 script, at most one db is modified, so this works for now. */
260 $_sys_db_transaction_level = 0;
263 * db_begin() - Begin a transaction.
265 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
268 function db_begin($dbserver=SYS_DB_PRIMARY) {
269 global $_sys_db_transaction_level;
271 // start database transaction only for the top-level
272 // programmatical transaction
273 $_sys_db_transaction_level++;
274 if ($_sys_db_transaction_level == 1) {
275 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
282 * db_commit() - Commit a transaction.
284 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
285 * @return true on success/false on failure.
287 function db_commit($dbserver=SYS_DB_PRIMARY) {
288 global $_sys_db_transaction_level;
290 // check for transaction stack underflow
291 if ($_sys_db_transaction_level == 0) {
292 echo "COMMIT underflow<br />";
296 // commit database transaction only when top-level
297 // programmatical transaction ends
298 $_sys_db_transaction_level--;
299 if ($_sys_db_transaction_level == 0) {
300 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
307 * db_rollback() - Rollback a transaction.
309 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
310 * @return true on success/false on failure.
312 function db_rollback($dbserver=SYS_DB_PRIMARY) {
313 global $_sys_db_transaction_level;
315 // check for transaction stack underflow
316 if ($_sys_db_transaction_level == 0) {
317 echo "ROLLBACK underflow<br />";
321 // rollback database transaction only when top-level
322 // programmatical transaction ends
323 $_sys_db_transaction_level--;
324 if ($_sys_db_transaction_level == 0) {
325 return db_query_params ("ROLLBACK", array(), -1, 0, $dbserver);
332 * db_numrows() - Returns the number of rows in this result set.
334 * @param int Query result set handle.
335 * @return int number of rows.
338 function db_numrows($qhandle) {
339 return @pg_numrows($qhandle);
343 * db_free_result() - Frees a database result properly.
345 * @param int Query result set handle.
347 function db_free_result($qhandle) {
348 return @pg_freeresult($qhandle);
352 * db_result() - Returns a field from a result set.
354 * @param int Query result set handle.
355 * @param integer Row number.
356 * @param string Field name.
357 * @return contents of field from database.
359 function db_result($qhandle,$row,$field) {
360 return @pg_result($qhandle,$row,$field);
364 * db_numfields() - Returns the number of fields in this result set.
366 * @param int Query result set handle.
368 function db_numfields($lhandle) {
369 return @pg_numfields($lhandle);
373 * db_fieldname() - Returns the name of a particular field in the result set
375 * @param int Query result set handle.
376 * @param int Column number.
377 * @return text name of the field.
379 function db_fieldname($lhandle,$fnumber) {
380 return @pg_fieldname($lhandle,$fnumber);
384 * db_affected_rows() - Returns the number of rows changed in the last query.
386 * @param int Query result set handle.
387 * @return int number of affected rows.
389 function db_affected_rows($qhandle) {
390 return @pg_cmdtuples($qhandle);
394 * db_fetch_array() - Returns an associative array from
395 * the current row of this database result
397 * @param int Query result set handle.
398 * @return associative array of fieldname/value key pairs.
400 function db_fetch_array($qhandle, $row=false) {
401 return @pg_fetch_array($qhandle);
405 * db_fetch_array_by_row() - Returns an associative array from
406 * the given row of this database result
408 * @param int Query result set handle.
409 * @param int Given row to fetch
410 * @return associative array of fieldname/value key pairs.
412 function db_fetch_array_by_row($qhandle, $row) {
413 return @pg_fetch_array($qhandle, $row);
417 * db_insertid() - Returns the last primary key from an insert.
419 * @param int Query result set handle.
420 * @param string table_name is the name of the table you inserted into.
421 * @param string pkey_field_name is the field name of the primary key.
422 * @param string Server to which original query was made
423 * @return int id of the primary key or 0 on failure.
425 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=SYS_DB_PRIMARY) {
426 $sql="SELECT max($pkey_field_name) AS id FROM $table_name";
428 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
429 if (db_numrows($res) >0) {
430 return db_result($res,0,'id');
432 // echo "No Rows Matched";
439 * db_error() - Returns the last error from the database.
441 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
442 * @return text error message.
444 function db_error($dbserver=SYS_DB_PRIMARY) {
445 return @pg_errormessage($dbserver);
449 * system_cleanup() - In the future, we may wish to do a number
450 * of cleanup functions at script termination.
452 * For now, we just abort any in-process transaction.
454 function system_cleanup() {
455 global $_sys_db_transaction_level;
456 if ($_sys_db_transaction_level > 0) {
457 echo "Open transaction detected!!!";
458 db_query_params ("ROLLBACK", array ());
462 function db_drop_table_if_exists ($tn) {
463 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
466 $count = db_result($rel,0,0);
468 $sql = "DROP TABLE $tn";
469 $rel = db_query_params ($sql, array ());
474 function db_drop_sequence_if_exists ($tn) {
475 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
478 $count = db_result($rel,0,0);
480 $sql = "DROP SEQUENCE $tn";
481 $rel = db_query_params ($sql, array ());
486 function db_int_array_to_any_clause ($arr) {
488 foreach ($arr as $cur) {
489 if (is_numeric($cur)) {
493 $res = '{' . implode (',', $arr2) . '}' ;
497 function db_string_array_to_any_clause ($arr) {
499 foreach ($arr as $cur) {
500 $arr2[] = pg_escape_string ($cur) ;
502 $res = '{"' . implode ('","', $arr2) . '"}' ;
506 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
507 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
508 $old_qpa = array ('', array(), 0) ;
510 $old_sql = $old_qpa[0] ;
511 $old_params = $old_qpa[1] ;
512 $old_max = $old_qpa[2] ;
515 $params = $old_params ;
518 foreach ($new_params as $index => $value) {
519 $i = count ($new_params) - $index ;
520 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
524 $new_sql = str_replace ('$_', '$', $new_sql) ;
528 return array ($sql, $params, $max) ;
531 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
532 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
537 // c-file-style: "bsd"