gorethink

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2014 License: Apache-2.0 Imports: 21 Imported by: 0

README

GoRethink - RethinkDB Driver for Go wercker status GoDoc

Go driver for RethinkDB made by Daniel Cannon and based off of Christopher Hesse's RethinkGo driver.

Current version: v0.4.1 (RethinkDB v1.14)

Version 0.3 introduced some API changes, for more information check the change log

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",
    Database: "test",
})

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, however by default there is only a single connection available. In order to turn this into a proper connection pool, we need to pass the maxIdle, maxActive and/or idleTimeout parameters to Connect():

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

var session *r.Session

session, err := r.Connect(r.ConnectOpts{
    Address:  "localhost:28015",
    Database: "test",
    MaxIdle: 10,
    IdleTimeout: time.Second * 10,
})

if err != nil {
    log.Fatalln(err.Error())
}

A pre-configured Pool instance can also be passed to Connect().

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 with the noreply flag set and returns immediately

Example:

res, err := Table("tablename").Get(key).Run(session)
if err != nil {
    // error
}

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 se.

Examples:

var row interface{}
for res.Next(&result) {
    // 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",
    }
}

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.

Documentation

Overview

Go driver for RethinkDB

Current version: v0.4.1 (RethinkDB v1.14) For more in depth information on how to use RethinkDB check out the API docs at http://rethinkdb.com/api

Example
package main

import (
	"fmt"
	"log"
	"os"

	r "github.com/dancannon/gorethink"
)

var session *r.Session
var url, authKey string

func init() {
	// Needed for wercker. By default url is "localhost:28015"
	url = os.Getenv("RETHINKDB_URL")
	if url == "" {
		url = "localhost:28015"
	}

	// Needed for running tests for RethinkDB with a non-empty authkey
	authKey = os.Getenv("RETHINKDB_AUTHKEY")
}

func main() {
	session, err := r.Connect(r.ConnectOpts{
		Address: url,
		AuthKey: authKey,
	})
	if err != nil {
		log.Fatalf("Error connecting to DB: %s", err)
	}

	res, err := r.Expr("Hello World").Run(session)
	if err != nil {
		log.Fatalln(err.Error())
	}

	var response string
	err = res.One(&response)
	if err != nil {
		log.Fatalln(err.Error())
	}

	fmt.Println(response)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Days
	Monday    = constructRootTerm("Monday", p.Term_MONDAY, []interface{}{}, map[string]interface{}{})
	Tuesday   = constructRootTerm("Tuesday", p.Term_TUESDAY, []interface{}{}, map[string]interface{}{})
	Wednesday = constructRootTerm("Wednesday", p.Term_WEDNESDAY, []interface{}{}, map[string]interface{}{})
	Thursday  = constructRootTerm("Thursday", p.Term_THURSDAY, []interface{}{}, map[string]interface{}{})
	Friday    = constructRootTerm("Friday", p.Term_FRIDAY, []interface{}{}, map[string]interface{}{})
	Saturday  = constructRootTerm("Saturday", p.Term_SATURDAY, []interface{}{}, map[string]interface{}{})
	Sunday    = constructRootTerm("Sunday", p.Term_SUNDAY, []interface{}{}, map[string]interface{}{})

	// Months
	January   = constructRootTerm("January", p.Term_JANUARY, []interface{}{}, map[string]interface{}{})
	February  = constructRootTerm("February", p.Term_FEBRUARY, []interface{}{}, map[string]interface{}{})
	March     = constructRootTerm("March", p.Term_MARCH, []interface{}{}, map[string]interface{}{})
	April     = constructRootTerm("April", p.Term_APRIL, []interface{}{}, map[string]interface{}{})
	May       = constructRootTerm("May", p.Term_MAY, []interface{}{}, map[string]interface{}{})
	June      = constructRootTerm("June", p.Term_JUNE, []interface{}{}, map[string]interface{}{})
	July      = constructRootTerm("July", p.Term_JULY, []interface{}{}, map[string]interface{}{})
	August    = constructRootTerm("August", p.Term_AUGUST, []interface{}{}, map[string]interface{}{})
	September = constructRootTerm("September", p.Term_SEPTEMBER, []interface{}{}, map[string]interface{}{})
	October   = constructRootTerm("October", p.Term_OCTOBER, []interface{}{}, map[string]interface{}{})
	November  = constructRootTerm("November", p.Term_NOVEMBER, []interface{}{}, map[string]interface{}{})
	December  = constructRootTerm("December", p.Term_DECEMBER, []interface{}{}, map[string]interface{}{})
)
View Source
var ErrEmptyResult = errors.New("The result does not contain any more rows")

Error constants

View Source
var Row = constructRootTerm("Doc", p.Term_IMPLICIT_VAR, []interface{}{}, map[string]interface{}{})

Returns the currently visited document.

Functions

func Dial

func Dial(s *Session) pool.Factory

Dial closes the previous connection and attempts to connect again.

func TestOnBorrow

func TestOnBorrow(c *Connection, t time.Time) error

Types

type BetweenOpts

type BetweenOpts struct {
	Index      interface{} `gorethink:"index,omitempty"`
	LeftBound  interface{} `gorethink:"left_bound,omitempty"`
	RightBound interface{} `gorethink:"right_bound,omitempty"`
}

type CloseOpts

type CloseOpts struct {
	NoReplyWait bool `gorethink:"noreplyWait,omitempty"`
}

type Conn

type Conn interface {
	SendQuery(s *Session, q *p.Query, t Term, opts map[string]interface{}, async bool) (*Cursor, error)
	ReadResponse(s *Session, token int64) (*Response, error)
	Close() error
}

type ConnectOpts

type ConnectOpts struct {
	Token       int64         `gorethink:"token,omitempty"`
	Address     string        `gorethink:"address,omitempty"`
	Database    string        `gorethink:"database,omitempty"`
	Timeout     time.Duration `gorethink:"timeout,omitempty"`
	AuthKey     string        `gorethink:"authkey,omitempty"`
	MaxIdle     int           `gorethink:"max_idle,omitempty"`
	MaxActive   int           `gorethink:"max_active,omitempty"`
	IdleTimeout time.Duration `gorethink:"idle_timeout,omitempty"`
}

type Connection

type Connection struct {
	// embed the net.Conn type, so that we can effectively define new methods on
	// it (interfaces do not allow that)
	net.Conn

	sync.Mutex
	// contains filtered or unexported fields
}

connection is a connection to a rethinkdb database

func (*Connection) Close

func (c *Connection) Close() error

func (*Connection) NoreplyWait added in v0.3.2

func (c *Connection) NoreplyWait() error

noreplyWaitQuery sends the NOREPLY_WAIT query to the server. TODO: Removed duplicated functions in connection and session for NoReplyWait

func (*Connection) ReadResponse

func (c *Connection) ReadResponse(s *Session, token int64) (*Response, error)

func (*Connection) SendQuery

func (c *Connection) SendQuery(s *Session, q Query, opts map[string]interface{}, async bool) (*Cursor, error)

type Cursor

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

Cursors are used to represent data returned from the database.

The code for this struct is based off of mgo's Iter and the official python driver's cursor.

func (*Cursor) All

func (c *Cursor) All(result interface{}) error

All retrieves all documents from the result set into the provided slice and closes the cursor.

The result argument must necessarily be the address for a slice. The slice may be nil or previously allocated.

func (*Cursor) Close

func (c *Cursor) Close() error

Close closes the cursor, preventing further enumeration. If the end is encountered, the cursor is closed automatically. Close is idempotent.

func (*Cursor) Err

func (c *Cursor) Err() error

Err returns nil if no errors happened during iteration, or the actual error otherwise.

func (*Cursor) IsNil

func (c *Cursor) IsNil() bool

Tests if the current row is nil.

func (*Cursor) Next

func (c *Cursor) Next(result interface{}) bool

Next retrieves the next document from the result set, blocking if necessary. This method will also automatically retrieve another batch of documents from the server when the current one is exhausted, or before that in background if possible.

Next returns true if a document was successfully unmarshalled onto result, and false at the end of the result set or if an error happened. When Next returns false, the Err method should be called to verify if there was an error during iteration.

func (*Cursor) One

func (c *Cursor) One(result interface{}) error

One retrieves a single document from the result set into the provided slice and closes the cursor.

func (*Cursor) Profile

func (c *Cursor) Profile() interface{}

Profile returns the information returned from the query profiler.

type DeleteOpts

type DeleteOpts struct {
	Durability    interface{} `gorethink:"durability,omitempty"`
	ReturnChanges interface{} `gorethink:"return_changes,omitempty"`
}

type DistinctOpts added in v0.4.0

type DistinctOpts struct {
	Index interface{} `gorethink:"index,omitempty"`
}

type DuringOpts

type DuringOpts struct {
	LeftBound  interface{} `gorethink:"left_bound,omitempty"`
	RightBound interface{} `gorethink:"right_bound,omitempty"`
}

type EqJoinOpts

type EqJoinOpts struct {
	Index interface{} `gorethink:"index,omitempty"`
}

type FilterOpts

type FilterOpts struct {
	Default interface{} `gorethink:"default,omitempty"`
}

type HttpOpts

type HttpOpts struct {
	// General Options
	Timeout      interface{} `gorethink:"timeout,omitempty"`
	Reattempts   interface{} `gorethink:"reattempts,omitempty"`
	Redirects    interface{} `gorethink:"redirect,omitempty"`
	Verify       interface{} `gorethink:"verify,omitempty"`
	ResultFormat interface{} `gorethink:"resul_format,omitempty"`

	// Request Options
	Method interface{} `gorethink:"method,omitempty"`
	Auth   interface{} `gorethink:"auth,omitempty"`
	Params interface{} `gorethink:"params,omitempty"`
	Header interface{} `gorethink:"header,omitempty"`
	Data   interface{} `gorethink:"data,omitempty"`

	// Pagination
	Page      interface{} `gorethink:"page,omitempty"`
	PageLimit interface{} `gorethink:"page_limit,omitempty"`
}

type ISO8601Opts

type ISO8601Opts struct {
	DefaultTimezone interface{} `gorethink:"default_timezone,omitempty"`
}

type IndexCreateOpts

type IndexCreateOpts struct {
	Multi interface{} `gorethink:"multi,omitempty"`
}

type IndexRenameOpts added in v0.4.0

type IndexRenameOpts struct {
	Overwrite interface{} `gorethink:"overwrite,omitempty"`
}

type InsertOpts

type InsertOpts struct {
	Durability    interface{} `gorethink:"durability,omitempty"`
	ReturnChanges interface{} `gorethink:"return_changes,omitempty"`
	CacheSize     interface{} `gorethink:"cache_size,omitempty"`
	Conflict      interface{} `gorethink:"conflict,omitempty"`
}

type OptArgs

type OptArgs interface {
	// contains filtered or unexported methods
}

type OrderByOpts

type OrderByOpts struct {
	Index interface{} `gorethink:"index,omitempty"`
}

type Query added in v0.4.0

type Query struct {
	Type       p.Query_QueryType
	Token      int64
	Term       *Term
	GlobalOpts map[string]interface{}
}

type RandomOpts

type RandomOpts struct {
	Float interface{} `gorethink:"float,omitempty"`
}

type ReplaceOpts

type ReplaceOpts struct {
	Durability    interface{} `gorethink:"durability,omitempty"`
	ReturnChanges interface{} `gorethink:"return_changes,omitempty"`
	NotAtomic     interface{} `gorethink:"non_atomic,omitempty"`
}

type Response added in v0.4.0

type Response struct {
	Token     int64
	Type      p.Response_ResponseType `json:"t"`
	Responses []interface{}           `json:"r"`
	Backtrace []interface{}           `json:"b"`
	Profile   interface{}             `json:"p"`
}

type RqlClientError

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

func (RqlClientError) Error

func (e RqlClientError) Error() string

func (RqlClientError) String

func (e RqlClientError) String() string

type RqlCompileError

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

func (RqlCompileError) Error

func (e RqlCompileError) Error() string

func (RqlCompileError) String

func (e RqlCompileError) String() string

type RqlConnectionError

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

func (RqlConnectionError) Error

func (e RqlConnectionError) Error() string

func (RqlConnectionError) String

func (e RqlConnectionError) String() string

type RqlDriverError

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

func (RqlDriverError) Error

func (e RqlDriverError) Error() string

func (RqlDriverError) String

func (e RqlDriverError) String() string

type RqlRuntimeError

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

func (RqlRuntimeError) Error

func (e RqlRuntimeError) Error() string

func (RqlRuntimeError) String

func (e RqlRuntimeError) String() string

type RunOpts

type RunOpts struct {
	Db           interface{} `gorethink:"db,omitempty"`
	Profile      interface{} `gorethink:"profile,omitempty"`
	UseOutdated  interface{} `gorethink:"use_outdated,omitempty"`
	NoReply      interface{} `gorethink:"noreply,omitempty"`
	ArrayLimit   interface{} `gorethink:"array_limit,omitempty"`
	TimeFormat   interface{} `gorethink:"time_format,omitempty"`
	GroupFormat  interface{} `gorethink:"group_format,omitempty"`
	BinaryFormat interface{} `gorethink:"binary_format,omitempty"`

	BatchConf interface{} `gorethink:"batch_conf,omitempty"`
}

type Session

type Session struct {

	// Response cache, used for batched responses
	sync.Mutex
	// contains filtered or unexported fields
}

func Connect

func Connect(args ConnectOpts) (*Session, error)

Connect creates a new database session.

Supported arguments include token, address, database, timeout, authkey, and timeFormat. Pool options include maxIdle, maxActive and idleTimeout.

By default maxIdle and maxActive are set to 1: passing values greater than the default (e.g. maxIdle: "10", maxActive: "20") will provide a pool of re-usable connections.

Basic connection example:

var session *r.Session
session, err := r.Connect(r.ConnectOpts{
	Address:  "localhost:28015",
	Database: "test",
	AuthKey:  "14daak1cad13dj",
})

func (*Session) Close

func (s *Session) Close(optArgs ...CloseOpts) error

Close closes the session

func (*Session) NoReplyWait

func (s *Session) NoReplyWait()

noreplyWait ensures that previous queries with the noreply flag have been processed by the server. Note that this guarantee only applies to queries run on the given connection

func (*Session) Reconnect

func (s *Session) Reconnect(optArgs ...CloseOpts) error

Reconnect closes and re-opens a session.

func (*Session) SetTimeout

func (s *Session) SetTimeout(timeout time.Duration)

SetTimeout causes any future queries that are run on this session to timeout after the given duration, returning a timeout error. Set to zero to disable.

func (*Session) Use

func (s *Session) Use(database string)

Use changes the default database used

type SliceOpts

type SliceOpts struct {
	LeftBound  interface{} `gorethink:"left_bound,omitempty"`
	RightBound interface{} `gorethink:"right_bound,omitempty"`
}

type TableCreateOpts

type TableCreateOpts struct {
	PrimaryKey interface{} `gorethink:"primary_key,omitempty"`
	Durability interface{} `gorethink:"durability,omitempty"`
	CacheSize  interface{} `gorethink:"cache_size,omitempty"`
	DataCenter interface{} `gorethink:"datacenter,omitempty"`
}

type TableOpts

type TableOpts struct {
	UseOutdated interface{} `gorethink:"use_outdated,omitempty"`
}

type Term

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

func Add

func Add(args ...interface{}) Term

Add sums two numbers or concatenates two arrays.

func And

func And(args ...interface{}) Term

And performs a logical and on two values.

func Args

func Args(args ...interface{}) Term

Args is a special term usd to splice an array of arguments into another term. This is useful when you want to call a varadic term such as GetAll with a set of arguments provided at runtime.

func Asc

func Asc(args ...interface{}) Term

func Binary added in v0.4.0

func Binary(data interface{}) Term

Binary encapsulates binary data within a query.

func Branch

func Branch(args ...interface{}) Term

Evaluate one of two control paths based on the value of an expression. branch is effectively an if renamed due to language constraints.

The type of the result is determined by the type of the branch that gets executed.

func Db

func Db(args ...interface{}) Term

Reference a database.

func DbCreate

func DbCreate(args ...interface{}) Term

Create a database. A RethinkDB database is a collection of tables, similar to relational databases.

If successful, the operation returns an object: {created: 1}. If a database with the same name already exists the operation throws RqlRuntimeError.

Note: that you can only use alphanumeric characters and underscores for the database name.

func DbDrop

func DbDrop(args ...interface{}) Term

Drop a database. The database, all its tables, and corresponding data will be deleted.

If successful, the operation returns the object {dropped: 1}. If the specified database doesn't exist a RqlRuntimeError is thrown.

func DbList

func DbList(args ...interface{}) Term

List all database names in the system.

func Desc

func Desc(args ...interface{}) Term

func Div

func Div(args ...interface{}) Term

Div divides two numbers.

func Do

func Do(args ...interface{}) Term

Evaluate the expr in the context of one or more value bindings. The type of the result is the type of the value returned from expr.

func EpochTime

func EpochTime(args ...interface{}) Term

Returns a time object based on seconds since epoch

func Eq

func Eq(args ...interface{}) Term

Eq returns true if two values are equal.

func Error

func Error(args ...interface{}) Term

Throw a runtime error. If called with no arguments inside the second argument to `default`, re-throw the current error.

func Expr

func Expr(value interface{}) Term

Expr converts any value to an expression. Internally it uses the `json` module to convert any literals, so any type annotations or methods understood by that module can be used. If the value cannot be converted, an error is returned at query .Run(session) time.

If you want to call expression methods on an object that is not yet an expression, this is the function you want.

func Ge

func Ge(args ...interface{}) Term

Ge returns true if the first value is greater than or equal to the second.

func Gt

func Gt(args ...interface{}) Term

Gt returns true if the first value is greater than the second.

func Http

func Http(url interface{}, optArgs ...HttpOpts) Term

Parse a JSON string on the server.

func ISO8601

func ISO8601(date interface{}, optArgs ...ISO8601Opts) Term

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)

func Js

func Js(jssrc interface{}) Term

Create a JavaScript expression.

func Json

func Json(args ...interface{}) Term

Parse a JSON string on the server.

func Le

func Le(args ...interface{}) Term

Le returns true if the first value is less than or equal to the second.

func Literal

func Literal(args ...interface{}) Term

func Lt

func Lt(args ...interface{}) Term

Lt returns true if the first value is less than the second.

func Mod

func Mod(args ...interface{}) Term

Mod divides two numbers and returns the remainder.

func Mul

func Mul(args ...interface{}) Term

func Ne

func Ne(args ...interface{}) Term

Ne returns true if two values are not equal.

func Not

func Not(args ...interface{}) Term

Not performs a logical not on a value.

func Now

func Now(args ...interface{}) Term

Returns a time object representing the current time in UTC

func Object

func Object(args ...interface{}) Term

Creates an object from a list of key-value pairs, where the keys must be strings.

func Or

func Or(args ...interface{}) Term

Or performs a logical or on two values.

func Sub

func Sub(args ...interface{}) Term

Sub subtracts two numbers.

func Table

func Table(name interface{}, optArgs ...TableOpts) Term

Select all documents in a table. This command can be chained with other commands to do further processing on the data.

Optional arguments (see http://www.rethinkdb.com/api/#js:selecting_data-table for more information): "use_outdated" (boolean - defaults to false)

func Time

func Time(args ...interface{}) Term

Create a time object for a specific time

func (Term) Add

func (t Term) Add(args ...interface{}) Term

Add sums two numbers or concatenates two arrays.

func (Term) And

func (t Term) And(args ...interface{}) Term

And performs a logical and on two values.

func (Term) Append

func (t Term) Append(args ...interface{}) Term

Append a value to an array.

func (Term) Avg

func (t Term) Avg(args ...interface{}) Term

Averages all the elements of a sequence. If called with a field name, averages all the values of that field in the sequence, skipping elements of the sequence that lack that field. If called with a function, calls that function on every element of the sequence and averages the results, skipping elements of the sequence where that function returns null or a non-existence error.

func (Term) Between

func (t Term) Between(lowerKey, upperKey interface{}, optArgs ...BetweenOpts) Term

Get all documents between two keys. Accepts three optional arguments: `index`, `left_bound`, and `right_bound`. If `index` is set to the name of a secondary index, `between` will return all documents where that index's value is in the specified range (it uses the primary key by default). `left_bound` or `right_bound` may be set to `open` or `closed` to indicate whether or not to include that endpoint of the range (by default, `left_bound` is closed and `right_bound` is open).

func (Term) ChangeAt

func (t Term) ChangeAt(args ...interface{}) Term

Change a value in an array at a given index. Returns the modified array.

func (Term) Changes

func (t Term) Changes() Term

Takes a table and returns an infinite stream of objects representing changes to that table. Whenever an insert, delete, update or replace is performed on the table, an object of the form {old_val:..., new_val:...} will be added to the stream. For an insert, old_val will be null, and for a delete, new_val will be null.

func (Term) CoerceTo

func (t Term) CoerceTo(args ...interface{}) Term

Converts a value of one type into another.

You can convert: a selection, sequence, or object into an ARRAY, an array of pairs into an OBJECT, and any DATUM into a STRING.

func (Term) ConcatMap

func (t Term) ConcatMap(args ...interface{}) Term

Flattens a sequence of arrays returned by the mapping function into a single sequence.

func (Term) Contains

func (t Term) Contains(args ...interface{}) Term

Returns whether or not a sequence contains all the specified values, or if functions are provided instead, returns whether or not a sequence contains values matching all the specified functions.

func (Term) Count

func (t Term) Count(args ...interface{}) Term

Count the number of elements in the sequence. With a single argument, count the number of elements equal to it. If the argument is a function, it is equivalent to calling filter before count.

func (Term) Date

func (t Term) Date(args ...interface{}) Term

Return a new time object only based on the day, month and year (ie. the same day at 00:00).

func (Term) Day

func (t Term) Day(args ...interface{}) Term

Return the day of a time object as a number between 1 and 31.

func (Term) DayOfWeek

func (t Term) DayOfWeek(args ...interface{}) Term

Return the day of week of a time object as a number between 1 and 7 (following ISO 8601 standard). For your convenience, the terms r.Monday(), r.Tuesday() etc. are defined and map to the appropriate integer.

func (Term) DayOfYear

func (t Term) DayOfYear(args ...interface{}) Term

Return the day of the year of a time object as a number between 1 and 366 (following ISO 8601 standard).

func (Term) Default

func (t Term) Default(args ...interface{}) Term

Handle non-existence errors. Tries to evaluate and return its first argument. If an error related to the absence of a value is thrown in the process, or if its first argument returns null, returns its second argument. (Alternatively, the second argument may be a function which will be called with either the text of the non-existence error or null.)

func (Term) Delete

func (t Term) Delete(optArgs ...DeleteOpts) Term

Delete one or more documents from a table. The optional argument return_changes will return the old value of the row you're deleting when set to true (only valid for single-row deletes). The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting.

func (Term) DeleteAt

func (t Term) DeleteAt(args ...interface{}) Term

Remove an element from an array at a given index. Returns the modified array.

func (Term) Difference

func (t Term) Difference(args ...interface{}) Term

Remove the elements of one array from another array.

func (Term) Distinct

func (t Term) Distinct(optArgs ...DistinctOpts) Term

Remove duplicate elements from the sequence.

func (Term) Div

func (t Term) Div(args ...interface{}) Term

Div divides two numbers.

func (Term) Do

func (t Term) Do(args ...interface{}) Term

Evaluate the expr in the context of one or more value bindings. The type of the result is the type of the value returned from expr.

func (Term) Downcase

func (t Term) Downcase(args ...interface{}) Term

Downcases a string.

func (Term) During

func (t Term) During(startTime, endTime interface{}, optArgs ...DuringOpts) Term

Returns true if a time is between two other times (by default, inclusive for the start, exclusive for the end).

Optional arguments (see http://www.rethinkdb.com/api/#js:dates_and_times-during for more information): "left_bound" and "right_bound" ("open" for exclusive or "closed" for inclusive)

func (Term) Eq

func (t Term) Eq(args ...interface{}) Term

Eq returns true if two values are equal.

func (Term) EqJoin

func (t Term) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) Term

An efficient join that looks up elements in the right table by primary key.

Optional arguments: "index" (string - name of the index to use in right table instead of the primary key)

func (Term) Exec

func (t Term) Exec(s *Session, optArgs ...RunOpts) error

Exec runs the query but does not return the result.

func (Term) Field

func (t Term) Field(args ...interface{}) Term

Get a single field from an object. If called on a sequence, gets that field from every object in the sequence, skipping objects that lack it.

func (Term) Filter

func (t Term) Filter(f interface{}, optArgs ...FilterOpts) Term

Get all the documents for which the given predicate is true.

Filter can be called on a sequence, selection, or a field containing an array of elements. The return type is the same as the type on which the function was called on. The body of every filter is wrapped in an implicit `.default(false)`, and the default value can be changed by passing the optional argument `default`. Setting this optional argument to `r.error()` will cause any non-existence errors to abort the filter.

func (Term) ForEach

func (t Term) ForEach(args ...interface{}) Term

Loop over a sequence, evaluating the given write query for each element.

func (Term) Ge

func (t Term) Ge(args ...interface{}) Term

Ge returns true if the first value is greater than or equal to the second.

func (Term) Get

func (t Term) Get(args ...interface{}) Term

Get a document by primary key. If nothing was found, RethinkDB will return a nil value.

func (Term) GetAll

func (t Term) GetAll(keys ...interface{}) Term

Get all documents where the given value matches the value of the primary index.

func (Term) GetAllByIndex

func (t Term) GetAllByIndex(index interface{}, keys ...interface{}) Term

Get all documents where the given value matches the value of the requested index.

func (Term) Group

func (t Term) Group(fieldOrFunctions ...interface{}) Term

Takes a stream and partitions it into multiple groups based on the fields or functions provided. Commands chained after group will be

called on each of these grouped sub-streams, producing grouped data.

func (Term) GroupByIndex

func (t Term) GroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term

Takes a stream and partitions it into multiple groups based on the fields or functions provided. Commands chained after group will be called on each of these grouped sub-streams, producing grouped data.

func (Term) Gt

func (t Term) Gt(args ...interface{}) Term

Gt returns true if the first value is greater than the second.

func (Term) HasFields

func (t Term) HasFields(args ...interface{}) Term

Test if an object has all of the specified fields. An object has a field if it has the specified key and that key maps to a non-null value. For instance,

the object `{'a':1,'b':2,'c':null}` has the fields `a` and `b`.

func (Term) Hours

func (t Term) Hours(args ...interface{}) Term

Return the hour in a time object as a number between 0 and 23.

func (Term) InTimezone

func (t Term) InTimezone(args ...interface{}) Term

Returns a new time object with a different time zone. While the time stays the same, the results returned by methods such as hours() will change since they take the timezone into account. The timezone argument has to be of the ISO 8601 format.

func (Term) IndexCreate

func (t Term) IndexCreate(name interface{}, optArgs ...IndexCreateOpts) Term

Create a new secondary index on this table.

A multi index can be created by passing an optional multi argument. Multi indexes

functions should return arrays and allow you to query based on whether a value
is present in the returned array. The example would allow us to get heroes who
possess a specific ability (the field 'abilities' is an array).

func (Term) IndexCreateFunc

func (t Term) IndexCreateFunc(name, f interface{}, optArgs ...IndexCreateOpts) Term

Create a new secondary index on this table based on the value of the function passed.

A compound index can be created by returning an array of values to use as the secondary index key.

func (Term) IndexDrop

func (t Term) IndexDrop(args ...interface{}) Term

Delete a previously created secondary index of this table.

func (Term) IndexList

func (t Term) IndexList(args ...interface{}) Term

List all the secondary indexes of this table.

func (Term) IndexRename added in v0.4.0

func (t Term) IndexRename(oldName, newName interface{}, optArgs ...IndexRenameOpts) Term

IndexRename renames an existing secondary index on a table. If the optional argument overwrite is specified as True, a previously existing index with the new name will be deleted and the index will be renamed. If overwrite is False (the default) an error will be raised if the new index name already exists.

func (Term) IndexStatus

func (t Term) IndexStatus(args ...interface{}) Term

Get the status of the specified indexes on this table, or the status of all indexes on this table if no indexes are specified.

func (Term) IndexWait

func (t Term) IndexWait(args ...interface{}) Term

Wait for the specified indexes on this table to be ready, or for all indexes on this table to be ready if no indexes are specified.

func (Term) IndexesOf

func (t Term) IndexesOf(args ...interface{}) Term

Get the indexes of an element in a sequence. If the argument is a predicate, get the indexes of all elements matching it.

func (Term) Info

func (t Term) Info(args ...interface{}) Term

Get information about a RQL value.

func (Term) InnerJoin

func (t Term) InnerJoin(args ...interface{}) Term

Returns the inner product of two sequences (e.g. a table, a filter result) filtered by the predicate. The query compares each row of the left sequence with each row of the right sequence to find all pairs of rows which satisfy the predicate. When the predicate is satisfied, each matched pair of rows of both sequences are combined into a result row.

func (Term) Insert

func (t Term) Insert(arg interface{}, optArgs ...InsertOpts) Term

Insert JSON documents into a table. Accepts a single JSON document or an array of documents. You may also pass the optional argument durability with value 'hard' or 'soft', to override the table or query's default durability setting, or the optional argument return_changes, which will return the value of the row you're inserting when set to true.

table.Insert(map[string]interface{}{"name": "Joe", "email": "joe@example.com"}).RunWrite(sess)
table.Insert([]interface{}{map[string]interface{}{"name": "Joe"}, map[string]interface{}{"name": "Paul"}}).RunWrite(sess)

func (Term) InsertAt

func (t Term) InsertAt(args ...interface{}) Term

Insert a value in to an array at a given index. Returns the modified array.

func (Term) IsEmpty

func (t Term) IsEmpty(args ...interface{}) Term

Test if a sequence is empty.

func (Term) Keys

func (t Term) Keys(args ...interface{}) Term

Return an array containing all of the object's keys.

func (Term) Le

func (t Term) Le(args ...interface{}) Term

Le returns true if the first value is less than or equal to the second.

func (Term) Limit

func (t Term) Limit(args ...interface{}) Term

End the sequence after the given number of elements.

func (Term) Lt

func (t Term) Lt(args ...interface{}) Term

Lt returns true if the first value is less than the second.

func (Term) Map

func (t Term) Map(args ...interface{}) Term

Transform each element of the sequence by applying the given mapping function.

func (Term) Match

func (t Term) Match(args ...interface{}) Term

Match against a regular expression. Returns a match object containing the matched string, that string's start/end position, and the capture groups.

Expr("id:0,name:mlucy,foo:bar").Match("name:(\\w+)").Field("groups").Nth(0).Field("str")

func (Term) Max

func (t Term) Max(args ...interface{}) Term

Finds the maximum of a sequence. If called with a field name, finds the element of that sequence with the largest value in that field. If called with a function, calls that function on every element of the sequence and returns the element which produced the largest value, ignoring any elements where the function returns null or produces a non-existence error.

func (Term) Merge

func (t Term) Merge(args ...interface{}) Term

Merge two objects together to construct a new object with properties from both. Gives preference to attributes from other when there is a conflict.

func (Term) Min

func (t Term) Min(args ...interface{}) Term

Finds the minimum of a sequence. If called with a field name, finds the element of that sequence with the smallest value in that field. If called with a function, calls that function on every element of the sequence and returns the element which produced the smallest value, ignoring any elements where the function returns null or produces a non-existence error.

func (Term) Minutes

func (t Term) Minutes(args ...interface{}) Term

Return the minute in a time object as a number between 0 and 59.

func (Term) Mod

func (t Term) Mod(args ...interface{}) Term

Mod divides two numbers and returns the remainder.

func (Term) Month

func (t Term) Month(args ...interface{}) Term

Return the month of a time object as a number between 1 and 12. For your convenience, the terms r.January(), r.February() etc. are defined and map to the appropriate integer.

func (Term) Mul

func (t Term) Mul(args ...interface{}) Term

Mul multiplies two numbers.

func (Term) Ne

func (t Term) Ne(args ...interface{}) Term

Ne returns true if two values are not equal.

func (Term) Not

func (t Term) Not(args ...interface{}) Term

Not performs a logical not on a value.

func (Term) Nth

func (t Term) Nth(args ...interface{}) Term

Get the nth element of a sequence.

func (Term) Or

func (t Term) Or(args ...interface{}) Term

Or performs a logical or on two values.

func (Term) OrderBy

func (t Term) OrderBy(args ...interface{}) Term

Sort the sequence by document values of the given key(s). To specify the index to use for ordering us a last argument in the following form:

OrderByOpts{Index: "index-name"}

OrderBy defaults to ascending ordering. To explicitly specify the ordering, wrap the attribute with either Asc or Desc.

query.OrderBy("name")
query.OrderBy(Asc("name"))
query.OrderBy(Desc("name"))

func (Term) OuterJoin

func (t Term) OuterJoin(args ...interface{}) Term

Computes a left outer join by retaining each row in the left table even if no match was found in the right table.

func (Term) Pluck

func (t Term) Pluck(args ...interface{}) Term

Plucks out one or more attributes from either an object or a sequence of objects (projection).

func (Term) Prepend

func (t Term) Prepend(args ...interface{}) Term

Prepend a value to an array.

func (Term) Random

func (t Term) Random(args ...interface{}) Term

Generate a random number between the given bounds. If no arguments are given, the result will be a floating-point number in the range [0,1).

When passing a single argument, r.random(x), the result will be in the range [0,x), and when passing two arguments, r.random(x,y), the range is [x,y). If x and y are equal, an error will occur, unless generating a floating-point number, for which x will be returned.

Note: The last argument given will always be the 'open' side of the range, but when generating a floating-point number, the 'open' side may be less than the 'closed' side.

func (Term) Reduce

func (t Term) Reduce(args ...interface{}) Term

Produce a single value from a sequence through repeated application of a reduction function

func (Term) Replace

func (t Term) Replace(arg interface{}, optArgs ...ReplaceOpts) Term

Replace documents in a table. Accepts a JSON document or a RQL expression, and replaces the original document with the new one. The new document must have the same primary key as the original document. The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting. The optional argument return_changes will return the old and new values of the row you're modifying when set to true (only valid for single-row replacements). The optional argument non_atomic lets you permit non-atomic updates.

func (Term) Run

func (t Term) Run(s *Session, optArgs ...RunOpts) (*Cursor, error)

Run runs a query using the given connection.

rows, err := query.Run(sess)
if err != nil {
	// error
}
for rows.Next() {
	doc := MyDocumentType{}
	err := r.Scan(&doc)
	    // Do something with row
}

func (Term) RunWrite

func (t Term) RunWrite(s *Session, optArgs ...RunOpts) (WriteResponse, error)

RunWrite runs a query using the given connection but unlike Run automatically scans the result into a variable of type WriteResponse. This function should be used if you are running a write query (such as Insert, Update, TableCreate, etc...)

res, err := r.Db("database").Table("table").Insert(doc).RunWrite(sess, r.RunOpts{
	NoReply: true,
})

func (Term) Sample

func (t Term) Sample(args ...interface{}) Term

Select a given number of elements from a sequence with uniform random distribution. Selection is done without replacement.

func (Term) Seconds

func (t Term) Seconds(args ...interface{}) Term

Return the seconds in a time object as a number between 0 and 59.999 (double precision).

func (Term) SetDifference

func (t Term) SetDifference(args ...interface{}) Term

Remove the elements of one array from another and return them as a set (an array with distinct values).

func (Term) SetInsert

func (t Term) SetInsert(args ...interface{}) Term

Add a value to an array and return it as a set (an array with distinct values).

func (Term) SetIntersection

func (t Term) SetIntersection(args ...interface{}) Term

Intersect two arrays returning values that occur in both of them as a set (an array with distinct values).

func (Term) SetUnion

func (t Term) SetUnion(args ...interface{}) Term

Add a several values to an array and return it as a set (an array with distinct values).

func (Term) Skip

func (t Term) Skip(args ...interface{}) Term

Skip a number of elements from the head of the sequence.

func (Term) Slice

func (t Term) Slice(args ...interface{}) Term

TODO: Add optional arguments Trim the sequence to within the bounds provided.

func (Term) SpliceAt

func (t Term) SpliceAt(args ...interface{}) Term

Insert several values in to an array at a given index. Returns the modified array.

func (Term) Split

func (t Term) Split(args ...interface{}) Term

Splits a string into substrings. Splits on whitespace when called with no arguments. When called with a separator, splits on that separator. When called with a separator and a maximum number of splits, splits on that separator at most max_splits times. (Can be called with null as the separator if you want to split on whitespace while still specifying max_splits.)

Mimics the behavior of Python's string.split in edge cases, except for splitting on the empty string, which instead produces an array of single-character strings.

func (Term) String

func (t Term) String() string

String returns a string representation of the query tree

func (Term) Sub

func (t Term) Sub(args ...interface{}) Term

Sub subtracts two numbers.

func (Term) Sum

func (t Term) Sum(args ...interface{}) Term

Sums all the elements of a sequence. If called with a field name, sums all the values of that field in the sequence, skipping elements of the sequence that lack that field. If called with a function, calls that function on every element of the sequence and sums the results, skipping elements of the sequence where that function returns null or a non-existence error.

func (Term) Sync

func (t Term) Sync(args ...interface{}) Term

Sync ensures that writes on a given table are written to permanent storage. Queries that specify soft durability (Durability: "soft") do not give such guarantees, so sync can be used to ensure the state of these queries. A call to sync does not return until all previous writes to the table are persisted.

func (Term) Table

func (t Term) Table(name interface{}, optArgs ...TableOpts) Term

Select all documents in a table. This command can be chained with other commands to do further processing on the data.

Optional arguments (see http://www.rethinkdb.com/api/#js:selecting_data-table for more information): "use_outdated" (boolean - defaults to false)

func (Term) TableCreate

func (t Term) TableCreate(name interface{}, optArgs ...TableCreateOpts) Term

Create a table. A RethinkDB table is a collection of JSON documents.

If successful, the operation returns an object: {created: 1}. If a table with the same name already exists, the operation throws RqlRuntimeError.

Note: that you can only use alphanumeric characters and underscores for the table name.

r.Db("database").TableCreate("table", "durability", "soft").Run(sess)

func (Term) TableDrop

func (t Term) TableDrop(args ...interface{}) Term

Drop a table. The table and all its data will be deleted.

If successful, the operation returns an object: {dropped: 1}. If the specified table doesn't exist a RqlRuntimeError is thrown.

func (Term) TableList

func (t Term) TableList(args ...interface{}) Term

List all table names in a database.

func (Term) TimeOfDay

func (t Term) TimeOfDay(args ...interface{}) Term

Return the number of seconds elapsed since the beginning of the day stored in the time object.

func (Term) Timezone

func (t Term) Timezone(args ...interface{}) Term

Returns the timezone of the time object

func (Term) ToEpochTime

func (t Term) ToEpochTime(args ...interface{}) Term

Convert a time object to its epoch time.

func (Term) ToISO8601

func (t Term) ToISO8601(args ...interface{}) Term

Convert a time object to its iso 8601 format.

func (Term) TypeOf

func (t Term) TypeOf(args ...interface{}) Term

Gets the type of a value.

func (Term) Ungroup

func (t Term) Ungroup(args ...interface{}) Term

func (Term) Union

func (t Term) Union(args ...interface{}) Term

Concatenate two sequences.

func (Term) Upcase

func (t Term) Upcase(args ...interface{}) Term

Upcases a string.

func (Term) Update

func (t Term) Update(arg interface{}, optArgs ...UpdateOpts) Term

Update JSON documents in a table. Accepts a JSON document, a RQL expression, or a combination of the two. The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting. The optional argument return_changes will return the old and new values of the row you're modifying when set to true (only valid for single-row updates). The optional argument non_atomic lets you permit non-atomic updates.

func (Term) WithFields

func (t Term) WithFields(args ...interface{}) Term

Takes a sequence of objects and a list of fields. If any objects in the sequence don't have all of the specified fields, they're dropped from the sequence. The remaining objects have the specified fields plucked out. (This is identical to `HasFields` followed by `Pluck` on a sequence.)

func (Term) Without

func (t Term) Without(args ...interface{}) Term

The opposite of pluck; takes an object or a sequence of objects, and returns them with the specified paths removed.

func (Term) Year

func (t Term) Year(args ...interface{}) Term

Return the year of a time object.

func (Term) Zip

func (t Term) Zip(args ...interface{}) Term

Used to 'zip' up the result of a join by merging the 'right' fields into 'left' fields of each member of the sequence.

type UpdateOpts

type UpdateOpts struct {
	Durability    interface{} `gorethink:"durability,omitempty"`
	ReturnChanges interface{} `gorethink:"return_changes,omitempty"`
	NotAtomic     interface{} `gorethink:"non_atomic,omitempty"`
}

type WriteResponse

type WriteResponse struct {
	Errors        int
	Created       int
	Inserted      int
	Updated       int
	Unchanged     int
	Replaced      int
	Renamed       int
	Deleted       int
	GeneratedKeys []string    `gorethink:"generated_keys"`
	FirstError    string      `gorethink:"first_error"` // populated if Errors > 0
	NewValue      interface{} `gorethink:"new_val"`
	OldValue      interface{} `gorethink:"old_val"`
}

Directories

Path Synopsis
Package ql2 is a generated protocol buffer package.
Package ql2 is a generated protocol buffer package.

Jump to

Keyboard shortcuts

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