yaccc

package module
v0.0.0-...-5cb367e Latest Latest
Warning

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

Go to latest
Published: May 12, 2019 License: Apache-2.0 Imports: 16 Imported by: 0

README

Yet Another Couchdb client with Context

Description

A minimal Couchdb client based on context. It aims to be battle tested and viable for production use.

This lib haven't reach the V1 yet, some breaking changes can appear in the future.

Documentation

Documentation and API Reference can be found on godoc.org

Installation

Install couch using the "go get" command:

    go get github.com/Peltoche/yaccc

Main Features

Server
  • Connection with retry
  • Ping
  • Mock
  • Authentication
  • Customizable logger
Database
  • Get from key
  • Set to key
  • Find from a raw query
  • Mock

Dependencies

The only external dependencies are:

  • github.com/pkg/errors (allow to print a stacktrace with the errors)
  • github.com/stretchr/testify/mock (for the mocks)

Example usage

package main

import (
	"context"
	"fmt"
	"time"

	"gitlab.com/Peltoche/yaccc"
)

type Movie struct {
	Title string `json:"title"`
	Year  int    `json:"year"`
	Score int    `json:"score"`
}

func main() {
	// Create the server
	//
	// If the connection fail, retry 3 times max with 1 second
	// between each retry.
	server, err := yaccc.NewServer("http://localhost:5984", 3, time.Second)
	if err != nil {
		panic(err)
	}

	db, err := server.ConnectOrCreateDatabase(context.TODO(), "movies")
	if err != nil {
		panic(err)
	}

	movieToSave := Movie{Title: "The Godfather", Year: 1972, Score: 90}

	_, err = db.Set(context.TODO(), "some-big-UUID", "", movieToSave)
	if err != nil {
		panic(err)
	}

	var res Movie
	_, err = db.Get(context.TODO(), "some-big-UUID", &res)
	if err != nil {
		panic(err)
	}

	fmt.Printf("result => %s\n", res.Title) // result => The Godfather

	server.DestroyDatabase(context.TODO(), "movies")
}

Contributing

Pull requests are welcome. Please use the gitlab repository to make Pull request and to create the Issues.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is used to interact with a couchdb database.

func NewClient

func NewClient(serverURL string, nbRetry int, sleepDuration time.Duration) (*Client, error)

NewClient instantiate a new 'Client' with the given arguments.

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) (*Client, error)

NewClientWithConfig instantiate a new 'Client' based on the given configs.

func (*Client) Authenticate

func (t *Client) Authenticate(user string, password string) error

Authenticate the requests.

func (*Client) ConnectDatabase

func (t *Client) ConnectDatabase(ctx context.Context, name string) (*Database, error)

ConnectDatabase will start a connection to the database with the given name.

func (*Client) CreateDatabase

func (t *Client) CreateDatabase(ctx context.Context, cmd *CreateDatabaseCmd) (*Database, error)

CreateDatabase will create a database with the given name.

If the database already exist, the method will fail with an error. If you want to ensure that the database exists, use the 'Ensure' method instead.

func (*Client) DestroyDatabase

func (t *Client) DestroyDatabase(ctx context.Context, name string) error

DestroyDatabase destroy the database given in parameter with all it content.

This method is idempotent. This means that if the database is not found it will return nil.

func (*Client) Ping

func (t *Client) Ping() error

Ping check if the connection with the server is ok.

func (*Client) SetClient

func (t *Client) SetClient(client *http.Client) *Client

SetClient configure a new http client for the server.

func (*Client) String

func (t *Client) String() string

String is an implementation of 'fmt.Stringer'.

type ClientConfig

type ClientConfig struct {
	URL        string           `yaml:"url"`
	User       string           `yaml:"user"`
	Password   string           `yaml:"password"`
	Connection ConnectionConfig `yaml:"connection"`
}

ClientConfig is the configuration used to instantiate a 'Client' and its "Database".

type ClusterInfo

type ClusterInfo struct {
	Replicas     int `json:"n"`
	Shards       int `json:"q"`
	ReadQuorums  int `json:"r"`
	WriteQuorums int `json:"w"`
}

ClusterInfo part of the Info response.

type ConnectionConfig

type ConnectionConfig struct {
	MaxRetryNumber   int           `yaml:"max-retry-number"`
	CoolDownDuration time.Duration `yaml:"cooldown-duration"`
}

ConnectionConfig specify the retry policy.

type CreateDatabaseCmd

type CreateDatabaseCmd struct {
	Name            string                    `json:"name" yaml:"name"`
	DesignDocuments map[string]DesignDocument `json:"design-documents" yaml:"design-documents"`
}

CreateDatabaseCmd is the required configuration to create a new database.

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database is used to interact with a couchdb database.

func (*Database) Delete

func (t *Database) Delete(
	ctx context.Context,
	id string,
	rev string,
) error

Delete the given the content of the given id.

func (*Database) Find

func (t *Database) Find(
	ctx context.Context,
	format string,
	v ...interface{},
) (*FindResult, error)

Find execute a map-reduce query and return the FindResult.

The query documentation can be found here : http://docs.couchdb.org/en/2.1.1/api/database/find.html

func (*Database) Get

func (t *Database) Get(
	ctx context.Context,
	id string,
	valuePtr interface{},
) (string, error)

Get the value at the specified id and fill the given valuePtr with.

In case of success it will also return the current document revision.

The value will be deserialized using 'json.Unmarshal' so the 'json' tags set on your struct will be take in account.

func (*Database) Info

func (t *Database) Info(ctx context.Context) (*DatabaseInfo, error)

Info return a bunch of metadata about the database.

func (*Database) Name

func (t *Database) Name() string

Name return the database name.

func (*Database) QueryView

func (t *Database) QueryView(ctx context.Context, query *ViewQuery) ([]ViewRow, error)

QueryView will query a new linked to the database.

func (*Database) Set

func (t *Database) Set(
	ctx context.Context,
	id string,
	rev string,
	value interface{},
) (string, error)

Set the given value with the given id.

Couchdb works with the MVCC model (http://docs.couchdb.org/en/2.1.1/intro/api.html#revisions) and so for updating and already existing document, it need its revision.

If it the first time the key is used, keep the rev field empty. If a document have been already saved with this key, give the revision returned during the previous call.

In case of success it return the revision of the newly saved document.

The value will be serialized using 'json.Marshal' so the 'json' tags set in your struct will be take in account.

func (*Database) SetTimeout

func (t *Database) SetTimeout(timeout time.Duration)

SetTimeout for request deadline.

Once the timeout is reached, the request is aborted via the context. An empty duration is equivalent to no timeout set.

func (*Database) String

func (t *Database) String() string

String is an implementation of 'fmt.Stringer'.

type DatabaseInfo

type DatabaseInfo struct {
	Name              string      `json:"db_name"`
	Cluster           ClusterInfo `json:"cluster"`
	CompactRunning    bool        `json:"compact_running"`
	DiskFormatVersion int         `json:"disk_format_version"`
	DocCount          int         `json:"doc_count"`
	DocDelCount       int         `json:"doc_del_count"`
	InstanceStartTime string      `json:"instance_start_time"`
	PurgeSeq          int         `json:"purge_seq"`
	Sizes             SizesInfo   `json:"sizes"`
	UpdateSeq         string      `json:"update_seq"`
}

DatabaseInfo returned by the Info method.

type DatabaseMock

type DatabaseMock struct {
	mock.Mock
}

DatabaseMock is a mock implementation of 'Database' with the 'testify/mock' lib.

func (*DatabaseMock) Create

func (t *DatabaseMock) Create(_ context.Context) error

Create is a mock implementation of 'Database.Create' method.

func (*DatabaseMock) Destroy

func (t *DatabaseMock) Destroy(_ context.Context) error

Destroy is a mock implementation of 'Database.Destroy' method.

func (*DatabaseMock) Ensure

func (t *DatabaseMock) Ensure(_ context.Context) error

Ensure is a mock implementation of 'Database.Ensure' method.

func (*DatabaseMock) Exist

func (t *DatabaseMock) Exist(_ context.Context) (bool, error)

Exist is a mock implementation of 'Database.Exist' method.

func (*DatabaseMock) Find

func (t *DatabaseMock) Find(
	_ context.Context,
	format string,
	v ...interface{},
) (*FindResult, error)

Find is a mock implementation of 'Database.Find' method.

func (*DatabaseMock) Get

func (t *DatabaseMock) Get(
	_ context.Context, id string, valuePtr interface{},
) (string, error)

Get is a mock implementation of 'Database.Get' method.

func (*DatabaseMock) Info

Info is a mock implementation of 'Database.Info' method.

func (*DatabaseMock) Set

func (t *DatabaseMock) Set(
	_ context.Context, id string, rev string, value interface{},
) (string, error)

Set is a mock implementation of 'Database.Set' method.

type DesignDocument

type DesignDocument struct {
	Language Language        `json:"language" yaml:"language"`
	Views    map[string]View `json:"views" yaml:"views"`
}

DesignDocument regrouping views definitions.

type FindResult

type FindResult struct {
	Bookmark string            `json:"bookmark"`
	Docs     []json.RawMessage `json:"docs"`
	Warning  string            `json:"warning"`
}

FindResult is the Result of a 'Find' query.

It contains several documents which can be unmarshaled with a call to UnmarshalNext.

func NewFindResult

func NewFindResult(raw io.Reader) (*FindResult, error)

NewFindResult instantiate aa new FindResult.

func (*FindResult) Next

func (t *FindResult) Next() bool

Next return true is the next call document can be retrieved or not.

func (*FindResult) UnmarshalNext

func (t *FindResult) UnmarshalNext(valuePtr interface{}) (string, string, error)

UnmarshalNext retrieve the next document and fill valuePtr with.

The value will be deserialized using 'json.Unmarshal' so the 'json' tags set on your struct will be take in account.

type Language

type Language string

Language use for the DesignDocuments.

const (
	Javascript Language = "javascript"
	Erlang     Language = "erlang"
)

Languages availables for the DesignDocuments.

type Range

type Range struct {
	Start interface{}
	End   interface{}
}

Range for ViewQuery

type SizesInfo

type SizesInfo struct {
	Active   int `json:"active"`
	External int `json:"external"`
	File     int `json:"file"`
}

SizesInfo part of the Info response.

type SortOrder

type SortOrder int

SortOrder for ViewQuery

const (
	Ascending SortOrder = iota
	Descending
)

Available SortOrder for ViewQuery.

type View

type View struct {
	Map    string `json:"map,omitempty" yaml:"map,omitempty"`
	Reduce string `json:"reduce,omitempty" yaml:"reduce,omitempty"`
}

View definition.

type ViewQuery

type ViewQuery struct {
	DesignDocument string
	ViewName       string
	Limit          uint
	Skip           uint
	Order          SortOrder
	Keys           []interface{}
	Range          *Range
}

ViewQuery contains the parameters for query a view.

type ViewRow

type ViewRow struct {
	ID    string
	Key   interface{}
	Value json.RawMessage
}

ViewRow returned by a QueryView.

Jump to

Keyboard shortcuts

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