specfile
[plewww.git] / includes / database.pgsql.inc
1 <?php
2 // $Id: database.pgsql.inc 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Database interface code for PostgreSQL database servers.
7  */
8
9 /**
10  * @ingroup database
11  * @{
12  */
13
14 /**
15  * Initialize a database connection.
16  *
17  * Note that you can change the pg_connect() call to pg_pconnect() if you
18  * want to use persistent connections. This is not recommended on shared hosts,
19  * and might require additional database/webserver tuning. It can increase
20  * performance, however, when the overhead to connect to your database is high
21  * (e.g. your database and web server live on different machines).
22  */
23 function db_connect($url) {
24    // Check if MySQL support is present in PHP
25   if (!function_exists('pg_connect')) {
26     drupal_maintenance_theme();
27     drupal_set_title('PHP PostgreSQL support not enabled');
28     print theme('maintenance_page', '<p>We were unable to use the PostgreSQL database because the PostgreSQL extension for PHP is not installed. Check your <code>PHP.ini</code> to see how you can enable it.</p>
29 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>');
30     exit;
31   }
32
33   // Cannot parse passwords with @ in them
34   $url = db_parse_url($url);
35
36   // Decode url-encoded information in the db connection string
37   $url['user'] = urldecode($url['user']);
38   $url['pass'] = urldecode($url['pass']);
39   $url['host'] = urldecode($url['host']);
40   $url['path'] = urldecode($url['path']);
41
42   $conn_string = ' user='. $url['user'] .' dbname='. substr($url['path'], 1) .' password='. $url['pass'] . ' host=' . $url['host'];
43   $conn_string .= isset($url['port']) ? ' port=' . $url['port'] : '';
44
45   // pg_last_error() does not return a useful error message for database
46   // connection errors. We must turn on error tracking to get at a good error
47   // message, which will be stored in $php_errormsg.
48   $track_errors_previous = ini_get('track_errors');
49   ini_set('track_errors', 1);
50
51   $connection = @pg_connect($conn_string);
52   if (!$connection) {
53     drupal_maintenance_theme();
54     drupal_set_title('Unable to connect to database');
55     print theme('maintenance_page', '<p>This either means that the database information in your <code>settings.php</code> file is incorrect or we can\'t contact the PostgreSQL database server. This could mean your hosting provider\'s database server is down.</p>
56 <p>The PostgreSQL error was: '. theme('placeholder', decode_entities($php_errormsg)) .'</p>
57 <p>Currently, the database is '. theme('placeholder', substr($url['path'], 1)) .', the username is '. theme('placeholder', $url['user']) .', and the database server is '. theme('placeholder', $url['host']) .'.</p>
58 <ul>
59   <li>Are you sure you have the correct username and password?</li>
60   <li>Are you sure that you have typed the correct hostname?</li>
61   <li>Are you sure you have the correct database name?</li>
62   <li>Are you sure that the database server is running?</li>
63 </ul>
64 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>');
65     exit;
66   }
67
68   // Restore error tracking setting
69   ini_set('track_errors', $track_errors_previous);
70
71   return $connection;
72 }
73
74 /**
75  * Helper function for db_query().
76  */
77 function _db_query($query, $debug = 0) {
78   global $active_db, $last_result, $queries;
79
80   if (variable_get('dev_query', 0)) {
81     list($usec, $sec) = explode(' ', microtime());
82     $timer = (float)$usec + (float)$sec;
83   }
84
85   $last_result = pg_query($active_db, $query);
86
87   if (variable_get('dev_query', 0)) {
88     $bt = debug_backtrace();
89     $query = $bt[2]['function'] . "\n" . $query;
90     list($usec, $sec) = explode(' ', microtime());
91     $stop = (float)$usec + (float)$sec;
92     $diff = $stop - $timer;
93     $queries[] = array($query, $diff);
94   }
95
96   if ($debug) {
97     print '<p>query: '. $query .'<br />error:'. pg_last_error($active_db) .'</p>';
98   }
99
100   if ($last_result !== FALSE) {
101     return $last_result;
102   }
103   else {
104     trigger_error(check_plain(pg_last_error($active_db) ."\nquery: ". $query), E_USER_WARNING);
105     return FALSE;
106   }
107 }
108
109 /**
110  * Fetch one result row from the previous query as an object.
111  *
112  * @param $result
113  *   A database query result resource, as returned from db_query().
114  * @return
115  *   An object representing the next row of the result. The attributes of this
116  *   object are the table fields selected by the query.
117  */
118 function db_fetch_object($result) {
119   if ($result) {
120     return pg_fetch_object($result);
121   }
122 }
123
124 /**
125  * Fetch one result row from the previous query as an array.
126  *
127  * @param $result
128  *   A database query result resource, as returned from db_query().
129  * @return
130  *   An associative array representing the next row of the result. The keys of
131  *   this object are the names of the table fields selected by the query, and
132  *   the values are the field values for this result row.
133  */
134 function db_fetch_array($result) {
135   if ($result) {
136     return pg_fetch_assoc($result);
137   }
138 }
139
140 /**
141  * Determine how many result rows were found by the preceding query.
142  *
143  * @param $result
144  *   A database query result resource, as returned from db_query().
145  * @return
146  *   The number of result rows.
147  */
148 function db_num_rows($result) {
149   if ($result) {
150     return pg_num_rows($result);
151   }
152 }
153
154 /**
155  * Return an individual result field from the previous query.
156  *
157  * Only use this function if exactly one field is being selected; otherwise,
158  * use db_fetch_object() or db_fetch_array().
159  *
160  * @param $result
161  *   A database query result resource, as returned from db_query().
162  * @param $row
163  *   The index of the row whose result is needed.
164  * @return
165  *   The resulting field.
166  */
167 function db_result($result, $row = 0) {
168   if ($result && pg_num_rows($result) > $row) {
169     $res = pg_fetch_row($result, $row);
170
171     return $res[0];
172   }
173 }
174
175 /**
176  * Determine whether the previous query caused an error.
177  */
178 function db_error() {
179   global $active_db;
180   return pg_last_error($active_db);
181 }
182
183 /**
184  * Return a new unique ID in the given sequence.
185  *
186  * For compatibility reasons, Drupal does not use auto-numbered fields in its
187  * database tables. Instead, this function is used to return a new unique ID
188  * of the type requested. If necessary, a new sequence with the given name
189  * will be created.
190  */
191 function db_next_id($name) {
192   $id = db_result(db_query("SELECT nextval('%s_seq')", db_prefix_tables($name)));
193   return $id;
194 }
195
196 /**
197  * Determine the number of rows changed by the preceding query.
198  */
199 function db_affected_rows() {
200   global $last_result;
201   return pg_affected_rows($last_result);
202 }
203
204 /**
205  * Runs a limited-range query in the active database.
206  *
207  * Use this as a substitute for db_query() when a subset of the query
208  * is to be returned.
209  * User-supplied arguments to the query should be passed in as separate
210  * parameters so that they can be properly escaped to avoid SQL injection
211  * attacks.
212  *
213  * @param $query
214  *   A string containing an SQL query.
215  * @param ...
216  *   A variable number of arguments which are substituted into the query
217  *   using printf() syntax. Instead of a variable number of query arguments,
218  *   you may also pass a single array containing the query arguments.
219  *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
220  *   in '') and %%.
221  *
222  *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
223  *   and TRUE values to decimal 1.
224  *
225  * @param $from
226  *   The first result row to return.
227  * @param $count
228  *   The maximum number of result rows to return.
229  * @return
230  *   A database query result resource, or FALSE if the query was not executed
231  *   correctly.
232  */
233 function db_query_range($query) {
234   $args = func_get_args();
235   $count = array_pop($args);
236   $from = array_pop($args);
237   array_shift($args);
238
239   $query = db_prefix_tables($query);
240   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
241     $args = $args[0];
242   }
243   _db_query_callback($args, TRUE);
244   $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
245   $query .= ' LIMIT '. (int)$count .' OFFSET '. (int)$from;
246   return _db_query($query);
247 }
248
249 /**
250  * Runs a SELECT query and stores its results in a temporary table.
251  *
252  * Use this as a substitute for db_query() when the results need to stored
253  * in a temporary table. Temporary tables exist for the duration of the page
254  * request.
255  * User-supplied arguments to the query should be passed in as separate parameters
256  * so that they can be properly escaped to avoid SQL injection attacks.
257  *
258  * Note that if you need to know how many results were returned, you should do
259  * a SELECT COUNT(*) on the temporary table afterwards. db_num_rows() and
260  * db_affected_rows() do not give consistent result across different database
261  * types in this case.
262  *
263  * @param $query
264  *   A string containing a normal SELECT SQL query.
265  * @param ...
266  *   A variable number of arguments which are substituted into the query
267  *   using printf() syntax. The query arguments can be enclosed in one
268  *   array instead.
269  *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
270  *   in '') and %%.
271  *
272  *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
273  *   and TRUE values to decimal 1.
274  *
275  * @param $table
276  *   The name of the temporary table to select into. This name will not be
277  *   prefixed as there is no risk of collision.
278  * @return
279  *   A database query result resource, or FALSE if the query was not executed
280  *   correctly.
281  */
282 function db_query_temporary($query) {
283   $args = func_get_args();
284   $tablename = array_pop($args);
285   array_shift($args);
286
287   $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' AS SELECT', db_prefix_tables($query));
288   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
289     $args = $args[0];
290   }
291   _db_query_callback($args, TRUE);
292   $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
293   return _db_query($query);
294 }
295
296 /**
297  * Returns a properly formatted Binary Large OBject value.
298  * In case of PostgreSQL encodes data for insert into bytea field.
299  *
300  * @param $data
301  *   Data to encode.
302  * @return
303  *  Encoded data.
304  */
305 function db_encode_blob($data) {
306   return "'". pg_escape_bytea($data) ."'";
307 }
308
309 /**
310  * Returns text from a Binary Large OBject value.
311  * In case of PostgreSQL decodes data after select from bytea field.
312  *
313  * @param $data
314  *   Data to decode.
315  * @return
316  *  Decoded data.
317  */
318 function db_decode_blob($data) {
319   return pg_unescape_bytea($data);
320 }
321
322 /**
323  * Prepare user input for use in a database query, preventing SQL injection attacks.
324  * Note: This function requires PostgreSQL 7.2 or later.
325  */
326 function db_escape_string($text) {
327   return pg_escape_string($text);
328 }
329
330 /**
331  * Lock a table.
332  * This function automatically starts a transaction.
333  */
334 function db_lock_table($table) {
335   db_query('BEGIN; LOCK TABLE {'. db_escape_table($table) .'} IN EXCLUSIVE MODE');
336 }
337
338 /**
339  * Unlock all locked tables.
340  * This function automatically commits a transaction.
341  */
342 function db_unlock_tables() {
343   db_query('COMMIT');
344 }
345
346 /**
347  * Verify if the database is set up correctly.
348  */
349 function db_check_setup() {
350   $encoding = db_result(db_query('SHOW server_encoding'));
351   if (!in_array(strtolower($encoding), array('unicode', 'utf8'))) {
352     drupal_set_message(t('Your PostgreSQL database is set up with the wrong character encoding (%encoding). It is possible it will not work as expected. It is advised to recreate it with UTF-8/Unicode encoding. More information can be found in the <a href="%url">PostgreSQL documentation</a>.', array('%encoding' => $encoding, '%url' => 'http://www.postgresql.org/docs/7.4/interactive/multibyte.html')), 'status');
353   }
354 }
355
356 /**
357  * @} End of "ingroup database".
358  */
359
360