3 * database.php - The database abstraction library
4 * This is the PostgreSQL version of our database connection/querying layer
6 * Copyright 1999-2001 (c) VA Linux Systems
10 * This file is part of GForge.
12 * GForge is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * GForge is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with GForge; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 //$gfconn - database connection handle
30 * Current row for each result set
32 * @var array $sys_db_row_pointer
34 $sys_db_row_pointer=array(); //current row for each result set
37 * pg_connectstring() - builds a postgres connection string.
38 * Combines the supplied arguments into a valid, specific, postgresql
39 * connection string. It only includes the host and port options
40 * if specified. Without those options, it will use the unix domain
41 * sockets to connect to the postgres server on the local machine.
43 * @author Graham Batty graham@sandworm.ca
44 * @param dbname The database to connect to. Required.
45 * @param user The username used to connect. Required
46 * @param password The password used to connect
47 * @param host The hostname to connect to, if not localhost
48 * @param port The port to connect to, if not 5432
49 * @return string The connection string to pass to pg_connect()
52 function pg_connectstring($dbname, $user, $password = "", $host = "", $port = "") {
53 $string = "dbname=$dbname user=$user";
55 $string .= " password=$password";
57 $string .= " host=$host";
60 $string .= " port=$port";
67 * db_connect() - Connect to the database
68 * Notice the global vars that must be set up
69 * Sets up a global $gfconn variable which is used
70 * in other functions in this library.
72 function db_connect() {
73 global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$gfconn,
74 $sys_dbname,$sys_db_use_replication,$sys_dbport,$sys_dbreaddb,$sys_dbreadhost;
77 // Connect to primary database
79 if (function_exists("pg_pconnect")) {
80 $gfconn = pg_pconnect(pg_connectstring($sys_dbname, $sys_dbuser, $sys_dbpasswd, $sys_dbhost, $sys_dbport));
82 print("function pg_pconnect doesn't exist: no postgresql interface");
87 // If any replication is configured, connect
89 if ($sys_db_use_replication) {
90 $gfconn2 = pg_pconnect(pg_connectstring($sys_dbreaddb, $sys_dbuser, $sys_dbpasswd, $sys_dbreadhost, $sys_dbreadport));
96 // Now map the physical database connections to the
97 // "virtual" list that is used to distribute load in db_query()
99 define('SYS_DB_PRIMARY', $gfconn);
100 define('SYS_DB_STATS', $gfconn2);
101 define('SYS_DB_TROVE', $gfconn2);
102 define('SYS_DB_SEARCH', $gfconn2);
104 // Register top-level "finally" handler to abort current
105 // transaction in case of error
106 register_shutdown_function("system_cleanup");
110 * db_query() - Query the database.
112 * @param text SQL statement.
113 * @param int How many rows do you want returned.
114 * @param int Of matching rows, return only rows starting here.
115 * @param int ability to spread load to multiple db servers.
116 * @return int result set handle.
118 function db_query($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
122 if (!$limit || !is_numeric($limit) || $limit < 0) {
126 if (!$offset || !is_numeric($offset) || $offset < 0) {
129 $qstring=$qstring." LIMIT $limit OFFSET $offset";
132 //$GLOBALS['G_DEBUGQUERY'] .= $qstring .' |<font size="-2">'.$dbserver.'</font>'. "<p>\n";
133 $res = @pg_exec($dbserver,$qstring);
134 //echo "\n<br />|*| [$qstring]: ".db_error();
139 * db_mquery() - Query the database.
141 * @param text SQL statement.
142 * @param int How many rows do you want returned.
143 * @param int Of matching rows, return only rows starting here.
144 * @param int ability to spread load to multiple db servers.
145 * @return int result set handle.
147 function db_mquery($qstring,$limit='-1',$offset=0,$dbserver=SYS_DB_PRIMARY) {
148 return db_query($qstring, $limit, $offset, $dbserver);
152 * db_more_results() - Check if there are more unprocessed results.
154 * @return bool true if there are more results..
156 function db_more_results() {
161 * db_next_result() - Get the next result from query with multiple statements.
163 * @param string SQL statement
164 * @param int How many rows do you want returned
165 * @param int Of matching rows, return only rows starting here
167 function db_next_result() {
171 /* Current transaction level, private variable */
172 /* FIXME: Having scalar variable for transaction level is
173 no longer correct after multiple database (dbservers) support
174 introduction. However, it is true that in one given PHP
175 script, at most one db is modified, so this works for now. */
176 $_sys_db_transaction_level = 0;
179 * db_begin() - Begin a transaction.
181 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
184 function db_begin($dbserver=SYS_DB_PRIMARY) {
185 global $_sys_db_transaction_level;
187 // start database transaction only for the top-level
188 // programmatical transaction
189 $_sys_db_transaction_level++;
190 if ($_sys_db_transaction_level == 1) {
191 return db_query("BEGIN WORK", -1, 0, $dbserver);
198 * db_commit() - Commit a transaction.
200 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
201 * @return true on success/false on failure.
203 function db_commit($dbserver=SYS_DB_PRIMARY) {
204 global $_sys_db_transaction_level;
206 // check for transaction stack underflow
207 if ($_sys_db_transaction_level == 0) {
208 echo "COMMIT underflow<br />";
212 // commit database transaction only when top-level
213 // programmatical transaction ends
214 $_sys_db_transaction_level--;
215 if ($_sys_db_transaction_level == 0) {
216 return db_query("COMMIT", -1, 0, $dbserver);
223 * db_rollback() - Rollback a transaction.
225 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
226 * @return true on success/false on failure.
228 function db_rollback($dbserver=SYS_DB_PRIMARY) {
229 global $_sys_db_transaction_level;
231 // check for transaction stack underflow
232 if ($_sys_db_transaction_level == 0) {
233 echo "ROLLBACK underflow<br />";
237 // rollback database transaction only when top-level
238 // programmatical transaction ends
239 $_sys_db_transaction_level--;
240 if ($_sys_db_transaction_level == 0) {
241 return db_query("ROLLBACK", -1, 0, $dbserver);
248 * db_numrows() - Returns the number of rows in this result set.
250 * @param int Query result set handle.
251 * @return int number of rows.
254 function db_numrows($qhandle) {
255 return @pg_numrows($qhandle);
259 * db_free_result() - Frees a database result properly.
261 * @param int Query result set handle.
263 function db_free_result($qhandle) {
264 return @pg_freeresult($qhandle);
268 * db_reset_result() - Reset is useful for db_fetch_array
269 * sometimes you need to start over.
271 * @param int Query result set handle.
272 * @param integer Row number.
275 function db_reset_result($qhandle,$row=0) {
276 global $sys_db_row_pointer;
277 return $sys_db_row_pointer[$qhandle]=$row;
281 * db_result() - Returns a field from a result set.
283 * @param int Query result set handle.
284 * @param integer Row number.
285 * @param string Field name.
286 * @return contents of field from database.
288 function db_result($qhandle,$row,$field) {
289 return @pg_result($qhandle,$row,$field);
293 * db_numfields() - Returns the number of fields in this result set.
295 * @param int Query result set handle.
297 function db_numfields($lhandle) {
298 return @pg_numfields($lhandle);
302 * db_fieldname() - Returns the name of a particular field in the result set
304 * @param int Query result set handle.
305 * @param int Column number.
306 * @return text name of the field.
308 function db_fieldname($lhandle,$fnumber) {
309 return @pg_fieldname($lhandle,$fnumber);
313 * db_affected_rows() - Returns the number of rows changed in the last query.
315 * @param int Query result set handle.
316 * @return int number of affected rows.
318 function db_affected_rows($qhandle) {
319 return @pg_cmdtuples($qhandle);
323 * db_fetch_array() - Returns an associative array from
324 * the current row of this database result
325 * Use db_reset_result to seek a particular row.
327 * @param int Query result set handle.
328 * @return associative array of fieldname/value key pairs.
330 function db_fetch_array($qhandle) {
331 global $sys_db_row_pointer;
332 if(!isset($sys_db_row_pointer[$qhandle])) {
333 $sys_db_row_pointer[$qhandle] = 0;
335 $sys_db_row_pointer[$qhandle]++;
336 return @pg_fetch_array($qhandle,($sys_db_row_pointer[$qhandle]-1));
340 * db_insertid() - Returns the last primary key from an insert.
342 * @param int Query result set handle.
343 * @param string table_name is the name of the table you inserted into.
344 * @param string pkey_field_name is the field name of the primary key.
345 * @param string Server to which original query was made
346 * @return int id of the primary key or 0 on failure.
348 function db_insertid($qhandle,$table_name,$pkey_field_name,$dbserver=SYS_DB_PRIMARY) {
349 $sql="SELECT max($pkey_field_name) AS id FROM $table_name";
351 $res=db_query($sql, -1, 0, $dbserver);
352 if (db_numrows($res) >0) {
353 return db_result($res,0,'id');
355 // echo "No Rows Matched";
362 * db_error() - Returns the last error from the database.
364 * @param constant Database server (SYS_DB_PRIMARY, SYS_DB_STATS, SYS_DB_TROVE, SYS_DB_SEARCH)
365 * @return text error message.
367 function db_error($dbserver=SYS_DB_PRIMARY) {
368 return @pg_errormessage($dbserver);
372 * system_cleanup() - In the future, we may wish to do a number
373 * of cleanup functions at script termination.
375 * For now, we just abort any in-process transaction.
377 function system_cleanup() {
378 global $_sys_db_transaction_level;
379 if ($_sys_db_transaction_level > 0) {
380 echo "Open transaction detected!!!";
381 db_query("ROLLBACK");
385 function db_drop_table_if_exists ($tn) {
386 $sql = "SELECT COUNT(*) FROM pg_class WHERE relname='$tn';";
387 $rel = db_query($sql);
389 $count = db_result($rel,0,0);
391 $sql = "DROP TABLE $tn;";
392 $rel = db_query ($sql);
397 function db_drop_sequence_if_exists ($tn) {
398 $sql = "SELECT COUNT(*) FROM pg_class WHERE relname='$tn';";
399 $rel = db_query($sql);
401 $count = db_result($rel,0,0);
403 $sql = "DROP SEQUENCE $tn;";
404 $rel = db_query ($sql);
411 // c-file-style: "bsd"