couchdb

package module
v0.0.0-...-e122966 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2017 License: MIT Imports: 13 Imported by: 2

README

couchdb

Minimalist CouchDB client

Documentation

Understanding

  • client.go - represents the couchdb client for the others to use.
  • db.go - This is the low level db interface for the object. (Couch works on rest.)
  • dbrequests - Wrapper for all requests from couch.
  • view.go - Deals with creation of views.
  • document.go - Deals with the creation and updating of documents in the db.

Running Tests

Make sure there is a couch instane running on default port (5984) for it to work. Have disabled the DeleteDB for now so the DB created would persist.

$ export GOPATH=$PWD
$ go get -a
$ go test -v

Example Usage

For any operation, there is a Database Object which represents a connection to a database in couchdb client.

client := NewClient("127.0.0.1", 5984) // Creates the client conenction.
dbObj := client.DB("testdb") //Db object which represents the connection to db.

Exists checks if the database exists. Create can create the database if it does not exist.

status, err := dbObj.Exists() // Status contains the status of the check
err := dbObj.Create() //Creates a new database with the dbName passed to the object

Documents

Creating a new document can be done as follows. Any json can be save and the example below shows how to Marshal an object.

doc := NewDocument("", "", &DBObject) //args - ID and Revison of the docuemnt to pickup
byteObj, err := json.Marshal(obj)
err := doc.Create(byteObj) //Creates a document Id and Rev would be updated by now.

// For updating,
obj.Update()
byteObj, err = json.Marshal(obj)
err = doc.Update((byteObj)

To get the object back, the way to go about it would be to wrap the object with CouchWrapper which can take care of the extra information that comes back.

doc := NewDocument(Id, Rev, &DBObject) //Rev can be empty and not used right now, have it there for if present case.
jsonObj, err := doc.GetDocument()
if err != nil {
	t.Error("Error ", err)
}

type UpdateObj struct {
	CouchWrapperUpdate
	TestObj
}

obj := &UpdateObj{}
json.Unmarshal(jsonObj, obj)

Views

View has two parts- DesignDoc and View DesignDoc is the representation of the design Document. Each design Document can have multiple Views assosciated with it. The example below shows how to come up with a designDocument contating multiple views.

view := NewView("test_view", "doc", "doc.age < 22", "doc.name, doc.age")

view2 := NewView("raw_view", "", "", "")
view2.RawStatus = true
view2.RawJson = "function(rawDoc) {console.log(1234)}"

fView := NewView("fred_view", "newVar", "newVar.age > 22", "newVar.name, newVar.age")

doc := NewDesignDoc("test_design", &DBObject) // Creating the doc

doc.AddView(view)  // Adding the views into it.
doc.AddView(fView)
doc.AddView(view2)

err := doc.SaveDoc() //Saving the document which creates the permanent view.
if err != nil {
	t.Error(err)
}

Requesting a view.

//arguments are @designDoc - followed by test_view

err, data := DBObject.GetView("test_design", "test_view", "")
if err != nil {
	t.Error("Error :", err)
} else {
	t.Log(string(data))
}

The views in designDocuments can be updated as well.

err, desDoc := RetreiveDocFromDb("test_design", &DBObject)
if err == nil {
	desDoc.Views[0].Name = "test_view_updated" //Demo of an update. Assuming a view exists.
	desDoc.RevStatus = true
	err := desDoc.SaveDoc()
	if err != nil {
		t.Error(err)
	}
}

Documentation

Overview

Representation of a document in couch DB

This is where all the code with respect to the documents go in.

File stores the contents in the template file so that its part of the package.

DesignDoc is needed with a name -> corresponds to the design document to query. Eash DesignDoc has a set of Views. -> Each view is a map reduce Function or raw javascript code.

Index

Constants

This section is empty.

Variables

View Source
var DESIGNTMPL *template.Template = template.Must(template.New("design").Parse(strings.Replace(strings.Replace(`
{
	"_id": "{{.Id}}",
	{{if .RevStatus}}
	"_rev":"{{.Rev}}",
	{{end}}
	"views": {
		{{range .Views}}

		   "{{.Name}}": {
		   {{if .RawJson}}
			{{.RawJson}}
		   {{else}}
			"map": " \
			function({{.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .CondStatus}}\
					if({{.Condition}}) { \
						emit({{.KeyName}}, get_value({{.VariableName}},  [{{.EmitStr}}]));\
						} \
				{{else}} \
						emit({{.KeyName}}, get_value({{.VariableName}},  [{{.EmitStr}}]));\
				{{end}} \
			}"
		   {{end}}
		   },

		{{end}}
		   "{{.LastView.Name}}": {
	            {{if .LastView.RawJson}}
			{{.LastView.RawJson}}
		    {{else}}
			"map": " \
			function({{.LastView.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .LastView.CondStatus}}\
					if({{.LastView.Condition}}) { \
						emit({{.LastView.KeyName}}, get_value({{.LastView.VariableName}},  [{{.LastView.EmitStr}}]));\
						} \
				{{else}} \
						emit({{.LastView.KeyName}}, get_value({{.LastView.VariableName}},  [{{.LastView.EmitStr}}]));\
				{{end}} \
			}"
		    {{end}}
		   }
	},
	"language": "javascript"
}
`, "\\\n", "", -1), "\t", "", -1)))

Functions

This section is empty.

Types

type Client

type Client struct {
	Host     string
	Port     int
	Username string
	Password string
	Secure   bool
	Timeout  int
}

Client defines the base client for the orm

func NewClient

func NewClient(h string, p int) Client

NewClient returns a new instance of a client with only host and port definted

func (*Client) DB

func (c *Client) DB(name string) Database

DB creates a Database client

func (*Client) GetAuth

func (c *Client) GetAuth() (string, string)

GetAuth is a thin utility for getting the password

func (*Client) GetHost

func (c *Client) GetHost() string

GetHost is a thin utility for getting the host

func (*Client) GetPort

func (c *Client) GetPort() (p int)

GetPort is a thin utility for getting the port

func (*Client) GetPwd

func (c *Client) GetPwd() string

GetPwd is a thin utility for getting the password

func (*Client) GetTimeout

func (c *Client) GetTimeout() int

GetTimeout is a thin utility for getting the timeout

func (*Client) GetTimeoutDuration

func (c *Client) GetTimeoutDuration() time.Duration

GetTimeoutDuration is a thin utility for getting the timeout in duration format

func (*Client) GetUser

func (c *Client) GetUser() string

GetUser is a thin utility for getting the username

func (*Client) SetAuth

func (c *Client) SetAuth(u string, p string) *Client

SetAuth is a thin utility for setting the password

func (*Client) SetHost

func (c *Client) SetHost(h string) *Client

SetHost is a thin utility for setting the host

func (*Client) SetInsecure

func (c *Client) SetInsecure()

SetInsecure is a thin utility for setting the client to http

func (*Client) SetPort

func (c *Client) SetPort(p int) *Client

SetPort is a thin utility for setting the port

func (*Client) SetPwd

func (c *Client) SetPwd(p string) *Client

SetPwd is a thin utility for setting the password

func (*Client) SetSecure

func (c *Client) SetSecure()

SetSecure is a thin utility for setting the client to https

func (*Client) SetTimeout

func (c *Client) SetTimeout(t int) *Client

SetTimeout is a thin utility for setting the timeout

func (*Client) SetUser

func (c *Client) SetUser(u string) *Client

SetUser is a thin utility for setting the username

type CouchWrapperUpdate

type CouchWrapperUpdate struct {
	Id  string `json:"_id"`
	Rev string `json:"_rev"`
}

type Database

type Database struct {
	Name    string
	BaseURL string
	Client  *Client
	Req     *Request
}

Database defintes a database client It can be used to get Documents and Views

func NewDB

func NewDB(name string, c *Client) Database

NewDB creates an instance of a Database

func (*Database) Create

func (db *Database) Create() error

Create creates a new database

func (*Database) Delete

func (db *Database) Delete() error

Delete deletes database

func (*Database) Exists

func (db *Database) Exists() error

Exists check to see if database exists

func (*Database) GetView

func (db *Database) GetView(docName string, viewName string, args map[string]string) ([]byte, error)

type DesignDoc

type DesignDoc struct {
	Id        string //The id of the document
	Rev       string
	Views     []*View
	LastView  *View
	Db        *Database
	RevStatus bool
}

func NewDesignDoc

func NewDesignDoc(id string, db *Database) (doc *DesignDoc)

func RetreiveDocFromDb

func RetreiveDocFromDb(id string, db *Database) (err error, desDoc *DesignDoc)

func (*DesignDoc) AddView

func (doc *DesignDoc) AddView(view *View)

func (*DesignDoc) CheckExists

func (doc *DesignDoc) CheckExists(viewName string) (int, bool)

Returning index as -1 => LastView has it. Otherwise the index returned is in the view. status returns true or false indicating presence.

func (*DesignDoc) CreateDoc

func (doc *DesignDoc) CreateDoc() (error, []byte)

Works on the default Global value and not on config files.

func (*DesignDoc) SaveDoc

func (doc *DesignDoc) SaveDoc() (err error)

type DocCreateResoponse

type DocCreateResoponse struct {
	Error string `json:"error"`
	Ok    bool   `json:"ok"`
	Id    string `json:"id"`
	Rev   string `json:"rev"`
}

type Document

type Document struct {
	Db  *Database
	Id  string `json:"_id"`
	Rev string `json:"_rev"`
}

Document either has an Id, Rev and the DB it connects to.

func NewDocument

func NewDocument(id string, rev string, Db *Database) *Document

func (*Document) Create

func (doc *Document) Create(data []byte) error

Creates a document if it does not already exist and generates an error if it already exists.

func (*Document) Delete

func (doc *Document) Delete() error

func (*Document) Exists

func (doc *Document) Exists() ([]byte, error)

Function checks if the document exists and returns error if it does not

func (*Document) GetDocument

func (doc *Document) GetDocument() ([]byte, error)

Gets the document using the given id and error if it does not exist.

func (*Document) Update

func (doc *Document) Update(newBody []byte) error

Updates the document with the new Data. Data contains an encoded marshalled object that has the required fields, pre computed..

type Request

type Request struct {
	Req     *http.Client
	BaseURL string
	// contains filtered or unexported fields
}

Request defines a base request used in DB connections

func (*Request) Delete

func (r *Request) Delete(p string) ([]byte, error)

func (*Request) Get

func (r *Request) Get(p string, args map[string]string) ([]byte, error)

func (*Request) PathUrl

func (r *Request) PathUrl(p string) (*url.URL, error)

PathUrl joins the provided path with the host

func (*Request) Post

func (r *Request) Post(p string, body []byte, headers map[string]string) ([]byte, error)

func (*Request) Put

func (r *Request) Put(p string) ([]byte, error)

type View

type View struct {
	Name         string
	VariableName string
	KeyName      string
	CondStatus   bool
	Condition    string
	EmitStr      string
	RawJson      string
}

func NewView

func NewView(name string, varName string, condition string, emitStr string) (view *View)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL