Make it possible to opt-out of field keywordization in the query DSL

An example:

``` clojure
(with-collection coll
  (find {})
  (limit 3)
  (sort { :population -1 })
  (keywordize-fields false))
```
This commit is contained in:
Michael S. Klishin 2012-02-12 10:13:39 +04:00
parent c04df6e58c
commit fe421cc0db
2 changed files with 35 additions and 10 deletions

View file

@ -36,14 +36,15 @@
(defn empty-query
([]
{
:query {}
:sort {}
:fields []
:skip 0
:limit 0
:batch-size 256
:hint nil
:snapshot false
:query {}
:sort {}
:fields []
:skip 0
:limit 0
:batch-size 256
:hint nil
:snapshot false
:keywordize-fields true
})
([^DBCollection coll]
(merge (empty-query) { :collection coll })))
@ -53,7 +54,7 @@
(to-db-object (zipmap fields (repeat 1))))
(defn exec
[{ :keys [collection query fields skip limit sort batch-size hint snapshot read-preference] :or { limit 0 batch-size 256 skip 0 } }]
[{ :keys [collection query fields skip limit sort batch-size hint snapshot read-preference keywordize-fields] :or { limit 0 batch-size 256 skip 0 } }]
(let [cursor (doto ^DBCursor (.find ^DBCollection collection (to-db-object query) (fields-to-db-object fields))
(.limit limit)
(.skip skip)
@ -64,7 +65,7 @@
(.snapshot cursor))
(when read-preference
(.setReadPreference cursor read-preference))
(map (fn [x] (from-db-object x true))
(map (fn [x] (from-db-object x keywordize-fields))
(seq cursor))))
;;
@ -107,6 +108,10 @@
[m ^ReadPreference rp]
(merge m { :read-preference rp }))
(defn keywordize-fields
[m bool]
(merge m { :keywordize-fields bool }))
(defn paginate
[m & { :keys [page per-page] :or { page 1 per-page 10 } }]
(merge m { :limit per-page :skip (monger.internal.pagination/offset-for page per-page) }))

View file

@ -260,3 +260,23 @@
(merge top3)
(merge by-population-desc))]
(is (= result [ca-doc tx-doc ny-doc]))))
(deftest combined-querying-dsl-example2
(let [coll "docs"
ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" }
de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" }
ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" }
ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" }
tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" }
top3 (partial-query (limit 3))
by-population-desc (partial-query (sort { :population -1 }))
_ (mgcol/insert-batch coll [ma-doc de-doc ny-doc ca-doc tx-doc])
result (with-collection coll
(find {})
(merge top3)
(merge by-population-desc)
(keywordize-fields false))]
;; documents have fields as strings,
;; not keywords
(is (= (map #(% "name") result)
(map #(% :name) [ca-doc tx-doc ny-doc])))))