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)) {
109 function db_switcher(&$dbserver=NULL) {
112 case 'SYS_DB_PRIMARY':
113 $dbserver = SYS_DB_PRIMARY ;
116 $dbserver = SYS_DB_STATS ;
119 $dbserver = SYS_DB_TROVE ;
121 case 'SYS_DB_SEARCH':
122 $dbserver = SYS_DB_SEARCH ;
125 $dbserver = SYS_DB_PRIMARY ;
130 * db_query() - Query the database.
132 * @deprecated since 4.8. Use db_query_params() instead!
134 * @param text SQL statement.
135 * @param int How many rows do you want returned.
136 * @param int Of matching rows, return only rows starting here.
137 * @param int ability to spread load to multiple db servers.
138 * @return int result set handle.
140 function db_query($qstring,$limit='-1',$offset=0,$dbserver=NULL) {
141 db_connect_if_needed () ;
142 db_switcher ($dbserver) ;
147 if (!$limit || !is_numeric($limit) || $limit < 0) {
151 if (!$offset || !is_numeric($offset) || $offset < 0) {
154 $qstring=$qstring." LIMIT $limit OFFSET $offset";
157 $res = @pg_query($dbserver,$qstring);
159 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
160 error_log('SQL> '.db_error());
162 //echo "\n<br />|*| [$qstring]: ".db_error();
167 * db_query_from_file() - Query the database, from a file.
169 * @param string File that contains the SQL statements.
170 * @param int How many rows do you want returned.
171 * @param int Of matching rows, return only rows starting here.
172 * @param int ability to spread load to multiple db servers.
173 * @return int result set handle.
175 function db_query_from_file($file,$limit='-1',$offset=0,$dbserver=NULL) {
176 db_connect_if_needed () ;
177 db_switcher ($dbserver) ;
182 $qstring = file_get_contents($file);
184 error_log('db_query_from_file(): Cannot read file $file!');
187 if (!$limit || !is_numeric($limit) || $limit < 0) {
191 if (!$offset || !is_numeric($offset) || $offset < 0) {
194 $qstring=$qstring." LIMIT $limit OFFSET $offset";
196 $res = @pg_query($dbserver,$qstring);
198 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
199 error_log('SQL> '.db_error());
201 //echo "\n<br />|*| [$qstring]: ".db_error();
206 * db_query_params() - Query the database, with parameters
208 * @param text SQL statement.
209 * @param array parameters
210 * @param int How many rows do you want returned.
211 * @param int Of matching rows, return only rows starting here.
212 * @param int ability to spread load to multiple db servers.
213 * @return int result set handle.
215 function db_query_params($qstring,$params,$limit='-1',$offset=0,$dbserver=NULL) {
216 db_connect_if_needed () ;
217 db_switcher ($dbserver) ;
222 if (!$limit || !is_numeric($limit) || $limit < 0) {
226 if (!$offset || !is_numeric($offset) || $offset < 0) {
229 $qstring=$qstring." LIMIT $limit OFFSET $offset";
232 $res = @pg_query_params($dbserver,$qstring,$params);
234 error_log('SQL: '. preg_replace('/\n\t+/', ' ',$qstring));
235 error_log('SQL> '.db_error());
241 * db_query_params() - Query the database, with a query+params array
243 * @param array array(query, array(parameters...))
244 * @param int How many rows do you want returned.
245 * @param int Of matching rows, return only rows starting here.
246 * @param int ability to spread load to multiple db servers.
247 * @return int result set handle.
249 function db_query_qpa ($qpa,$limit='-1',$offset=0,$dbserver=NULL) {
252 return db_query_params ($sql, $params, $limit, $offset, $dbserver) ;
256 * db_mquery() - Query the database.
258 * @deprecated since 4.8. Use db_query_params() instead!
260 * @param text SQL statement.
261 * @param int How many rows do you want returned.
262 * @param int Of matching rows, return only rows starting here.
263 * @param int ability to spread load to multiple db servers.
264 * @return int result set handle.
266 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=NULL) {
267 return db_query($qstring, $limit, $offset, $dbserver);
271 * db_more_results() - Check if there are more unprocessed results.
273 * @return bool true if there are more results..
275 function db_more_results() {
280 * db_next_result() - Get the next result from query with multiple statements.
282 * @param string SQL statement
283 * @param int How many rows do you want returned
284 * @param int Of matching rows, return only rows starting here
286 function db_next_result() {
290 /* Current transaction level, private variable */
291 /* FIXME: Having scalar variable for transaction level is
292 no longer correct after multiple database (dbservers) support
293 introduction. However, it is true that in one given PHP
294 script, at most one db is modified, so this works for now. */
295 $_sys_db_transaction_level = 0;
298 * db_begin() - Begin a transaction.
300 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
303 function db_begin($dbserver=NULL) {
304 global $_sys_db_transaction_level;
306 // start database transaction only for the top-level
307 // programmatical transaction
308 $_sys_db_transaction_level++;
309 if ($_sys_db_transaction_level == 1) {
310 return db_query_params ("BEGIN WORK", array(), -1, 0, $dbserver);
317 * db_commit() - Commit a transaction.
319 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
320 * @return true on success/false on failure.
322 function db_commit($dbserver=NULL) {
323 global $_sys_db_transaction_level;
325 // check for transaction stack underflow
326 if ($_sys_db_transaction_level == 0) {
327 echo "COMMIT underflow<br />";
331 // commit database transaction only when top-level
332 // programmatical transaction ends
333 $_sys_db_transaction_level--;
334 if ($_sys_db_transaction_level == 0) {
335 return db_query_params ("COMMIT", array(), -1, 0, $dbserver);
342 * db_rollback() - Rollback 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_rollback($dbserver=NULL) {
348 global $_sys_db_transaction_level;
350 // check for transaction stack underflow
351 if ($_sys_db_transaction_level == 0) {
352 echo "ROLLBACK underflow<br />";
356 // rollback 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 ("ROLLBACK", array(), -1, 0, $dbserver);
367 * db_numrows() - Returns the number of rows in this result set.
369 * @param int Query result set handle.
370 * @return int number of rows.
373 function db_numrows($qhandle) {
374 return @pg_numrows($qhandle);
378 * db_free_result() - Frees a database result properly.
380 * @param int Query result set handle.
382 function db_free_result($qhandle) {
383 return @pg_freeresult($qhandle);
387 * db_result() - Returns a field from a result set.
389 * @param int Query result set handle.
390 * @param integer Row number.
391 * @param string Field name.
392 * @return contents of field from database.
394 function db_result($qhandle,$row,$field) {
395 return @pg_result($qhandle,$row,$field);
399 * db_numfields() - Returns the number of fields in this result set.
401 * @param int Query result set handle.
403 function db_numfields($lhandle) {
404 return @pg_numfields($lhandle);
408 * db_fieldname() - Returns the name of a particular field in the result set
410 * @param int Query result set handle.
411 * @param int Column number.
412 * @return text name of the field.
414 function db_fieldname($lhandle,$fnumber) {
415 return @pg_fieldname($lhandle,$fnumber);
419 * db_affected_rows() - Returns the number of rows changed in the last query.
421 * @param int Query result set handle.
422 * @return int number of affected rows.
424 function db_affected_rows($qhandle) {
425 return @pg_cmdtuples($qhandle);
429 * db_fetch_array() - Returns an associative array from
430 * the current row of this database result
432 * @param int Query result set handle.
433 * @return associative array of fieldname/value key pairs.
435 function db_fetch_array($qhandle, $row=false) {
436 return @pg_fetch_array($qhandle);
440 * db_fetch_array_by_row() - Returns an associative array from
441 * the given row of this database result
443 * @param int Query result set handle.
444 * @param int Given row to fetch
445 * @return associative array of fieldname/value key pairs.
447 function db_fetch_array_by_row($qhandle, $row) {
448 return @pg_fetch_array($qhandle, $row);
452 * db_insertid() - Returns the last primary key from an insert.
454 * @param int Query result set handle.
455 * @param string table_name is the name of the table you inserted into.
456 * @param string pkey_field_name is the field name of the primary key.
457 * @param string Server to which original query was made
458 * @return int id of the primary key or 0 on failure.
460 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=NULL) {
461 $sql="SELECT max($pkey_field_name) AS id FROM $table_name";
463 $res = db_query_params ($sql, array(), -1, 0, $dbserver);
464 if (db_numrows($res) >0) {
465 return db_result($res,0,'id');
467 // echo "No Rows Matched";
474 * db_error() - Returns the last error from the database.
476 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
477 * @return text error message.
479 function db_error($dbserver=NULL) {
480 return @pg_errormessage($dbserver);
484 * system_cleanup() - In the future, we may wish to do a number
485 * of cleanup functions at script termination.
487 * For now, we just abort any in-process transaction.
489 function system_cleanup() {
490 global $_sys_db_transaction_level;
491 if ($_sys_db_transaction_level > 0) {
492 echo "Open transaction detected!!!";
493 db_query_params ("ROLLBACK", array ());
497 function db_drop_table_if_exists ($tn) {
498 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
501 $count = db_result($rel,0,0);
503 $sql = "DROP TABLE $tn";
504 $rel = db_query_params ($sql, array ());
509 function db_drop_sequence_if_exists ($tn) {
510 $rel = db_query_params ('SELECT COUNT(*) FROM pg_class WHERE relname=$1 and relkind=$2',
513 $count = db_result($rel,0,0);
515 $sql = "DROP SEQUENCE $tn";
516 $rel = db_query_params ($sql, array ());
521 function db_int_array_to_any_clause ($arr) {
523 foreach ($arr as $cur) {
524 if (is_numeric($cur)) {
528 $res = '{' . implode (',', $arr2) . '}' ;
532 function db_string_array_to_any_clause ($arr) {
534 foreach ($arr as $cur) {
535 $arr2[] = pg_escape_string ($cur) ;
537 $res = '{"' . implode ('","', $arr2) . '"}' ;
541 function db_construct_qpa ($old_qpa = false, $new_sql = '', $new_params = array ()) {
542 if (!is_array($old_qpa) || count ($old_qpa) < 3) {
543 $old_qpa = array ('', array(), 0) ;
545 $old_sql = $old_qpa[0] ;
546 $old_params = $old_qpa[1] ;
547 $old_max = $old_qpa[2] ;
550 $params = $old_params ;
553 foreach ($new_params as $index => $value) {
554 $i = count ($new_params) - $index ;
555 $new_sql = preg_replace ('/\\$'.$i.'(?!\d)/', '$_'.($i + $old_max), $new_sql) ;
559 $new_sql = str_replace ('$_', '$', $new_sql) ;
563 return array ($sql, $params, $max) ;
566 function db_join_qpa ($old_qpa = false, $new_qpa = false) {
567 return db_construct_qpa ($old_qpa, $new_qpa[0], $new_qpa[1]) ;
572 // c-file-style: "bsd"