1 <?php rcs_id('$Id: DbaDatabase.php,v 1.8 2004-04-06 20:00:10 rurban Exp $');
3 require_once('lib/ErrorManager.php');
4 // FIXME: autodetect supported handlers.
6 define('DBA_DATABASE_DEFAULT_TIMEOUT', 20);
10 function DbaDatabase($filename, $mode = false, $handler = 'gdbm') {
11 $this->_file = $filename;
12 $this->_handler = $handler;
13 $this->_timeout = DBA_DATABASE_DEFAULT_TIMEOUT;
19 function set_timeout($timeout) {
20 $this->_timeout = $timeout;
23 function open($mode = 'w') {
25 return; // already open.
27 $watchdog = $this->_timeout;
30 $this->_dba_open_error = false;
31 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_dba_open_error_handler'));
33 // oops, you don't have DBM support.
34 if (!function_exists("dba_open")) {
35 echo "You don't seem to have DBM file support compiled into PHP.";
38 // PHP 4.3.x Windows lock bug workaround: http://bugs.php.net/bug.php?id=23975
39 if (isWindows() and (strlen($mode) == 1)) {
40 $mode .= "-"; // add locking
42 while (($dbh = dba_open($this->_file, $mode, $this->_handler)) < 1) {
48 $ErrorManager->popErrorHandler();
51 if ( ($error = $this->_dba_open_error) ) {
52 $error->errno = E_USER_ERROR;
53 $ErrorManager->handleError($error);
56 trigger_error("dba_open failed", E_USER_ERROR);
65 dba_close($this->_dbh);
69 function exists($key) {
70 return dba_exists($key, $this->_dbh);
73 function fetch($key) {
74 $val = dba_fetch($key, $this->_dbh);
76 return $this->_error("fetch($key)");
80 function insert($key, $val) {
81 if (!dba_insert($key, $val, $this->_dbh))
82 return $this->_error("insert($key)");
85 function replace($key, $val) {
86 if (!dba_replace($key, $val, $this->_dbh))
87 return $this->_error("replace($key)");
92 return dba_firstkey($this->_dbh);
96 return dba_nextkey($this->_dbh);
99 function delete($key) {
100 if (!dba_delete($key, $this->_dbh))
101 return $this->_error("delete($key)");
105 return dba_fetch($key, $this->_dbh);
108 function set($key, $val) {
110 if (dba_exists($key, $dbh)) {
111 if ($val !== false) {
112 if (!dba_replace($key, $val, $dbh))
113 return $this->_error("store[replace]($key)");
116 if (!dba_delete($key, $dbh))
117 return $this->_error("store[delete]($key)");
121 if (!dba_insert($key, $val, $this->_dbh))
122 return $this->_error("store[insert]($key)");
127 if (!dba_sync($this->_dbh))
128 return $this->_error("sync()");
131 function optimize() {
132 if (!dba_optimize($this->_dbh))
133 return $this->_error("optimize()");
137 function _error($mes) {
138 trigger_error("DbaDatabase: $mes", E_USER_WARNING);
141 trigger_error("$this->_file: dba error: $mes", E_USER_ERROR);
146 for ($key = $this->firstkey($dbh); $key; $key = $this->nextkey($dbh))
147 printf("%10s: %s\n", $key, $this->fetch($key));
150 function _dba_open_error_handler ($error) {
151 $this->_dba_open_error = $error;
157 // (c-file-style: "gnu")
162 // c-hanging-comment-ender-p: nil
163 // indent-tabs-mode: nil