|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 2 | +# use this file except in compliance with the License. You may obtain a copy of |
| 3 | +# the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 | +# License for the specific language governing permissions and limitations under |
| 11 | +# the License. |
| 12 | + |
| 13 | +defmodule MangoDatabase do |
| 14 | + def recreate(db, opts \\ []) do |
| 15 | + resp = Couch.get("/#{db}") |
| 16 | + if resp.status_code == 200 do |
| 17 | + docs = resp.body["doc_count"] + resp.body["doc_del_count"] |
| 18 | + if docs > 0 do |
| 19 | + delete(db) |
| 20 | + create(db, opts) |
| 21 | + end |
| 22 | + else |
| 23 | + create(db, opts) |
| 24 | + end |
| 25 | + end |
| 26 | + |
| 27 | + defp create(db, opts) do |
| 28 | + partitioned = Keyword.get(opts, :partitioned, false) |
| 29 | + Couch.put("/#{db}?partitioned=#{partitioned}") |
| 30 | + end |
| 31 | + |
| 32 | + defp delete(db) do |
| 33 | + Couch.delete("/#{db}") |
| 34 | + end |
| 35 | + |
| 36 | + # TODO: make this use batches if necessary |
| 37 | + def save_docs(db, docs) do |
| 38 | + resp = Couch.post("/#{db}/_bulk_docs", body: %{"docs" => docs}) |
| 39 | + end |
| 40 | + |
| 41 | + def create_index(db, fields, name) do |
| 42 | + resp = Couch.post("/#{db}/_index", body: %{ |
| 43 | + "index" => %{"fields" => fields}, |
| 44 | + "name" => name, |
| 45 | + "ddoc" => name, |
| 46 | + "type" => "json", |
| 47 | + "w" => 3 |
| 48 | + }) |
| 49 | + end |
| 50 | + |
| 51 | + def create_text_index(db) do |
| 52 | + # TODO |
| 53 | + end |
| 54 | + |
| 55 | + # TODO: port more options from src/mango/test/mango.py `def find(...)` |
| 56 | + def find(db, selector, opts \\ []) do |
| 57 | + defaults = [use_index: nil, skip: 0, limit: 25, r: 1, conflicts: false] |
| 58 | + options = Keyword.merge(defaults, opts) |
| 59 | + |
| 60 | + resp = Couch.post("/#{db}/_find", body: %{ |
| 61 | + "selector" => selector, |
| 62 | + "use_index" => options[:use_index], |
| 63 | + "skip" => options[:skip], |
| 64 | + "limit" => options[:limit], |
| 65 | + "r" => options[:r], |
| 66 | + "conflicts" => options[:conflicts] |
| 67 | + }) |
| 68 | + resp.body["docs"] |
| 69 | + end |
| 70 | +end |
0 commit comments