Categorygithub.com/boomfinity-developers/rethinkdb-go
modulepackage
0.7.2
Repository: https://github.com/boomfinity-developers/rethinkdb-go.git
Documentation: pkg.go.dev

# README

GoRethink - RethinkDB Driver for Go

GitHub tag GoDoc build status

Go driver for RethinkDB

Current version: v0.7.2 (RethinkDB v2.0)

Please note that this version of the driver only supports versions of RethinkDB using the v0.4 protocol (any versions of the driver older than RethinkDB 2.0 will not work).

Gitter

Installation

go get -u github.com/dancannon/gorethink

Connection

Basic Connection

Setting up a basic connection with RethinkDB is simple:

import (
    r "github.com/dancannon/gorethink"
)

var session *r.Session

session, err := r.Connect(r.ConnectOpts{
    Address: "localhost:28015",
})
if err != nil {
    log.Fatalln(err.Error())
}

See the documentation for a list of supported arguments to Connect().

Connection Pool

The driver uses a connection pool at all times, by default it creates and frees connections automatically. It's safe for concurrent use by multiple goroutines.

To configure the connection pool MaxIdle, MaxOpen and IdleTimeout can be specified during connection. If you wish to change the value of MaxIdle or MaxOpen during runtime then the functions SetMaxIdleConns and SetMaxOpenConns can be used.

var session *r.Session

session, err := r.Connect(r.ConnectOpts{
    Address: "localhost:28015",
    Database: "test",
    MaxIdle: 10,
    MaxOpen: 10,
})
if err != nil {
    log.Fatalln(err.Error())
}

session.SetMaxOpenConns(5)

Connect to a cluster

To connect to a RethinkDB cluster which has multiple nodes you can use the following syntax. When connecting to a cluster with multiple nodes queries will be distributed between these nodes.

var session *r.Session

session, err := r.Connect(r.ConnectOpts{
    Addresses: []string{"localhost:28015", "localhost:28016"},
    Database: "test",
    AuthKey:  "14daak1cad13dj",
    DiscoverHosts: true,
})
if err != nil {
    log.Fatalln(err.Error())
}

When DiscoverHosts is true any nodes are added to the cluster after the initial connection then the new node will be added to the pool of available nodes used by GoRethink.

Query Functions

This library is based on the official drivers so the code on the API page should require very few changes to work.

To view full documentation for the query functions check the GoDoc

Slice Expr Example

r.Expr([]interface{}{1, 2, 3, 4, 5}).Run(session)

Map Expr Example

r.Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Run(session)

Get Example

r.Db("database").Table("table").Get("GUID").Run(session)

Map Example (Func)

r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(func (row Term) interface{} {
    return row.Add(1)
}).Run(session)

Map Example (Implicit)

r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(r.Row.Add(1)).Run(session)

Between (Optional Args) Example

r.Db("database").Table("table").Between(1, 10, r.BetweenOpts{
    Index: "num",
    RightBound: "closed",
}).Run(session)

Optional Arguments

As shown above in the Between example optional arguments are passed to the function as a struct. Each function that has optional arguments as a related struct. This structs are named in the format FunctionNameOpts, for example BetweenOpts is the related struct for Between.

Results

Different result types are returned depending on what function is used to execute the query.

  • Run returns a cursor which can be used to view all rows returned.
  • RunWrite returns a WriteResponse and should be used for queries such as Insert, Update, etc...
  • Exec sends a query to the server and closes the connection immediately after reading the response from the database. If you do not wish to wait for the response then you can set the NoReply flag.

Example:

res, err := r.Db("database").Table("tablename").Get(key).Run(session)
if err != nil {
    // error
}
defer res.Close() // Always ensure you close the cursor to ensure connections are not leaked

Cursors have a number of methods available for accessing the query results

  • Next retrieves the next document from the result set, blocking if necessary.
  • All retrieves all documents from the result set into the provided slice.
  • One retrieves the first document from the result set.

Examples:

var row interface{}
for res.Next(&row) {
    // Do something with row
}
if res.Err() != nil {
    // error
}
var rows []interface{}
err := res.All(&rows)
if err != nil {
    // error
}
var row interface{}
err := res.One(&row)
if err == r.ErrEmptyResult {
    // row not found
}
if err != nil {
    // error
}

Encoding/Decoding Structs

When passing structs to Expr(And functions that use Expr such as Insert, Update) the structs are encoded into a map before being sent to the server. Each exported field is added to the map unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

Each fields default name in the map is the field name but can be specified in the struct field's tag value. The "gorethink" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

// Field is ignored by this package.
Field int `gorethink:"-"`
// Field appears as key "myName".
Field int `gorethink:"myName"`
// Field appears as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `gorethink:"myName,omitempty"`
// Field appears as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `gorethink:",omitempty"`

Alternatively you can implement the FieldMapper interface by providing the FieldMap function which returns a map of strings in the form of "FieldName": "NewName". For example:

type A struct {
    Field int
}

func (a A) FieldMap() map[string]string {
    return map[string]string{
        "Field": "myName",
    }
}

Benchmarks

Everyone wants their project's benchmarks to be speedy. And while we know that rethinkDb and the gorethink driver are quite fast, our primary goal is for our benchmarks to be correct. They are designed to give you, the user, an accurate picture of writes per second (w/s). If you come up with a accurate test that meets this aim, submit a pull request please.

Thanks to @jaredfolkins for the contribution.

TypeValue
Model NameMacBook Pro
Model IdentifierMacBookPro11,3
Processor NameIntel Core i7
Processor Speed2.3 GHz
Number of Processors1
Total Number of Cores4
L2 Cache (per Core)256 KB
L3 Cache6 MB
Memory16 GB
BenchmarkBatch200RandomWrites                20                              557227775                     ns/op
BenchmarkBatch200RandomWritesParallel10      30                              354465417                     ns/op
BenchmarkBatch200SoftRandomWritesParallel10  100                             761639276                     ns/op
BenchmarkRandomWrites                        100                             10456580                      ns/op
BenchmarkRandomWritesParallel10              1000                            1614175                       ns/op
BenchmarkRandomSoftWrites                    3000                            589660                        ns/op
BenchmarkRandomSoftWritesParallel10          10000                           247588                        ns/op
BenchmarkSequentialWrites                    50                              24408285                      ns/op
BenchmarkSequentialWritesParallel10          1000                            1755373                       ns/op
BenchmarkSequentialSoftWrites                3000                            631211                        ns/op
BenchmarkSequentialSoftWritesParallel10      10000                           263481                        ns/op

Examples

View other examples on the wiki.

License

Copyright 2013 Daniel Cannon

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author

# Functions

Add sums two numbers or concatenates two arrays.
And performs a logical and on two values.
Args is a special term usd to splice an array of arguments into another term.
No description provided by the author
Binary encapsulates binary data within a query.
Evaluate one of two control paths based on the value of an expression.
Circle constructs a circular line or polygon.
Connect creates a new database session.
Reference a database.
Create a database.
Drop a database.
List all database names in the system.
No description provided by the author
Distance calculates the Haversine distance between two points.
Div divides two numbers.
Evaluate the expr in the context of one or more value bindings.
Returns a time object based on seconds since epoch.
Eq returns true if two values are equal.
Throw a runtime error.
Expr converts any value to an expression.
Ge returns true if the first value is greater than or equal to the second.
Geojson converts a GeoJSON object to a ReQL geometry object.
Gt returns true if the first value is greater than the second.
Parse a JSON string on the server.
Returns a time object based on an ISO8601 formatted date-time string Optional arguments (see http://www.rethinkdb.com/api/#js:dates_and_times-iso8601 for more information): "default_timezone" (string).
Create a JavaScript expression.
Parse a JSON string on the server.
Le returns true if the first value is less than or equal to the second.
Line constructs a geometry object of type Line.
No description provided by the author
Lt returns true if the first value is less than the second.
Map transform each element of the sequence by applying the given mapping function.
Mod divides two numbers and returns the remainder.
Mul multiplies two numbers.
Ne returns true if two values are not equal.
NewCluster creates a new cluster by connecting to the given hosts.
NewConnection creates a new connection to the database server.
NewHost create a new Host.
NewPool creates a new connection pool for the given host.
Not performs a logical not on a value.
Returns a time object representing the current time in UTC.
Creates an object from a list of key-value pairs, where the keys must be strings.
Or performs a logical or on two values.
Point constructs a geometry object of type Point.
Polygon constructs a geometry object of type Polygon.
Range generates a stream of sequential integers in a specified range.
SetVerbose allows the driver logging level to be set.
Sub subtracts two numbers.
Select all documents in a table.
Create a time object for a specific time.
UUID returns a UUID (universally unique identifier), a string that can be used as a unique ID.
Wait for a table or all the tables in a database to be ready.

# Variables

No description provided by the author
No description provided by the author
No description provided by the author
ErrBadConn should be returned by a connection operation to signal to the pool that a driver.Conn is in a bad state (such as the server having earlier closed the connection) and the pool should retry on a new connection.
No description provided by the author
No description provided by the author
No description provided by the author
Error constants.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Months.
No description provided by the author
No description provided by the author
No description provided by the author
MaxVal represents the smallest possible value RethinkDB can store.
No description provided by the author
MinVal represents the smallest possible value RethinkDB can store.
Days.
No description provided by the author
No description provided by the author
Returns the currently visited document.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
CircleOpts describes the optional arguments for a Circle operation.
CloseOpts allows calls to the Close function to be configured.
A Cluster represents a connection to a RethinkDB cluster, a cluster is created by the Session and should rarely be created manually.
Connection is a connection to a rethinkdb database.
ConnectOpts is used to specify optional arguments when connecting to a cluster.
Cursor is the result of a query.
No description provided by the author
DistanceOpts describes the optional arguments for a Distance operation.
No description provided by the author
No description provided by the author
No description provided by the author
ExecOpts inherits its options from RunOpts, the only difference is the addition of the NoReply field.
No description provided by the author
GetIntersectingOpts describes the optional arguments for a GetIntersecting operation.
GetIntersectingOpts describes the optional arguments for a GetIntersecting operation.
Host name and port of server.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Node represents a database server in the cluster.
No description provided by the author
A Pool is used to store a pool of connections to a single RethinkDB server.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
A Session represents a connection to a RethinkDB cluster and should be used when executing queries.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author