Better list_all method
[ajatus.git] / plugins / ajatus / couchdb / databases.php
blob3daff94ea06deccb34a33a9e8cb8437847fd48ca
1 <?php
2 /**
3 *
4 * Copyright (c) 2007 Jerry Jalava <jerry.jalava@gmail.com>
5 * Licensed under the GPLv3 license
6 * http://www.gnu.org/licenses/gpl.html
7 *
8 */
10 class couchdb_databases
12 private $configuration;
13 private $cache = array();
15 public function __construct(&$configuration)
17 $this->configuration =& $configuration;
20 public function __get($name)
22 return $this->get($name);
25 public function __set($name, $value)
27 if ($value === false)
29 return $this->delete($name);
32 //TODO: Add rename option here also.
33 /**
34 * If $value is string -> create $value -> copy contents of $name to $value -> remove $name
35 **/
37 return $this->create($name);
40 public function __isset($name)
42 return $this->exists($name);
45 public function get_all($names_only=false)
47 $transport = new couchdb_transport($this->configuration);
49 try
51 $names = $transport->free_execute('_all_dbs');
53 if ($names_only)
55 return $names;
58 $dbs = array();
59 foreach ($names as $dbname)
61 $dbs[$dbname] = new couchdb_databases_database($dbname, $this->configuration);
64 return $dbs;
66 catch (couchdb_transport_exception $e)
68 throw new couchdb_database_exception("Unknown error occured while listing databases. {$e}");
72 public function create($name)
74 $db = new couchdb_databases_database($name, $this->configuration);
75 return $db->create();
78 public function delete($name)
80 $this->exists($name);
81 $db = new couchdb_databases_database($name, $this->configuration);
83 return $db->delete();
86 private function &get($name)
88 if (! isset($this->cache[$name]))
90 $this->cache[$name] = $this->exists($name);
93 return $this->cache[$name];
96 private function exists($name, $graceful=false)
98 try
100 $db = new couchdb_databases_database($name, $this->configuration);
101 return $db->exists();
103 catch(couchdb_database_exception $e)
105 if ($graceful)
107 return false;
110 if ($e->getCode() == 404)
112 throw new couchdb_database_exception("Couldn't find database '{$name}'!");
115 throw $e;
118 return false;
121 public function clear_caches()
123 foreach ($this->cache as $name => $db)
125 $db->clear_caches();
128 $this->cache = array();