gorethink

package
v0.0.0-...-7429fd7 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2015 License: Apache-2.0, MIT Imports: 18 Imported by: 0

README

GoRethink - RethinkDB Driver for Go

wercker status

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

Current supported RethinkDB version: 1.11 | Documentation: GoDoc

Installation

go get -u github.com/dancannon/gorethink

If you do not have the goprotobuf runtime installed, it is required:

brew install mercurial # if you do not have mercurial installed
go get code.google.com/p/goprotobuf/{proto,protoc-gen-go}

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(map[string]interface{}{
        "address":  "localhost:28015",
        "database": "test",
        "authkey":  "14daak1cad13dj",
    })

    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(map[string]interface{}{
        "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}).RunRow(conn)

Map Expr Example

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

Get Example

r.Db("database").Table("table").Get("GUID").RunRow(conn)

Map Example (Func)

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

Map Example (Implicit)

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

Between (Optional Args) Example

r.Db("database").Table("table").Between(1, 10, r.BetweenOpts{
    Index: "num",
    RightBound: "closed",
}).Run(conn)
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 ResultRows type which can be used to view all rows returned.
  • RunRow returns a single row and can be used for queries such as Get where only a single row should be returned(or none).
  • RunWrite returns a ResultRow scanned into 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

Both ResultRows and ResultRow have the function Scan which is used to bind a row to a variable.

Example:

row, err := Table("tablename").Get(key).RunRow(conn)
if err != nil {
	// error
}
// Check if something was found
if !row.IsNil() {
	var response interface{}
	err := row.Scan(&response)
}

ResultRows also has the function Next which is used to iterate through a result set. If a partial sequence is returned by the server Next will automatically fetch the result of the sequence.

Example:

rows, err := Table("tablename").Run(conn)
if err != nil {
	// error
}
for rows.Next() {
    var row interface{}
    err := r.Scan(&row)

    // Do something with row
}

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 supported RethinkDB version: 1.11 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"
	r "github.com/dancannon/gorethink"
	"log"
	"os"
)

var session *r.Session
var url string

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

func main() {
	session, err := r.Connect(map[string]interface{}{
		"address": url,
	})
	if err != nil {
		log.Fatalln(err.Error())
	}

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

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

	fmt.Println(response)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPoolExhausted = errors.New("gorethink: connection pool exhausted")
View Source
var Row = newRqlTerm("Doc", p.Term_IMPLICIT_VAR, []interface{}{}, map[string]interface{}{})

Returns the currently visited document.

Functions

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 RqlTerm, opts map[string]interface{}) (*ResultRows, error)
	Close() error
}

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
	// contains filtered or unexported fields
}

connection is a connection to a rethinkdb database

func Dial

func Dial(s *Session) (*Connection, error)

Reconnect closes the previous connection and attempts to connect again.

func (*Connection) Close

func (c *Connection) Close() error

func (*Connection) SendQuery

func (c *Connection) SendQuery(s *Session, q *p.Query, t RqlTerm, opts map[string]interface{}) (*ResultRows, error)

type DeleteOpts

type DeleteOpts struct {
	Durability interface{} `gorethink:"durability,omitempty"`
	ReturnVals interface{} `gorethink:"return_vals,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 ISO8601Opts

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

type IndexCreateOpts

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

type InsertOpts

type InsertOpts struct {
	Durability interface{} `gorethink:"durability,omitempty"`
	ReturnVals interface{} `gorethink:"return_vals,omitempty"`
	CacheSize  interface{} `gorethink:"cache_size,omitempty"`
	Upsert     interface{} `gorethink:"upsert,omitempty"`
}

type OptArgs

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

type Pool

type Pool struct {
	Session *Session

	// Maximum number of idle connections in the pool.
	MaxIdle int

	// Maximum number of connections allocated by the pool at a given time.
	// When zero, there is no limit on the number of connections in the pool.
	MaxActive int

	// Close connections after remaining idle for this duration. If the value
	// is zero, then idle connections are not closed. Applications should set
	// the timeout to a value less than the server's timeout.
	IdleTimeout time.Duration
	// contains filtered or unexported fields
}

Pool maintains a pool of connections. The application calls the Get method to get a connection from the pool and the connection's Close method to return the connection's resources to the pool.

func (*Pool) ActiveCount

func (p *Pool) ActiveCount() int

ActiveCount returns the number of active connections in the pool.

func (*Pool) Close

func (p *Pool) Close() error

Close releases the resources used by the pool.

func (*Pool) Get

func (p *Pool) Get() Conn

Get gets a connection from the pool.

type ReplaceOpts

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

type ResultRow

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

ResultRow contains the result of a RunRow query

func (*ResultRow) IsNil

func (r *ResultRow) IsNil() bool

Tests if the result is nil. RethinkDB returns an nil value on Get queries when nothing is found.

func (*ResultRow) Profile

func (r *ResultRow) Profile() interface{}

func (*ResultRow) Scan

func (r *ResultRow) Scan(dest interface{}) error

Scan copies the result from the matched row into the value pointed at by dest. If more than one row is returned by the query then Scan returns the first and ignores the rest. If no row is found then Scan returns an error.

RethinkDB returns an nil value on Get queries when nothing is found, and Scan won't fail in this case.

type ResultRows

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

ResultRows contains the result of a query. Its cursor starts before the first row of the result set. Use Next to advance through the rows.

func (*ResultRows) Close

func (r *ResultRows) Close() error

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

func (*ResultRows) Count

func (r *ResultRows) Count() (count int, more bool)

Returns the number of rows currently in the buffer. If only a partial response was returned from the server then the more flag is set to true.

func (*ResultRows) Err

func (r *ResultRows) Err() error

Err returns the error, if any, that was encountered during iteration.

func (*ResultRows) IsNil

func (r *ResultRows) IsNil() bool

Tests if the current row is nil.

func (*ResultRows) Next

func (r *ResultRows) Next() bool

Next prepares the next row for reading. It returns true on success or false if there are no more rows. Every call to scan must be preceeded by a call to next. If all rows in the buffer have been read and a partial sequence was returned then Next will load more from the database

func (*ResultRows) Profile

func (r *ResultRows) Profile() interface{}

func (*ResultRows) Scan

func (r *ResultRows) Scan(dest interface{}) error

Scan copies the result in the current row into the value pointed at by dest.

If an argument is of type *interface{}, Scan copies the value provided by the database without conversion.

If the value is a struct then Scan traverses the result recursively and attempts to match the keys returned by the database to the name used by the structs field (either the struct field name or its key).

func (*ResultRows) ScanAll

func (r *ResultRows) ScanAll(dest interface{}) error

ScanAll copies all the rows in the result buffer into the value pointed at by dest.

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 RqlTerm

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

func Add

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

Add sums two numbers or concatenates two arrays.

func And

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

And performs a logical and on two values.

func April

func April() RqlTerm

func Asc

func Asc(arg interface{}) RqlTerm

func August

func August() RqlTerm

func Avg

func Avg(arg interface{}) RqlTerm

Compute the average value of the given attribute for the group.

func Branch

func Branch(test, trueBranch, falseBranch interface{}) RqlTerm

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 Count

func Count() RqlTerm

Count the total size of the group.

func Db

func Db(name interface{}) RqlTerm

Reference a database.

func DbCreate

func DbCreate(name interface{}) RqlTerm

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(name interface{}) RqlTerm

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() RqlTerm

List all database names in the system.

func December

func December() RqlTerm

func Desc

func Desc(arg interface{}) RqlTerm

func Div

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

Div divides two numbers.

func Do

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

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(epochtime interface{}) RqlTerm

Returns a time object based on seconds since epoch

func Eq

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

Eq returns true if two values are equal.

func Error

func Error(message interface{}) RqlTerm

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{}) RqlTerm

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 February

func February() RqlTerm

func Friday

func Friday() RqlTerm

func Ge

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

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

func Gt

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

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

func ISO8601

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

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 January

func January() RqlTerm

Months

func Js

func Js(js interface{}) RqlTerm

Create a JavaScript expression.

func Json

func Json(json interface{}) RqlTerm

Parse a JSON string on the server.

func July

func July() RqlTerm

func June

func June() RqlTerm

func Le

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

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

func Literal

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

func Lt

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

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

func March

func March() RqlTerm

func May

func May() RqlTerm

func Mod

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

Mod divides two numbers and returns the remainder.

func Monday

func Monday() RqlTerm

Days

func Mul

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

func Ne

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

Ne returns true if two values are not equal.

func Not

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

Not performs a logical not on a value.

func November

func November() RqlTerm

func Now

func Now() RqlTerm

Returns a time object representing the current time in UTC

func October

func October() RqlTerm

func Or

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

Or performs a logical or on two values.

func Saturday

func Saturday() RqlTerm

func September

func September() RqlTerm

func Sub

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

Sub subtracts two numbers.

func Sum

func Sum(arg interface{}) RqlTerm

Compute the sum of the given field in the group.

func Sunday

func Sunday() RqlTerm

func Table

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

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 Thursday

func Thursday() RqlTerm

func Time

func Time(year, month, day, hour, min, sec interface{}, tz string) RqlTerm

Create a time object for a specific time

func Tuesday

func Tuesday() RqlTerm

func Wednesday

func Wednesday() RqlTerm

func (RqlTerm) Add

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

Add sums two numbers or concatenates two arrays.

func (RqlTerm) And

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

And performs a logical and on two values.

func (RqlTerm) Append

func (t RqlTerm) Append(arg interface{}) RqlTerm

Append a value to an array.

func (RqlTerm) Between

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

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 (RqlTerm) ChangeAt

func (t RqlTerm) ChangeAt(index, value interface{}) RqlTerm

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

func (RqlTerm) CoerceTo

func (t RqlTerm) CoerceTo(typeName interface{}) RqlTerm

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 (RqlTerm) ConcatMap

func (t RqlTerm) ConcatMap(f interface{}) RqlTerm

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

func (RqlTerm) Contains

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

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 (RqlTerm) Count

func (t RqlTerm) Count() RqlTerm

Count the number of elements in the sequence.

func (RqlTerm) CountFiltered

func (t RqlTerm) CountFiltered(f interface{}) RqlTerm

Count the number of elements in the sequence. CountFiltered uses the argument passed to it to filter the results before counting.

func (RqlTerm) Date

func (t RqlTerm) Date() RqlTerm

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

func (RqlTerm) Day

func (t RqlTerm) Day() RqlTerm

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

func (RqlTerm) DayOfWeek

func (t RqlTerm) DayOfWeek() RqlTerm

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 (RqlTerm) DayOfYear

func (t RqlTerm) DayOfYear() RqlTerm

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

func (RqlTerm) Default

func (t RqlTerm) Default(value interface{}) RqlTerm

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 (RqlTerm) Delete

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

Delete one or more documents from a table. The optional argument return_vals 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 (RqlTerm) DeleteAt

func (t RqlTerm) DeleteAt(index interface{}) RqlTerm

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

func (RqlTerm) DeleteAtRange

func (t RqlTerm) DeleteAtRange(index, endIndex interface{}) RqlTerm

Remove the elements between the given range. Returns the modified array.

func (RqlTerm) Difference

func (t RqlTerm) Difference(arg interface{}) RqlTerm

Remove the elements of one array from another array.

func (RqlTerm) Distinct

func (t RqlTerm) Distinct() RqlTerm

Remove duplicate elements from the sequence.

func (RqlTerm) Div

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

Div divides two numbers.

func (RqlTerm) Do

func (t RqlTerm) Do(f interface{}) RqlTerm

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 (RqlTerm) During

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

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 (RqlTerm) Eq

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

Eq returns true if two values are equal.

func (RqlTerm) EqJoin

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

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 (RqlTerm) Exec

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

Exec runs the query but does not return the result (It also automatically sets the noreply option).

func (RqlTerm) Field

func (t RqlTerm) Field(field interface{}) RqlTerm

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 (RqlTerm) Filter

func (t RqlTerm) Filter(f interface{}) RqlTerm

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 (RqlTerm) ForEach

func (t RqlTerm) ForEach(f interface{}) RqlTerm

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

func (RqlTerm) Ge

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

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

func (RqlTerm) Get

func (t RqlTerm) Get(key interface{}) RqlTerm

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

Example
type Person struct {
	Id        string `gorethink:"id, omitempty"`
	FirstName string `gorethink:"first_name"`
	LastName  string `gorethink:"last_name"`
	Gender    string `gorethink:"gender"`
}

sess, err := r.Connect(map[string]interface{}{
	"address": url,
})

// Setup table
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)
r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess)

// Fetch the row from the database
row, err := r.Db("test").Table("table").Get("1").RunRow(sess)
if err != nil {
	log.Fatalf("Error finding person: %s", err)
}

if row.IsNil() {
	log.Fatalf("Person not found")
}

// Scan query result into the person variable
var person Person
err = row.Scan(&person)
if err != nil {
	log.Fatalf("Error scanning database result: %s", err)
}
fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
Output:

John Smith (M)

func (RqlTerm) GetAll

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

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

Example (Compound)
type Person struct {
	Id        string `gorethink:"id, omitempty"`
	FirstName string `gorethink:"first_name"`
	LastName  string `gorethink:"last_name"`
	Gender    string `gorethink:"gender"`
}

sess, err := r.Connect(map[string]interface{}{
	"address": url,
})

// Setup table
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)
r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess)
r.Db("test").Table("table").IndexCreateFunc("full_name", func(row r.RqlTerm) interface{} {
	return []interface{}{row.Field("first_name"), row.Field("last_name")}
}).Run(sess)

// Fetch the row from the database
row, err := r.Db("test").Table("table").GetAllByIndex("full_name", []interface{}{"John", "Smith"}).RunRow(sess)
if err != nil {
	log.Fatalf("Error finding person: %s", err)
}

if row.IsNil() {
	log.Fatalf("Person not found")
}

// Scan query result into the person variable
var person Person
row.Scan(&person)

fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
Output:

John Smith (M)

func (RqlTerm) GetAllByIndex

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

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

func (RqlTerm) GroupBy

func (t RqlTerm) GroupBy(collector interface{}, args ...interface{}) RqlTerm

Groups elements by the values of the given attributes and then applies the given reduction. Though similar to GroupedMapReduce, GroupBy takes a standardized object for specifying the reduction. Can be used with a number of predefined common reductions

func (RqlTerm) GroupedMapReduce

func (t RqlTerm) GroupedMapReduce(grouping, mapping, reduction, base interface{}) RqlTerm

Partition the sequence into groups based on the grouping function. The elements of each group are then mapped using the mapping function and reduced using the reduction function.

func (RqlTerm) Gt

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

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

func (RqlTerm) HasFields

func (t RqlTerm) HasFields(fields ...interface{}) RqlTerm

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 (RqlTerm) Hours

func (t RqlTerm) Hours() RqlTerm

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

func (RqlTerm) InTimezone

func (t RqlTerm) InTimezone(tz interface{}) RqlTerm

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 (RqlTerm) IndexCreate

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

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).
Example
sess, err := r.Connect(map[string]interface{}{
	"address": url,
})

// Setup database
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)

response, err := r.Db("test").Table("table").IndexCreate("name").RunWrite(sess)
if err != nil {
	log.Fatalf("Error creating index: %s", err)
}

fmt.Printf("%d index created", response.Created)
Output:

1 index created
Example (Compound)
sess, err := r.Connect(map[string]interface{}{
	"address": url,
})

// Setup database
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)

response, err := r.Db("test").Table("table").IndexCreateFunc("full_name", func(row r.RqlTerm) interface{} {
	return []interface{}{row.Field("first_name"), row.Field("last_name")}
}).RunWrite(sess)
if err != nil {
	log.Fatalf("Error creating index: %s", err)
}

fmt.Printf("%d index created", response.Created)
Output:

1 index created

func (RqlTerm) IndexCreateFunc

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

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 (RqlTerm) IndexDrop

func (t RqlTerm) IndexDrop(name interface{}) RqlTerm

Delete a previously created secondary index of this table.

func (RqlTerm) IndexList

func (t RqlTerm) IndexList() RqlTerm

List all the secondary indexes of this table.

func (RqlTerm) IndexStatus

func (t RqlTerm) IndexStatus(indexes ...interface{}) RqlTerm

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 (RqlTerm) IndexWait

func (t RqlTerm) IndexWait(indexes ...interface{}) RqlTerm

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 (RqlTerm) IndexesOf

func (t RqlTerm) IndexesOf(arg interface{}) RqlTerm

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

func (RqlTerm) Info

func (t RqlTerm) Info() RqlTerm

Get information about a RQL value.

func (RqlTerm) InnerJoin

func (t RqlTerm) InnerJoin(other, predicate interface{}) RqlTerm

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 (RqlTerm) Insert

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

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_vals, which will return the value of the row you're inserting (and the old value if you use upsert) 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 (RqlTerm) InsertAt

func (t RqlTerm) InsertAt(index, value interface{}) RqlTerm

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

func (RqlTerm) IsEmpty

func (t RqlTerm) IsEmpty() RqlTerm

Test if a sequence is empty.

func (RqlTerm) Keys

func (t RqlTerm) Keys() RqlTerm

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

func (RqlTerm) Le

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

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

func (RqlTerm) Limit

func (t RqlTerm) Limit(n interface{}) RqlTerm

End the sequence after the given number of elements.

func (RqlTerm) Lt

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

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

func (RqlTerm) Map

func (t RqlTerm) Map(f interface{}) RqlTerm

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

func (RqlTerm) Match

func (t RqlTerm) Match(regexp interface{}) RqlTerm

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 (RqlTerm) Merge

func (t RqlTerm) Merge(arg interface{}) RqlTerm

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 (RqlTerm) Minutes

func (t RqlTerm) Minutes() RqlTerm

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

func (RqlTerm) Mod

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

Mod divides two numbers and returns the remainder.

func (RqlTerm) Month

func (t RqlTerm) Month() RqlTerm

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 (RqlTerm) Mul

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

Mul multiplies two numbers.

func (RqlTerm) Ne

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

Ne returns true if two values are not equal.

func (RqlTerm) Not

func (t RqlTerm) Not() RqlTerm

Not performs a logical not on a value.

func (RqlTerm) Nth

func (t RqlTerm) Nth(n interface{}) RqlTerm

Get the nth element of a sequence.

func (RqlTerm) Or

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

Or performs a logical or on two values.

func (RqlTerm) OrderBy

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

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:

map[string]interface{}{"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 (RqlTerm) OuterJoin

func (t RqlTerm) OuterJoin(other, predicate interface{}) RqlTerm

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

func (RqlTerm) Pluck

func (t RqlTerm) Pluck(fields ...interface{}) RqlTerm

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

func (RqlTerm) Prepend

func (t RqlTerm) Prepend(arg interface{}) RqlTerm

Prepend a value to an array.

func (RqlTerm) Reduce

func (t RqlTerm) Reduce(f, base interface{}) RqlTerm

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

The reduce function gets invoked repeatedly not only for the input values but also for results of previous reduce invocations. The type and format of the object that is passed in to reduce must be the same with the one returned from reduce.

func (RqlTerm) Replace

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

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_vals 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 (RqlTerm) Run

func (t RqlTerm) Run(s *Session, optArgs ...RunOpts) (*ResultRows, 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 (RqlTerm) RunRow

func (t RqlTerm) RunRow(s *Session, optArgs ...RunOpts) (*ResultRow, error)

Run runs a query using the given connection but unlike Run returns ResultRow. This function should be used if your query only returns a single row.

row, err := query.RunRow(sess, r.RunOpts{
	UseOutdated: true,
})
if err != nil {
	// error
}
if row.IsNil() {
	// nothing was found
}
err = row.Scan(&doc)

func (RqlTerm) RunWrite

func (t RqlTerm) 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...)

Optional arguments : "db", "use_outdated" (defaults to false), "noreply" (defaults to false) and "time_format".

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

func (RqlTerm) Sample

func (t RqlTerm) Sample(n interface{}) RqlTerm

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

func (RqlTerm) Seconds

func (t RqlTerm) Seconds() RqlTerm

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

func (RqlTerm) SetDifference

func (t RqlTerm) SetDifference(arg interface{}) RqlTerm

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

func (RqlTerm) SetInsert

func (t RqlTerm) SetInsert(arg interface{}) RqlTerm

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

func (RqlTerm) SetIntersection

func (t RqlTerm) SetIntersection(arg interface{}) RqlTerm

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

func (RqlTerm) SetUnion

func (t RqlTerm) SetUnion(arg interface{}) RqlTerm

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

func (RqlTerm) Skip

func (t RqlTerm) Skip(n interface{}) RqlTerm

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

func (RqlTerm) Slice

func (t RqlTerm) Slice(lower, upper interface{}) RqlTerm

Trim the sequence to within the bounds provided.

func (RqlTerm) SpliceAt

func (t RqlTerm) SpliceAt(index, value interface{}) RqlTerm

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

func (RqlTerm) String

func (t RqlTerm) String() string

compose returns a string representation of the query tree

func (RqlTerm) Sub

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

Sub subtracts two numbers.

func (RqlTerm) Sync

func (t RqlTerm) Sync() RqlTerm

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 (RqlTerm) Table

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

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 (RqlTerm) TableCreate

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

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)

Example
sess, err := r.Connect(map[string]interface{}{
	"address": url,
})

// Setup database
r.Db("test").TableDrop("table").Run(sess)

response, err := r.Db("test").TableCreate("table").RunWrite(sess)
if err != nil {
	log.Fatalf("Error creating table: %s", err)
}

fmt.Printf("%d table created", response.Created)
Output:

1 table created

func (RqlTerm) TableDrop

func (t RqlTerm) TableDrop(name interface{}) RqlTerm

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 (RqlTerm) TableList

func (t RqlTerm) TableList() RqlTerm

List all table names in a database.

func (RqlTerm) TimeOfDay

func (t RqlTerm) TimeOfDay() RqlTerm

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

func (RqlTerm) Timezone

func (t RqlTerm) Timezone() RqlTerm

Returns the timezone of the time object

func (RqlTerm) ToEpochTime

func (t RqlTerm) ToEpochTime() RqlTerm

Convert a time object to its epoch time.

func (RqlTerm) ToISO8601

func (t RqlTerm) ToISO8601() RqlTerm

Convert a time object to its iso 8601 format.

func (RqlTerm) TypeOf

func (t RqlTerm) TypeOf() RqlTerm

Gets the type of a value.

func (RqlTerm) Union

func (t RqlTerm) Union(arg interface{}) RqlTerm

Concatenate two sequences.

func (RqlTerm) Update

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

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_vals 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 (RqlTerm) WithFields

func (t RqlTerm) WithFields(selectors ...interface{}) RqlTerm

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 (RqlTerm) Without

func (t RqlTerm) Without(fields ...interface{}) RqlTerm

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

func (RqlTerm) Year

func (t RqlTerm) Year() RqlTerm

Return the year of a time object.

func (RqlTerm) Zip

func (t RqlTerm) Zip() RqlTerm

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

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"`
	TimeFormat  interface{} `gorethink:"time_format,omitempty"`
}

type Session

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

func Connect

func Connect(args map[string]interface{}) (*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(map[string]interface{}{
	"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()

Close closes the session

func (*Session) Reconnect

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

Reconnect closes and re-opens a session.

func (*Session) SetMaxIdleConns

func (s *Session) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection pool.

If MaxOpenConns is greater than 0 but less than the new MaxIdleConns then the new MaxIdleConns will be reduced to match the MaxOpenConns limit

If n <= 0, no idle connections are retained.

func (*Session) SetMaxOpenConns

func (s *Session) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database.

If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit

If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).

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 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 string `gorethink:"use_outdated,omitempty"`
}

type UpdateOpts

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

type WriteResponse

type WriteResponse struct {
	Errors        int
	Created       int
	Inserted      int
	Updated       int
	Unchanged     int
	Replaced      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

Jump to

Keyboard shortcuts

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