CouchDB

Version 6, last updated by Diego Medina at 2013-01-13

CouchDB

On Lift 2.5-M4, we moved the couchdb code to an external module, this wiki has updated instructions.

Installation

SBT users

Add dependency to your project description:

val lift_couchdb = "net.liftmodules" % "lift-couchdb" % "2.5-M4-1.1"

Maven users

Add dependency to your pom.xml:

<dependency>
  <groupId>net.liftmodules</groupId>
  <artifactId>lift-couchdb</artifactId>
  <version>2.5-M4-1.1</version>
</dependency>

Setup

import net.liftmodules.couchdb.{CouchDB, Database}
import dispatch.{Http, StatusCode}
...
// Construct a Database (by default on localhost, port 5984),
// read the scala docs for more contructors
val database = new Database("database_name")

// creates the database "database_name" if it doesn't exist
database createIfNotCreated(new Http())

//sets the default database for the application
CouchDB.defaultDatabase = database

Adding designs

...
import net.liftweb.json.Implicits.{int2jvalue, string2jvalue}
import net.liftweb.json.JsonAST.{JObject}
import net.liftweb.json.JsonDSL.{jobject2assoc, pair2Assoc, pair2jvalue}
...
val design: JObject = 
  ("language" -> "javascript") ~
  ("views" -> (("people_by_age" ->  ("map" -> "function(doc) { if (doc.type == 'Person') { emit(doc.age, doc); } }")) ~
               ("oldest"        -> (("map" -> "function(doc) { if (doc.type == 'Person') { emit(doc.name, doc.age); } }") ~
                                    ("reduce" -> "function(keys, values) { return Math.max.apply(null, values); }")))))
Http(database.design("design_name") put design)

CouchRecord

Define record class

import net.liftweb.record.field.{IntField, StringField}
...
class Person extends CouchRecord[Person] {
    def meta = Person
  
    object name extends StringField(this, 200)
    object age extends IntField(this)
  }
  
  object Person extends Person with CouchMetaRecord[Person] {
    def createRecord = new Person
  }

Working with a record

val newCouchRec = Person.createRecord.name("Alice").age(25)
newCouchRec.name.set("NotAlice")
newCouchRec save

Working with design views

val viewReturn = Person.queryView("design_name", "people_by_age", _.key(JString(JInt(30))))

Authentication

import dispatch.{:/,Http}
...
//create a request with basic http authentication
var req = :/("couchhost.example.com").as_!("myusername", "password")    
val database = new Database(req, "databaseName")

Comments are disabled for this space. In order to enable comments, Messages tool must be added to project.

You can add Messages tool from Tools section on the Admin tab.