4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | PEAR:DB wrapper class that implements PEAR MDB2 functions |
13 | See http://pear.php.net/package/MDB2 |
15 +-----------------------------------------------------------------------+
16 | Author: Lukas Kahwe Smith <smith@pooteeweet.org> |
17 +-----------------------------------------------------------------------+
19 $Id: rcube_mdb2.inc 239 2006-05-18 21:25:11Z roundcube $
25 * Obtain the PEAR::DB class that is used for abstraction
27 require_once('MDB2.php');
31 * Database independent query interface
33 * This is a wrapper for the PEAR::MDB2 class
35 * @package RoundCube Webmail
36 * @author David Saez Padros <david@ols.es>
37 * @author Thomas Bruederli <roundcube@gmail.com>
38 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
40 * @link http://pear.php.net/package/MDB2
44 var $db_dsnw; // DSN for write operations
45 var $db_dsnr; // DSN for read operations
46 var $db_connected = false; // Already connected ?
47 var $db_mode = ''; // Connection mode
48 var $db_handle = 0; // Connection handle
49 var $db_error = false;
50 var $db_error_msg = '';
52 var $a_query_results = array('dummy');
59 * @param string DSN for read/write operations
60 * @param string Optional DSN for read only operations
62 function __construct($db_dsnw, $db_dsnr='')
67 $this->db_dsnw = $db_dsnw;
68 $this->db_dsnr = $db_dsnr;
70 $dsn_array = MDB2::parseDSN($db_dsnw);
71 $this->db_provider = $dsn_array['phptype'];
76 * PHP 4 object constructor
78 * @see rcube_MDB2::__construct
80 function rcube_db($db_dsnw,$db_dsnr='')
82 $this->__construct($db_dsnw,$db_dsnr);
87 * Connect to specific database
89 * @param string DSN for DB connections
90 * @return object PEAR database handle
93 function dsn_connect($dsn)
95 // Use persistent connections if available
96 $dbh = MDB2::connect($dsn, array('persistent' => TRUE, 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL));
98 if (PEAR::isError($dbh))
100 $this->db_error = TRUE;
101 $this->db_error_msg = $dbh->getMessage();
103 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
104 'message' => $dbh->getMessage()), TRUE, FALSE);
107 else if ($this->db_provider=='sqlite')
109 $dsn_array = MDB2::parseDSN($dsn);
110 if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
111 $this->_sqlite_create_database($dbh, $this->sqlite_initials);
119 * Connect to appropiate databse
120 * depending on the operation
122 * @param string Connection mode (r|w)
125 function db_connect($mode)
127 $this->db_mode = $mode;
130 if ($this->db_connected)
132 // no replication, current connection is ok
133 if ($this->db_dsnw==$this->db_dsnr)
136 // connected to master, current connection is ok
137 if ($this->db_mode=='w')
140 // Same mode, current connection is ok
141 if ($this->db_mode==$mode)
146 $dsn = $this->db_dsnr;
148 $dsn = $this->db_dsnw;
150 $this->db_handle = $this->dsn_connect($dsn);
151 $this->db_connected = true;
157 * Getter for error state
159 * @param boolean True on error
163 return $this->db_error ? $this->db_error_msg : FALSE;
168 * Execute a SQL query
170 * @param string SQL query to execute
171 * @param mixed Values to be inserted in query
172 * @return number Query handle identifier
177 $params = func_get_args();
178 $query = array_shift($params);
180 return $this->_query($query, 0, 0, $params);
185 * Execute a SQL query with limits
187 * @param string SQL query to execute
188 * @param number Offset for LIMIT statement
189 * @param number Number of rows for LIMIT statement
190 * @param mixed Values to be inserted in query
191 * @return number Query handle identifier
194 function limitquery()
196 $params = func_get_args();
197 $query = array_shift($params);
198 $offset = array_shift($params);
199 $numrows = array_shift($params);
201 return $this->_query($query, $offset, $numrows, $params);
206 * Execute a SQL query with limits
208 * @param string SQL query to execute
209 * @param number Offset for LIMIT statement
210 * @param number Number of rows for LIMIT statement
211 * @param array Values to be inserted in query
212 * @return number Query handle identifier
215 function _query($query, $offset, $numrows, $params)
218 if (strtolower(trim(substr($query,0,6)))=='select')
223 $this->db_connect($mode);
225 if ($this->db_provider == 'sqlite')
226 $this->_sqlite_prepare();
228 if ($numrows || $offset)
229 $result = $this->db_handle->setLimit($numrows,$offset);
232 $result = $this->db_handle->query($query);
235 $params = (array)$params;
236 $q = $this->db_handle->prepare($query);
237 if ($this->db_handle->isError($q))
239 $this->db_error = TRUE;
240 $this->db_error_msg = $q->userinfo;
242 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
243 'message' => $this->db_error_msg), TRUE, TRUE);
247 $result = $q->execute($params);
252 // add result, even if it's an error
253 return $this->_add_result($result);
258 * Get number of rows for a SQL query
259 * If no query handle is specified, the last query will be taken as reference
261 * @param number Optional query handle identifier
262 * @return mixed Number of rows or FALSE on failure
265 function num_rows($res_id=NULL)
267 if (!$this->db_handle)
270 if ($result = $this->_get_result($res_id))
271 return $result->numRows();
278 * Get number of affected rows fort he last query
280 * @return mixed Number of rows or FALSE on failure
283 function affected_rows($result = null)
285 if (!$this->db_handle)
293 * Get last inserted record ID
294 * For Postgres databases, a sequence name is required
296 * @param string Sequence name for increment
297 * @return mixed ID or FALSE on failure
300 function insert_id($sequence = '')
302 if (!$this->db_handle || $this->db_mode=='r')
305 return $this->db_handle->lastInsertID($sequence);
310 * Get an associative array for one row
311 * If no query handle is specified, the last query will be taken as reference
313 * @param number Optional query handle identifier
314 * @return mixed Array with col values or FALSE on failure
317 function fetch_assoc($res_id=NULL)
319 $result = $this->_get_result($res_id);
320 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
325 * Get an index array for one row
326 * If no query handle is specified, the last query will be taken as reference
328 * @param number Optional query handle identifier
329 * @return mixed Array with col values or FALSE on failure
332 function fetch_array($res_id=NULL)
334 $result = $this->_get_result($res_id);
335 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
340 * Get co values for a result row
342 * @param object Query result handle
343 * @param number Fetch mode identifier
344 * @return mixed Array with col values or FALSE on failure
347 function _fetch_row($result, $mode)
349 if (PEAR::isError($result))
351 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
352 'message' => $this->db_link->getMessage()), TRUE, FALSE);
356 return $result->fetchRow($mode);
361 * Formats input so it can be safely used in a query
363 * @param mixed Value to quote
364 * @return string Quoted/converted string for use in query
367 function quote($input, $type = null)
369 // create DB handle if not available
370 if (!$this->db_handle)
371 $this->db_connect('r');
373 // escape pear identifier chars
374 $rep_chars = array('?' => '\?',
378 return $this->db_handle->quote($input, $type);
383 * Quotes a string so it can be safely used as a table or column name
385 * @param string Value to quote
386 * @return string Quoted string for use in query
387 * @deprecated Replaced by rcube_MDB2::quote_identifier
388 * @see rcube_MDB2::quote_identifier
391 function quoteIdentifier($str)
393 return $this->quote_identifier($str);
398 * Quotes a string so it can be safely used as a table or column name
400 * @param string Value to quote
401 * @return string Quoted string for use in query
404 function quote_identifier($str)
406 if (!$this->db_handle)
407 $this->db_connect('r');
409 return $this->db_handle->quoteIdentifier($str);
414 * Return SQL statement to convert a field value into a unix timestamp
416 * @param string Field name
417 * @return string SQL statement to use in query
420 function unixtimestamp($field)
422 switch($this->db_provider)
425 return "EXTRACT (EPOCH FROM $field)";
429 return "UNIX_TIMESTAMP($field)";
435 * Return SQL statement to convert from a unix timestamp
437 * @param string Field name
438 * @return string SQL statement to use in query
441 function fromunixtime($timestamp)
443 switch($this->db_provider)
448 return "FROM_UNIXTIME($timestamp)";
451 return date("'Y-m-d H:i:s'", $timestamp);
457 * Adds a query result and returns a handle ID
459 * @param object Query handle
460 * @return mixed Handle ID or FALE on failure
463 function _add_result($res)
466 if (PEAR::isError($res))
468 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
469 'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)), TRUE, FALSE);
474 $res_id = sizeof($this->a_query_results);
475 $this->a_query_results[$res_id] = $res;
476 $this->last_res_id = $res_id;
483 * Resolves a given handle ID and returns the according query handle
484 * If no ID is specified, the last ressource handle will be returned
486 * @param number Handle ID
487 * @return mixed Ressource handle or FALE on failure
490 function _get_result($res_id=NULL)
493 $res_id = $this->last_res_id;
495 if ($res_id && isset($this->a_query_results[$res_id]))
496 return $this->a_query_results[$res_id];
503 * Create a sqlite database from a file
505 * @param object SQLite database handle
506 * @param string File path to use for DB creation
509 function _sqlite_create_database($dbh, $file_name)
511 if (empty($file_name) || !is_string($file_name))
515 if ($fd = fopen($file_name, 'r'))
517 $data = fread($fd, filesize($file_name));
522 sqlite_exec($dbh->connection, $data);
527 * Add some proprietary database functions to the current SQLite handle
528 * in order to make it MySQL compatible
532 function _sqlite_prepare()
534 include_once('include/rcube_sqlite.inc');
536 // we emulate via callback some missing MySQL function
537 sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
538 sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
539 sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
540 sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
544 } // end class rcube_db