目次

Version 5, last updated by ghostM at Sep 10 20:26 UTC

CouchDB

Installation

SBT users

Add dependency to your project description:

val lift_couchdb = "net.liftweb" % "lift-couchdb" % "2.0"

Maven users

Add dependency to your pom.xml:

<dependency>
  <groupId>net.liftweb</groupId>
  <artifactId>lift-couchdb</artifactId>
  <version>2.0</version>
</dependency>

Note: For use with Scala 2.8 replace the version number (2.0) with 2.0-scala280-SNAPSHOT

Setup

import net.liftweb.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")