Skip to content

Commit

Permalink
Add default query term
Browse files Browse the repository at this point in the history
The default function lets you provide a default value/function when a
field or value is null or missing.

Fixes #29, fixes #99
  • Loading branch information
danielcompton committed Oct 11, 2015
1 parent 9b289d0 commit 90b58cd
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file. This change
- clojure.tools.logging support. [#72](https://github.com/apa512/clj-rethinkdb/pull/72)
- `fn` macro to ClojureScript `rethinkdb.query` namespace. [#64](https://github.com/apa512/clj-rethinkdb/issues/64)
- `rethinkdb.query/order-by` function to ClojureScript. [#65](https://github.com/apa512/clj-rethinkdb/issues/65)
- `rethinkdb.query/default` function, for supplying a default value/function for missing values.

### Changed
- Update dependency to Clojure 1.7. [#59](https://github.com/apa512/clj-rethinkdb/pull/59)
Expand Down
9 changes: 9 additions & 0 deletions src/rethinkdb/query.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,15 @@
([] (term :ERROR []))
([s] (term :ERROR [s])))

(defn default
"Provide a default value in case of non-existence errors. default evaluates its
first argument (the value it’s chained to). If that argument returns null or a
non-existence error is thrown in evaluation, then default returns its second argument.
The second argument is usually a default value, but it can be a RethinkDB function that
returns a value."
[any default]
(term :DEFAULT [any default]))

(defn coerce-to
"Convert a value of one type into another."
[x s]
Expand Down
9 changes: 8 additions & 1 deletion test/rethinkdb/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,14 @@
(is (= (r/run (-> (r/db test-db)
(r/table test-table)
(r/filter (r/fn [row]
(r/eq (r/get-field row :name) "Pikachu")))) conn) [(first pokemons)])))))
(r/eq (r/get-field row :name) "Pikachu")))) conn) [(first pokemons)]))
(is (= 1 (r/run (r/get-field {:a 1} :a) conn))))

(testing "default values"
(is (= "not found" (r/run (-> (r/get-field {:a 1} :b) (r/default "not found")) conn)))
(is (= "not found" (r/run (-> (r/max [nil]) (r/default "not found")) conn)))
(is (= "Cannot take the average of an empty stream. (If you passed `avg` a field name, it may be that no elements of the stream had that field.)"
(r/run (-> (r/avg [nil]) (r/default (r/fn [row] row))) conn))))))

(deftest db-in-connection
(testing "run a query with an implicit database"
Expand Down

0 comments on commit 90b58cd

Please sign in to comment.