Permalink
Browse files

cleaning

  • Loading branch information...
1 parent c9ca16b commit 0075cc2aee1eca6af31bf32a2d13bfffee5c87a7 @aboekhoff aboekhoff committed Nov 29, 2009
View
BIN build/classes/somnium/congomongo/ClojureDBObject.class
Binary file not shown.
View
172 src/main/clj/somnium/congomongo.clj
@@ -1,172 +0,0 @@
-; Copyright (c) 2009 Andrew Boekhoff
-
-; Permission is hereby granted, free of charge, to any person obtaining a copy
-; of this software and associated documentation files (the "Software"), to deal
-; in the Software without restriction, including without limitation the rights
-; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-; copies of the Software, and to permit persons to whom the Software is
-; furnished to do so, subject to the following conditions:
-
-; The above copyright notice and this permission notice shall be included in
-; all copies or substantial portions of the Software.
-
-; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-; THE SOFTWARE.
-
-(ns
- #^{:author "Andrew Boekhoff",
- :doc "Various wrappers and utilities for the mongodb-java-driver"}
- somnium.congomongo
- (:use [somnium.congomongo.config :only [*mongo-config*]]
- [somnium.congomongo.util :only [named defunk]]
- [somnium.congomongo.coerce :only [coerce coerce-fields]]
- [clojure.contrib.json read write])
- (:import [com.mongodb Mongo DB DBCollection DBObject]
- [com.mongodb.util JSON]
- [somnium.congomongo ClojureDBObject]))
-
-(defunk mongo!
- "Creates a Mongo object and sets the default database.
- Keyword arguments include:
- :host -> defaults to localhost
- :port -> defaults to 27017
- :db -> defaults to nil (you'll have to set it anyway, might as well do it now.)"
- {:arglists '({:db ? :host "localhost" :port 27017})}
- [:db nil :host "localhost" :port 27017]
- (let [mongo (Mongo. host port)
- n-db (if db (.getDB mongo (named db)) nil)]
- (reset! *mongo-config*
- {:mongo mongo
- :db n-db})
- true))
-
-;; perhaps split *mongo-config* out into vars for thread-local
-;; changes.
-
-(definline get-coll
- "Returns a DBCollection object"
- [collection]
- `(doto (.getCollection #^DB (:db @*mongo-config*)
- #^String (named ~collection))
- (.setObjectClass ClojureDBObject)))
-
-(defunk fetch
- "Fetches objects from a collection. Optional arguments include
- :where -> takes a query map
- :only -> takes an array of keys to retrieve
- :as -> what to return, defaults to :clojure, can also be :json or :mongo
- :from -> argument type, same options as above
- :one? -> defaults to false, use fetch-one as a shortcut
- :count? -> defaults to false, use fetch-count as a shortcut"
- {:arglists '([collection {:where {} :only [] :as :clojure :from :clojure :one false :count false}])}
- [coll :where {} :only [] :as :clojure :from :clojure :one? false :count? false]
- (let [n-where (coerce where [from :mongo])
- n-only (coerce-fields only)
- n-col (get-coll coll)]
- (cond
- count? (.getCount n-col n-where n-only)
- one? (if-let [m (.findOne n-col n-where n-only)]
- (coerce m [:mongo as]) nil)
- :else (if-let [m (.find n-col n-where n-only)]
- (coerce m [:mongo as] :many :true) nil))))
-
-(defn fetch-one [col & options]
- (apply fetch col (concat options [:one? true])))
-
-(defn fetch-count [col & options]
- (apply fetch col (concat options [:count? true])))
-
-(defunk insert!
- "Inserts a map into collection. Will not overwrite existing maps.
- Takes optional from and to keyword arguments. To insert
- as a side-effect only specify :to as nil."
- {:arglists '([coll obj {:many false :from :clojure :to :clojure}])}
- [coll obj :from :clojure :to :clojure :many false]
- (let [res (.insert #^DBCollection (get-coll coll)
- (if many
- #^java.util.List (coerce obj [from :mongo] :many many)
- #^DBObject (coerce obj [from :mongo] :many many)))]
- (if to
- (coerce res [:mongo to] :many many))))
-
-(defunk mass-insert!
- {:arglists '([coll objs {:from :clojure :to :clojure}])}
- [coll objs :from :clojure :to :clojure]
- (insert! coll objs :from from :to to :many true))
-
-;; should this raise an exception if _ns and _id aren't present?
-(defunk update!
- "Alters/inserts a map in a collection. Overwrites existing objects.
- The shortcut forms need a map with valid :_id and :_ns fields or
- a collection and a map with a valid :_id field."
- {:arglists '(collection old new {:upsert true :multiple false :as :clojure :from :clojure})}
- [coll old new :upsert true :multiple false :as :clojure :from :clojure]
- (coerce (.update #^DBCollection (get-coll coll)
- #^DBObject (coerce old [from :mongo])
- #^DBObject (coerce new [from :mongo])
- upsert multiple) [:mongo as]))
-
-(defunk destroy!
- "Removes map from collection. Takes a collection name and
- a query map"
- {:arglists '(collection where {:from :clojure})}
- [c q :from :clojure]
- (.remove (get-coll c)
- #^DBObject (coerce q [from :mongo])))
-
-(defunk add-index!
- "Adds an index on the collection for the specified fields if it does not exist.
- Options include:
- :unique -> defaults to false
- :force -> defaults to true"
- {:arglists '(collection fields {:unique false :force true})}
- [c f :unique false :force true]
- (-> (get-coll c)
- (.ensureIndex (coerce-fields f) force unique)))
-
-(defn drop-index!
- "Drops an index on the collection for the specified fields"
- [coll fields]
- (.dropIndex (get-coll coll) (coerce-fields fields)))
-
-(defn drop-all-indexes!
- "Drops all indexes from a collection"
- [coll]
- (.dropIndexes (get-coll coll)))
-
-(defunk get-indexes
- "Get index information on collection"
- {:arglists '([collection :as (:clojure)])}
- [coll :as :clojure]
- (map #(into {} %) (.getIndexInfo (get-coll coll))))
-
-(defn drop-database!
- "drops a database from the mongo server"
- [title]
- (.dropDatabase (:mongo @*mongo-config*) (named title)))
-
-(defn set-database!
- "atomically alters the current database"
- [title]
- (if-let [db (.getDB (:mongo @*mongo-config*) (named title))]
- (swap! *mongo-config* merge {:db db})
- (throw (RuntimeException. (str "database with title " title " does not exist.")))))
-
-(defn databases
- "List databases on the mongo server" []
- (.getDatabaseNames (:mongo @*mongo-config*)))
-
-(defn collections
- "Returns the set of collections stored in the current database" []
- (.getCollectionNames #^DB (:db @*mongo-config*)))
-
-(defn drop-coll!
- [collection]
- "Permanently deletes a collection. Use with care."
- (.drop #^DBCollection (.getCollection #^DB (:db @*mongo-config*)
- #^String (named collection))))
View
39 src/main/clj/somnium/congomongo/coerce.clj
@@ -1,39 +0,0 @@
-(ns somnium.congomongo.coerce
- (:use [somnium.congomongo.util :only [defunk]]
- [clojure.contrib.json read write]
- [clojure.contrib.def :only [defvar]])
- (:import [somnium.congomongo ClojureDBObject]
- [clojure.lang IPersistentMap]
- [com.mongodb.util JSON]))
-
-(defvar *keywordize* true
- "Set this to false to prevent ClojureDBObject from setting string keys to keywords")
-
-(defunk
- coerce
- {:arglists '([obj [:from :to] {:many false}])
- :doc
- "takes an object, a vector of keywords:
- from [ :clojure :mongo :json ]
- to [ :clojure :mongo :json ],
- and an an optional :many keyword parameter which defaults to false"}
- [obj from-to :many false]
- (if (= (from-to 0) (from-to 1))
- obj
- (let [fun
- (condp = from-to
- [:clojure :mongo ] #(ClojureDBObject. #^IPersistentMap %)
- [:clojure :json ] #(json-str %)
- [:mongo :clojure] #(.toClojure #^ClojureDBObject %
- #^Boolean/TYPE *keywordize*)
- [:mongo :json ] #(.toString #^ClojureDBObject %)
- [:json :clojure] #(binding [*json-keyword-keys* *keywordize*] (read-json %))
- [:json :mongo ] #(JSON/parse %)
- :else (throw (RuntimeException.
- "unsupported keyword pair")))]
- (if many (map fun obj) (fun obj)))))
-
-(defn coerce-fields
- "only used for creating argument object for :only"
- [fields]
- (ClojureDBObject. #^IPersistentMap (zipmap fields (repeat 1))))
View
2 src/main/clj/somnium/congomongo/config.clj
@@ -1,2 +0,0 @@
-(ns somnium.congomongo.config)
-(def *mongo-config* (atom {}))
View
29 src/main/clj/somnium/congomongo/error.clj
@@ -1,29 +0,0 @@
-(ns
- #^{:author "Jeff Sapp"}
- somnium.congomongo.error
- (:use somnium.congomongo
- somnium.congomongo.config
- somnium.congomongo.coerce)
- (:import [com.mongodb DB]))
-
-(defn get-last-error
- "Gets the error (if there is one) from the previous operation"
- []
- (let [e (into {} (.getLastError #^DB (:db @*mongo-config*)))]
- (when (e "err") e)))
-
-(defn get-previous-error
- "Returns the last error that occurred"
- []
- (let [e (into {} (.getPreviousError #^DB (:db @*mongo-config*)))]
- (when (e "err") e)))
-
-(defn reset-error!
- "Resets the error memory for the database"
- []
- (into {} (.resetError #^DB (:db @*mongo-config*))))
-
-(defn force-error!
- "This method forces an error"
- []
- (into {} (.forceError #^DB (:db @*mongo-config*))))
View
34 src/main/clj/somnium/congomongo/util.clj
@@ -1,34 +0,0 @@
-(ns somnium.congomongo.util)
-
-(defmacro defunk
- "Mostly identitical to defnk in clojure.contrib.def but keeps argmap meta data."
- {:arglists '([title docstring? attr-map? [params*] body])}
- [title & stuff]
- (let [[metad [argvec & body]] (split-with (complement vector?) stuff)
- [args kwargs] (split-with symbol? argvec)
- syms (map #(-> % name symbol) (take-nth 2 kwargs))
- values (take-nth 2 (rest kwargs))
- sym-vals (apply hash-map (interleave syms values))
- default-map {:keys (vec syms)
- :or sym-vals}]
- `(defn ~title
- ~@metad
- [~@args & options#]
- (let [~default-map (apply hash-map options#)]
- ~@body))))
-
-(defn named [s]
- "convenience for interchangeably handling keywords, symbols, and strings"
- (if (instance? clojure.lang.Named s) (name s) s))
-
-(defn partition-map
- "creates a hash-map of first and rest pairs from a partitioned collection"
- [coll n]
- (apply merge
- (map #(hash-map (first %) (rest %))
- (partition n coll))))
-
-(defn map-keys
- "applies f to each key in h"
- [f h]
- (zipmap (map f (keys h)) (vals h)))
View
135 src/main/java/somnium/congomongo/ClojureDBObject.java
@@ -1,135 +0,0 @@
-/*
- * Subclass of com.mongodb.BasicDBObject for
- * rapid creation of clojure persistent data structures.
- */
-
-package somnium.congomongo;
-import com.mongodb.BasicDBObject;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.Map;
-import java.util.ArrayList;
-import clojure.lang.Keyword;
-import clojure.lang.Symbol;
-import clojure.lang.MapEntry;
-import clojure.lang.IPersistentMap;
-import clojure.lang.PersistentHashMap;
-import clojure.lang.PersistentVector;
-
-/**
- *
- * @author somnium
- */
-
-public class ClojureDBObject extends BasicDBObject {
-
- public ClojureDBObject() {
- }
-
- public ClojureDBObject(IPersistentMap m) {
- this.putClojure(m);
- }
-
- public void putClojure(IPersistentMap m) {
- Iterator<MapEntry> iter = m.iterator();
-
- while (iter.hasNext()) {
- MapEntry e = iter.next();
- Object cKey = e.getKey();
- String mKey;
-
- // check key for keyword type
- // and assign result to var mKey
-
- if (cKey instanceof Keyword) {
- mKey = ((Keyword)cKey).getName();}
- else {mKey = cKey.toString();}
-
- // delegate to readClojureObject
-
- this.put(mKey, readClojureObject(e.getValue()));
- }
- }
-
- private Object readClojureObject(Object o) {
-
- if (o instanceof Keyword) {
- return ((Keyword)o).getName();
- }
-
- else if (o instanceof IPersistentMap) {
- ClojureDBObject clj = new ClojureDBObject();
- clj.putClojure((IPersistentMap) o);
- return clj;
- }
-
- else if (o instanceof List) {
- ArrayList<Object>alist = new ArrayList<Object>();
- Iterator<Object> i = ((java.util.List)o).iterator();
- while (i.hasNext()) {
- Object obj = i.next();
- alist.add(readClojureObject(obj));
- }
- return alist;
- }
-
- else return o;
-
- }
-
- // options:
- // use struct-map?
- // keywordize keys?
- // call .toString on ObjectIds?
-
- public IPersistentMap toClojure() {
- return toClojure(true);
- }
-
- public IPersistentMap toClojure(boolean keywordize) {
- return toClojureMap(this, keywordize);
- }
-
- private static IPersistentMap toClojureMap(Map m, boolean keywordize){
-
- Set keys = m.keySet();
- Iterator<String> iter = keys.iterator();
- ArrayList<Object> alist = new ArrayList<Object>();
- while (iter.hasNext()) {
- String s = iter.next();
- Object v = m.get(s);
-
- if (keywordize) {
- Symbol sym = Symbol.intern(s);
- Keyword k = Keyword.intern(sym);
- alist.add(k);
- } else {
- alist.add(s);
- }
-
- alist.add(toClojureVal(v, keywordize));
- }
-
- return PersistentHashMap.create(alist);
- }
-
- private static Object toClojureVal(Object o, boolean keywordize) {
-
- if (o instanceof Map) {
- return toClojureMap((Map)o, keywordize);
- }
-
- else if (o instanceof List) {
- ArrayList<Object>alist = new ArrayList<Object>();
- Iterator<Object> i = ((java.util.List)o).iterator();
- while (i.hasNext()) {
- Object obj = i.next();
- alist.add(toClojureVal(obj, keywordize));
- }
- return PersistentVector.create(alist);
- }
-
- else return o;
- }
- }

0 comments on commit 0075cc2

Please sign in to comment.