Documentation ¶
Overview ¶
Package gorethink implements a Go driver for RethinkDB
Current version: v3.0.2 (RethinkDB v2.3) For more in depth information on how to use RethinkDB check out the API docs at http://rethinkdb.com/api
Example ¶
session, err := r.Connect(r.ConnectOpts{ Address: url, }) if err != nil { log.Fatalln(err) } res, err := r.Expr("Hello World").Run(session) if err != nil { log.Fatalln(err) } var response string err = res.One(&response) if err != nil { log.Fatalln(err) } fmt.Println(response)
Output: Hello World
Index ¶
- Constants
- Variables
- func IsConflictErr(err error) bool
- func IsTypeErr(err error) bool
- func SetTags(tags ...string)
- func SetVerbose(verbose bool)
- type BetweenOpts
- type ChangeResponse
- type ChangesOpts
- type CircleOpts
- type CloseOpts
- type Cluster
- func (c *Cluster) AddSeeds(hosts []Host)
- func (c *Cluster) Close(optArgs ...CloseOpts) error
- func (c *Cluster) Exec(ctx context.Context, q Query) (err error)
- func (c *Cluster) GetNextNode() (*Node, hostpool.HostPoolResponse, error)
- func (c *Cluster) GetNodes() []*Node
- func (c *Cluster) IsConnected() bool
- func (c *Cluster) Query(ctx context.Context, q Query) (cursor *Cursor, err error)
- func (c *Cluster) Server() (response ServerResponse, err error)
- func (c *Cluster) SetInitialPoolCap(n int)
- func (c *Cluster) SetMaxIdleConns(n int)
- func (c *Cluster) SetMaxOpenConns(n int)
- type ConnectOpts
- type Connection
- type Cursor
- func (c *Cursor) All(result interface{}) error
- func (c *Cursor) Close() error
- func (c *Cursor) Err() error
- func (c *Cursor) Interface() (interface{}, error)
- func (c *Cursor) IsNil() bool
- func (c *Cursor) Listen(channel interface{})
- func (c *Cursor) Next(dest interface{}) bool
- func (c *Cursor) NextResponse() ([]byte, bool)
- func (c *Cursor) One(result interface{}) error
- func (c *Cursor) Peek(dest interface{}) (bool, error)
- func (c *Cursor) Profile() interface{}
- func (c *Cursor) Skip()
- func (c *Cursor) Type() string
- type DeleteOpts
- type DistanceOpts
- type DistinctOpts
- type DuringOpts
- type EqJoinOpts
- type ExecOpts
- type FilterOpts
- type FoldOpts
- type GetAllOpts
- type GetIntersectingOpts
- type GetNearestOpts
- type GroupOpts
- type HTTPOpts
- type HandshakeVersion
- type Host
- type ISO8601Opts
- type IndexCreateOpts
- type IndexRenameOpts
- type InsertOpts
- type JSOpts
- type MaxOpts
- type MinOpts
- type Mock
- func (m *Mock) AssertExecuted(t testingT, expectedQuery *MockQuery) bool
- func (m *Mock) AssertExpectations(t testingT) bool
- func (m *Mock) AssertNotExecuted(t testingT, expectedQuery *MockQuery) bool
- func (m *Mock) AssertNumberOfExecutions(t testingT, expectedQuery *MockQuery, expectedExecutions int) bool
- func (m *Mock) Exec(ctx context.Context, q Query) error
- func (m *Mock) IsConnected() bool
- func (m *Mock) On(t Term, opts ...map[string]interface{}) *MockQuery
- func (m *Mock) Query(ctx context.Context, q Query) (*Cursor, error)
- type MockQuery
- func (mq *MockQuery) After(d time.Duration) *MockQuery
- func (mq *MockQuery) On(t Term) *MockQuery
- func (mq *MockQuery) Once() *MockQuery
- func (mq *MockQuery) Return(response interface{}, err error) *MockQuery
- func (mq *MockQuery) Times(i int) *MockQuery
- func (mq *MockQuery) Twice() *MockQuery
- func (mq *MockQuery) WaitUntil(w <-chan time.Time) *MockQuery
- type Node
- func (n *Node) Close(optArgs ...CloseOpts) error
- func (n *Node) Closed() bool
- func (n *Node) Exec(ctx context.Context, q Query) (err error)
- func (n *Node) NoReplyWait() error
- func (n *Node) Query(ctx context.Context, q Query) (cursor *Cursor, err error)
- func (n *Node) Server() (ServerResponse, error)
- func (n *Node) SetInitialPoolCap(idleConns int)
- func (n *Node) SetMaxIdleConns(idleConns int)
- func (n *Node) SetMaxOpenConns(openConns int)
- type OptArgs
- type OrderByOpts
- type Pool
- func (p *Pool) Close() error
- func (p *Pool) Exec(ctx context.Context, q Query) error
- func (p *Pool) Ping() error
- func (p *Pool) Query(ctx context.Context, q Query) (*Cursor, error)
- func (p *Pool) Server() (ServerResponse, error)
- func (p *Pool) SetInitialPoolCap(n int)deprecated
- func (p *Pool) SetMaxIdleConns(n int)deprecated
- func (p *Pool) SetMaxOpenConns(n int)deprecated
- type Query
- type QueryExecutor
- type RQLAuthError
- type RQLAvailabilityError
- type RQLClientError
- type RQLCompileError
- type RQLConnectionError
- type RQLDriverCompileError
- type RQLDriverError
- type RQLInternalError
- type RQLNonExistenceError
- type RQLOpFailedError
- type RQLOpIndeterminateError
- type RQLQueryLogicError
- type RQLResourceLimitError
- type RQLRuntimeError
- type RQLServerCompileError
- type RQLTimeoutError
- type RQLUserError
- type RandomOpts
- type ReconfigureOpts
- type ReplaceOpts
- type Response
- type RunOpts
- type ServerResponse
- type Session
- func (s *Session) Close(optArgs ...CloseOpts) error
- func (s *Session) Database() string
- func (s *Session) Exec(ctx context.Context, q Query) error
- func (s *Session) IsConnected() bool
- func (s *Session) NoReplyWait() error
- func (s *Session) Query(ctx context.Context, q Query) (*Cursor, error)
- func (s *Session) Reconnect(optArgs ...CloseOpts) error
- func (s *Session) Server() (ServerResponse, error)
- func (s *Session) SetHosts(hosts []Host)
- func (s *Session) SetInitialPoolCap(n int)
- func (s *Session) SetMaxIdleConns(n int)
- func (s *Session) SetMaxOpenConns(n int)
- func (s *Session) Use(database string)
- type SliceOpts
- type TableCreateOpts
- type TableOpts
- type Term
- func Add(args ...interface{}) Term
- func And(args ...interface{}) Term
- func Args(args ...interface{}) Term
- func Asc(args ...interface{}) Term
- func Avg(args ...interface{}) Term
- func Binary(data interface{}) Term
- func Branch(args ...interface{}) Term
- func Ceil(args ...interface{}) Term
- func Circle(point, radius interface{}, optArgs ...CircleOpts) Term
- func Contains(args ...interface{}) Term
- func Count(args ...interface{}) Term
- func DB(args ...interface{}) Term
- func DBCreate(args ...interface{}) Term
- func DBDrop(args ...interface{}) Term
- func DBList(args ...interface{}) Term
- func Desc(args ...interface{}) Term
- func Distance(point1, point2 interface{}, optArgs ...DistanceOpts) Term
- func Distinct(arg interface{}, optArgs ...DistinctOpts) Term
- func Div(args ...interface{}) Term
- func Do(args ...interface{}) Term
- func EpochTime(args ...interface{}) Term
- func Eq(args ...interface{}) Term
- func Error(args ...interface{}) Term
- func Expr(val interface{}) Term
- func Floor(args ...interface{}) Term
- func Ge(args ...interface{}) Term
- func GeoJSON(args ...interface{}) Term
- func Group(fieldOrFunctions ...interface{}) Term
- func GroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
- func Gt(args ...interface{}) Term
- func HTTP(url interface{}, optArgs ...HTTPOpts) Term
- func ISO8601(date interface{}, optArgs ...ISO8601Opts) Term
- func JS(jssrc interface{}, optArgs ...JSOpts) Term
- func JSON(args ...interface{}) Term
- func Le(args ...interface{}) Term
- func Line(args ...interface{}) Term
- func Literal(args ...interface{}) Term
- func Lt(args ...interface{}) Term
- func Map(args ...interface{}) Term
- func Max(args ...interface{}) Term
- func MaxIndex(index interface{}, args ...interface{}) Term
- func Min(args ...interface{}) Term
- func MinIndex(index interface{}, args ...interface{}) Term
- func MockAnything() Term
- func Mod(args ...interface{}) Term
- func Mul(args ...interface{}) Term
- func MultiGroup(fieldOrFunctions ...interface{}) Term
- func MultiGroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
- func Ne(args ...interface{}) Term
- func Not(args ...interface{}) Term
- func Now(args ...interface{}) Term
- func Object(args ...interface{}) Term
- func Or(args ...interface{}) Term
- func Point(lon, lat interface{}) Term
- func Polygon(args ...interface{}) Term
- func Random(args ...interface{}) Term
- func Range(args ...interface{}) Term
- func RawQuery(q []byte) Term
- func Round(args ...interface{}) Term
- func Sub(args ...interface{}) Term
- func Sum(args ...interface{}) Term
- func Table(name interface{}, optArgs ...TableOpts) Term
- func TableCreate(name interface{}, optArgs ...TableCreateOpts) Term
- func TableDrop(args ...interface{}) Term
- func TableList(args ...interface{}) Term
- func Time(args ...interface{}) Term
- func TypeOf(args ...interface{}) Term
- func UUID(args ...interface{}) Term
- func Union(args ...interface{}) Term
- func UnionWithOpts(optArgs UnionOpts, args ...interface{}) Term
- func Wait(optArgs ...WaitOpts) Termdeprecated
- func (t Term) Add(args ...interface{}) Term
- func (t Term) And(args ...interface{}) Term
- func (t Term) Append(args ...interface{}) Term
- func (t Term) AtIndex(args ...interface{}) Term
- func (t Term) Avg(args ...interface{}) Term
- func (t Term) Between(lowerKey, upperKey interface{}, optArgs ...BetweenOpts) Term
- func (t Term) Branch(args ...interface{}) Term
- func (t Term) Build() (interface{}, error)
- func (t Term) Ceil(args ...interface{}) Term
- func (t Term) ChangeAt(args ...interface{}) Term
- func (t Term) Changes(optArgs ...ChangesOpts) Term
- func (t Term) CoerceTo(args ...interface{}) Term
- func (t Term) ConcatMap(args ...interface{}) Term
- func (t Term) Config() Term
- func (t Term) Contains(args ...interface{}) Term
- func (t Term) Count(args ...interface{}) Term
- func (t Term) Date(args ...interface{}) Term
- func (t Term) Day(args ...interface{}) Term
- func (t Term) DayOfWeek(args ...interface{}) Term
- func (t Term) DayOfYear(args ...interface{}) Term
- func (t Term) Default(args ...interface{}) Term
- func (t Term) Delete(optArgs ...DeleteOpts) Term
- func (t Term) DeleteAt(args ...interface{}) Term
- func (t Term) Difference(args ...interface{}) Term
- func (t Term) Distance(point interface{}, optArgs ...DistanceOpts) Term
- func (t Term) Distinct(optArgs ...DistinctOpts) Term
- func (t Term) Div(args ...interface{}) Term
- func (t Term) Do(args ...interface{}) Term
- func (t Term) Downcase(args ...interface{}) Term
- func (t Term) During(startTime, endTime interface{}, optArgs ...DuringOpts) Term
- func (t Term) Eq(args ...interface{}) Term
- func (t Term) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) Term
- func (t Term) Exec(s QueryExecutor, optArgs ...ExecOpts) error
- func (t Term) Field(args ...interface{}) Term
- func (t Term) Fill() Term
- func (t Term) Filter(f interface{}, optArgs ...FilterOpts) Term
- func (t Term) Floor(args ...interface{}) Term
- func (t Term) Fold(base, fn interface{}, optArgs ...FoldOpts) Term
- func (t Term) ForEach(args ...interface{}) Term
- func (t Term) Ge(args ...interface{}) Term
- func (t Term) Get(args ...interface{}) Term
- func (t Term) GetAll(keys ...interface{}) Term
- func (t Term) GetAllByIndex(index interface{}, keys ...interface{}) Term
- func (t Term) GetIntersecting(args interface{}, optArgs ...GetIntersectingOpts) Term
- func (t Term) GetNearest(point interface{}, optArgs ...GetNearestOpts) Term
- func (t Term) Grant(args ...interface{}) Term
- func (t Term) Group(fieldOrFunctions ...interface{}) Term
- func (t Term) GroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
- func (t Term) Gt(args ...interface{}) Term
- func (t Term) HasFields(args ...interface{}) Term
- func (t Term) Hours(args ...interface{}) Term
- func (t Term) InTimezone(args ...interface{}) Term
- func (t Term) Includes(args ...interface{}) Term
- func (t Term) IndexCreate(name interface{}, optArgs ...IndexCreateOpts) Term
- func (t Term) IndexCreateFunc(name, indexFunction interface{}, optArgs ...IndexCreateOpts) Term
- func (t Term) IndexDrop(args ...interface{}) Term
- func (t Term) IndexList(args ...interface{}) Term
- func (t Term) IndexRename(oldName, newName interface{}, optArgs ...IndexRenameOpts) Term
- func (t Term) IndexStatus(args ...interface{}) Term
- func (t Term) IndexWait(args ...interface{}) Term
- func (t Term) Info(args ...interface{}) Term
- func (t Term) InnerJoin(args ...interface{}) Term
- func (t Term) Insert(arg interface{}, optArgs ...InsertOpts) Term
- func (t Term) InsertAt(args ...interface{}) Term
- func (t Term) Intersects(args ...interface{}) Term
- func (t Term) IsEmpty(args ...interface{}) Term
- func (t Term) Keys(args ...interface{}) Term
- func (t Term) Le(args ...interface{}) Term
- func (t Term) Limit(args ...interface{}) Term
- func (t Term) Lt(args ...interface{}) Term
- func (t Term) Map(args ...interface{}) Term
- func (t Term) Match(args ...interface{}) Term
- func (t Term) Max(args ...interface{}) Term
- func (t Term) MaxIndex(index interface{}, args ...interface{}) Term
- func (t Term) Merge(args ...interface{}) Term
- func (t Term) Min(args ...interface{}) Term
- func (t Term) MinIndex(index interface{}, args ...interface{}) Term
- func (t Term) Minutes(args ...interface{}) Term
- func (t Term) MockAnything() Term
- func (t Term) Mod(args ...interface{}) Term
- func (t Term) Month(args ...interface{}) Term
- func (t Term) Mul(args ...interface{}) Term
- func (t Term) MultiGroup(fieldOrFunctions ...interface{}) Term
- func (t Term) MultiGroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
- func (t Term) Ne(args ...interface{}) Term
- func (t Term) Not(args ...interface{}) Term
- func (t Term) Nth(args ...interface{}) Term
- func (t Term) OffsetsOf(args ...interface{}) Term
- func (t Term) OptArgs(args interface{}) Term
- func (t Term) Or(args ...interface{}) Term
- func (t Term) OrderBy(args ...interface{}) Term
- func (t Term) OuterJoin(args ...interface{}) Term
- func (t Term) Pluck(args ...interface{}) Term
- func (t Term) PolygonSub(args ...interface{}) Term
- func (t Term) Prepend(args ...interface{}) Term
- func (t Term) ReadAll(dest interface{}, s QueryExecutor, optArgs ...RunOpts) error
- func (t Term) ReadOne(dest interface{}, s QueryExecutor, optArgs ...RunOpts) error
- func (t Term) Rebalance() Term
- func (t Term) Reconfigure(optArgs ...ReconfigureOpts) Term
- func (t Term) Reduce(args ...interface{}) Term
- func (t Term) Replace(arg interface{}, optArgs ...ReplaceOpts) Term
- func (t Term) Round(args ...interface{}) Term
- func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error)
- func (t Term) RunWrite(s QueryExecutor, optArgs ...RunOpts) (WriteResponse, error)
- func (t Term) Sample(args ...interface{}) Term
- func (t Term) Seconds(args ...interface{}) Term
- func (t Term) SetDifference(args ...interface{}) Term
- func (t Term) SetInsert(args ...interface{}) Term
- func (t Term) SetIntersection(args ...interface{}) Term
- func (t Term) SetUnion(args ...interface{}) Term
- func (t Term) Skip(args ...interface{}) Term
- func (t Term) Slice(args ...interface{}) Term
- func (t Term) SpliceAt(args ...interface{}) Term
- func (t Term) Split(args ...interface{}) Term
- func (t Term) Status() Term
- func (t Term) String() string
- func (t Term) Sub(args ...interface{}) Term
- func (t Term) Sum(args ...interface{}) Term
- func (t Term) Sync(args ...interface{}) Term
- func (t Term) Table(name interface{}, optArgs ...TableOpts) Term
- func (t Term) TableCreate(name interface{}, optArgs ...TableCreateOpts) Term
- func (t Term) TableDrop(args ...interface{}) Term
- func (t Term) TableList(args ...interface{}) Term
- func (t Term) TimeOfDay(args ...interface{}) Term
- func (t Term) Timezone(args ...interface{}) Term
- func (t Term) ToEpochTime(args ...interface{}) Term
- func (t Term) ToGeoJSON(args ...interface{}) Term
- func (t Term) ToISO8601(args ...interface{}) Term
- func (t Term) ToJSON() Term
- func (t Term) TypeOf(args ...interface{}) Term
- func (t Term) Ungroup(args ...interface{}) Term
- func (t Term) Union(args ...interface{}) Term
- func (t Term) UnionWithOpts(optArgs UnionOpts, args ...interface{}) Term
- func (t Term) Upcase(args ...interface{}) Term
- func (t Term) Update(arg interface{}, optArgs ...UpdateOpts) Term
- func (t Term) Values(args ...interface{}) Term
- func (t Term) Wait(optArgs ...WaitOpts) Term
- func (t Term) WithFields(args ...interface{}) Term
- func (t Term) Without(args ...interface{}) Term
- func (t Term) Year(args ...interface{}) Term
- func (t Term) Zip(args ...interface{}) Term
- type UnionOpts
- type UpdateOpts
- type WaitOpts
- type WriteResponse
Examples ¶
- Package
- Branch
- Connect
- Connect (Cluster)
- Connect (ConnectionPool)
- Cursor.Peek
- DBCreate
- DBDrop
- Error
- Expr (Int)
- Expr (Map)
- Expr (Slice)
- Expr (Struct)
- Expr (StructTags)
- Map (MultipleSequences)
- RawQuery
- Term.Default
- Term.Delete
- Term.Delete (Many)
- Term.Field
- Term.Filter
- Term.Filter (Function)
- Term.Filter (Row)
- Term.Fold
- Term.Get
- Term.Get (Merge)
- Term.GetAll
- Term.GetAll (Multiple)
- Term.GetAll (OptArgs)
- Term.GetAllByIndex
- Term.Group
- Term.GroupByIndex
- Term.IndexCreate
- Term.IndexCreate (Compound)
- Term.Insert (GeneratedKey)
- Term.Insert (Map)
- Term.Insert (Multiple)
- Term.Insert (Struct)
- Term.Insert (Upsert)
- Term.Map
- Term.MultiGroup
- Term.OrderBy (Compound)
- Term.OrderBy (Index)
- Term.OrderBy (IndexDesc)
- Term.OrderBy (Multiple)
- Term.OrderBy (MultipleWithIndex)
- Term.Reduce
- Term.TableCreate
- Term.Ungroup
- Term.Update
- Term.Update (All)
- Term.Update (Increment)
- Term.Update (Nested)
- Term.Update (SoftDurability)
Constants ¶
const ( SystemDatabase = "rethinkdb" TableConfigSystemTable = "table_config" ServerConfigSystemTable = "server_config" DBConfigSystemTable = "db_config" ClusterConfigSystemTable = "cluster_config" TableStatusSystemTable = "table_status" ServerStatusSystemTable = "server_status" CurrentIssuesSystemTable = "current_issues" UsersSystemTable = "users" PermissionsSystemTable = "permissions" JobsSystemTable = "jobs" StatsSystemTable = "stats" LogsSystemTable = "logs" )
Variables ¶
var ( // ErrNoHosts is returned when no hosts to the Connect method. ErrNoHosts = errors.New("no hosts provided") // ErrNoConnectionsStarted is returned when the driver couldn't to any of // the provided hosts. ErrNoConnectionsStarted = errors.New("no connections were made when creating the session") // ErrInvalidNode is returned when attempting to connect to a node which // returns an invalid response. ErrInvalidNode = errors.New("invalid node") // ErrNoConnections is returned when there are no active connections in the // clusters connection pool. ErrNoConnections = errors.New("gorethink: no connections were available") // ErrConnectionClosed is returned when trying to send a query with a closed // connection. ErrConnectionClosed = errors.New("gorethink: the connection is closed") // ErrQueryTimeout is returned when query context deadline exceeded. ErrQueryTimeout = errors.New("gorethink: query timeout") )
var ( // MinVal represents the smallest possible value RethinkDB can store MinVal = constructRootTerm("MinVal", p.Term_MINVAL, []interface{}{}, map[string]interface{}{}) // MaxVal represents the largest possible value RethinkDB can store MaxVal = constructRootTerm("MaxVal", p.Term_MAXVAL, []interface{}{}, map[string]interface{}{}) )
var ( // Monday is a constant representing the day of the week Monday Monday = constructRootTerm("Monday", p.Term_MONDAY, []interface{}{}, map[string]interface{}{}) // Tuesday is a constant representing the day of the week Tuesday Tuesday = constructRootTerm("Tuesday", p.Term_TUESDAY, []interface{}{}, map[string]interface{}{}) // Wednesday is a constant representing the day of the week Wednesday Wednesday = constructRootTerm("Wednesday", p.Term_WEDNESDAY, []interface{}{}, map[string]interface{}{}) // Thursday is a constant representing the day of the week Thursday Thursday = constructRootTerm("Thursday", p.Term_THURSDAY, []interface{}{}, map[string]interface{}{}) // Friday is a constant representing the day of the week Friday Friday = constructRootTerm("Friday", p.Term_FRIDAY, []interface{}{}, map[string]interface{}{}) // Saturday is a constant representing the day of the week Saturday Saturday = constructRootTerm("Saturday", p.Term_SATURDAY, []interface{}{}, map[string]interface{}{}) // Sunday is a constant representing the day of the week Sunday Sunday = constructRootTerm("Sunday", p.Term_SUNDAY, []interface{}{}, map[string]interface{}{}) // January is a constant representing the month January January = constructRootTerm("January", p.Term_JANUARY, []interface{}{}, map[string]interface{}{}) // February is a constant representing the month February February = constructRootTerm("February", p.Term_FEBRUARY, []interface{}{}, map[string]interface{}{}) // March is a constant representing the month March March = constructRootTerm("March", p.Term_MARCH, []interface{}{}, map[string]interface{}{}) // April is a constant representing the month April April = constructRootTerm("April", p.Term_APRIL, []interface{}{}, map[string]interface{}{}) // May is a constant representing the month May May = constructRootTerm("May", p.Term_MAY, []interface{}{}, map[string]interface{}{}) // June is a constant representing the month June June = constructRootTerm("June", p.Term_JUNE, []interface{}{}, map[string]interface{}{}) // July is a constant representing the month July July = constructRootTerm("July", p.Term_JULY, []interface{}{}, map[string]interface{}{}) // August is a constant representing the month August August = constructRootTerm("August", p.Term_AUGUST, []interface{}{}, map[string]interface{}{}) // September is a constant representing the month September September = constructRootTerm("September", p.Term_SEPTEMBER, []interface{}{}, map[string]interface{}{}) // October is a constant representing the month October October = constructRootTerm("October", p.Term_OCTOBER, []interface{}{}, map[string]interface{}{}) // November is a constant representing the month November November = constructRootTerm("November", p.Term_NOVEMBER, []interface{}{}, map[string]interface{}{}) // December is a constant representing the month December December = constructRootTerm("December", p.Term_DECEMBER, []interface{}{}, map[string]interface{}{}) )
var ErrEmptyResult = errors.New("The result does not contain any more rows")
Error constants
var (
Log *logrus.Logger
)
var Row = constructRootTerm("Doc", p.Term_IMPLICIT_VAR, []interface{}{}, map[string]interface{}{})
Row returns the currently visited document. Note that Row does not work within subqueries to access nested documents; you should use anonymous functions to access those documents instead. Also note that unlike in other drivers to access a rows fields you should call Field. For example:
r.row("fieldname") should instead be r.Row.Field("fieldname")
Functions ¶
func IsConflictErr ¶ added in v1.4.0
IsConflictErr returns true if the error is non-nil and the query failed due to a duplicate primary key.
func IsTypeErr ¶ added in v1.4.0
IsTypeErr returns true if the error is non-nil and the query failed due to a type error.
func SetTags ¶ added in v1.4.0
func SetTags(tags ...string)
SetTags allows you to override the tags used when decoding or encoding structs. The driver will check for the tags in the same order that they were passed into this function. If no parameters are passed then the driver will default to checking for the gorethink tag (the gorethink tag is always included)
func SetVerbose ¶ added in v0.7.0
func SetVerbose(verbose bool)
SetVerbose allows the driver logging level to be set. If true is passed then the log level is set to Debug otherwise it defaults to Info.
Types ¶
type BetweenOpts ¶
type BetweenOpts struct { Index interface{} `gorethink:"index,omitempty"` LeftBound interface{} `gorethink:"left_bound,omitempty"` RightBound interface{} `gorethink:"right_bound,omitempty"` }
BetweenOpts contains the optional arguments for the Between term
type ChangeResponse ¶ added in v1.0.0
type ChangeResponse struct { NewValue interface{} `gorethink:"new_val,omitempty"` OldValue interface{} `gorethink:"old_val,omitempty"` State string `gorethink:"state,omitempty"` Error string `gorethink:"error,omitempty"` }
ChangeResponse is a helper type used when dealing with changefeeds. The type contains both the value before the query and the new value.
type ChangesOpts ¶ added in v0.6.0
type ChangesOpts struct { Squash interface{} `gorethink:"squash,omitempty"` IncludeInitial interface{} `gorethink:"include_initial,omitempty"` IncludeStates interface{} `gorethink:"include_states,omitempty"` IncludeOffsets interface{} `gorethink:"include_offsets,omitempty"` IncludeTypes interface{} `gorethink:"include_types,omitempty"` ChangefeedQueueSize interface{} `gorethink:"changefeed_queue_size,omitempty"` }
ChangesOpts contains the optional arguments for the Changes term
type CircleOpts ¶ added in v0.5.0
type CircleOpts struct { NumVertices interface{} `gorethink:"num_vertices,omitempty"` GeoSystem interface{} `gorethink:"geo_system,omitempty"` Unit interface{} `gorethink:"unit,omitempty"` Fill interface{} `gorethink:"fill,omitempty"` }
CircleOpts contains the optional arguments for the Circle term.
type CloseOpts ¶
type CloseOpts struct {
NoReplyWait bool `gorethink:"noreplyWait,omitempty"`
}
CloseOpts allows calls to the Close function to be configured.
type Cluster ¶ added in v0.7.0
type Cluster struct {
// contains filtered or unexported fields
}
A Cluster represents a connection to a RethinkDB cluster, a cluster is created by the Session and should rarely be created manually.
The cluster keeps track of all nodes in the cluster and if requested can listen for cluster changes and start tracking a new node if one appears. Currently nodes are removed from the pool if they become unhealthy (100 failed queries). This should hopefully soon be replaced by a backoff system.
func NewCluster ¶ added in v0.7.0
func NewCluster(hosts []Host, opts *ConnectOpts) (*Cluster, error)
NewCluster creates a new cluster by connecting to the given hosts.
func (*Cluster) Exec ¶ added in v0.7.0
Exec executes a ReQL query using the cluster to connect to the database
func (*Cluster) GetNextNode ¶ added in v1.2.0
GetNextNode returns a random node on the cluster
func (*Cluster) IsConnected ¶ added in v0.7.0
IsConnected returns true if cluster has nodes and is not already closed.
func (*Cluster) Query ¶ added in v0.7.0
Query executes a ReQL query using the cluster to connect to the database
func (*Cluster) Server ¶ added in v1.2.0
func (c *Cluster) Server() (response ServerResponse, err error)
Server returns the server name and server UUID being used by a connection.
func (*Cluster) SetInitialPoolCap ¶
SetInitialPoolCap sets the initial capacity of the connection pool.
func (*Cluster) SetMaxIdleConns ¶ added in v0.7.0
SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
func (*Cluster) SetMaxOpenConns ¶ added in v0.7.0
SetMaxOpenConns sets the maximum number of open connections to the database.
type ConnectOpts ¶
type ConnectOpts struct { // Address holds the address of the server initially used when creating the // session. Only used if Addresses is empty Address string `gorethink:"address,omitempty"` // Addresses holds the addresses of the servers initially used when creating // the session. Addresses []string `gorethink:"addresses,omitempty"` // Database is the default database name used when executing queries, this // value is only used if the query does not contain any DB term Database string `gorethink:"database,omitempty"` // Username holds the username used for authentication, if blank (and the v1 // handshake protocol is being used) then the admin user is used Username string `gorethink:"username,omitempty"` // Password holds the password used for authentication (only used when using // the v1 handshake protocol) Password string `gorethink:"password,omitempty"` // AuthKey is used for authentication when using the v0.4 handshake protocol // This field is no deprecated AuthKey string `gorethink:"authkey,omitempty"` // Timeout is the time the driver waits when creating new connections, to // configure the timeout used when executing queries use WriteTimeout and // ReadTimeout Timeout time.Duration `gorethink:"timeout,omitempty"` // WriteTimeout is the amount of time the driver will wait when sending the // query to the server WriteTimeout time.Duration `gorethink:"write_timeout,omitempty"` // ReadTimeout is the amount of time the driver will wait for a response from // the server when executing queries. ReadTimeout time.Duration `gorethink:"read_timeout,omitempty"` // KeepAlivePeriod is the keep alive period used by the connection, by default // this is 30s. It is not possible to disable keep alive messages KeepAlivePeriod time.Duration `gorethink:"keep_alive_timeout,omitempty"` // TLSConfig holds the TLS configuration and can be used when connecting // to a RethinkDB server protected by SSL TLSConfig *tls.Config `gorethink:"tlsconfig,omitempty"` // HandshakeVersion is used to specify which handshake version should be // used, this currently defaults to v1 which is used by RethinkDB 2.3 and // later. If you are using an older version then you can set the handshake // version to 0.4 HandshakeVersion HandshakeVersion `gorethink:"handshake_version,omitempty"` // UseJSONNumber indicates whether the cursors running in this session should // use json.Number instead of float64 while unmarshaling documents with // interface{}. The default is `false`. UseJSONNumber bool // NumRetries is the number of times a query is retried if a connection // error is detected, queries are not retried if RethinkDB returns a // runtime error. NumRetries int // InitialCap is used by the internal connection pool and is used to // configure how many connections are created for each host when the // session is created. If zero then no connections are created until // the first query is executed. InitialCap int `gorethink:"initial_cap,omitempty"` // MaxOpen is used by the internal connection pool and is used to configure // the maximum number of connections held in the pool. If all available // connections are being used then the driver will open new connections as // needed however they will not be returned to the pool. By default the // maximum number of connections is 2 MaxOpen int `gorethink:"max_open,omitempty"` // DiscoverHosts is used to enable host discovery, when true the driver // will attempt to discover any new nodes added to the cluster and then // start sending queries to these new nodes. DiscoverHosts bool `gorethink:"discover_hosts,omitempty"` // HostDecayDuration is used by the go-hostpool package to calculate a weighted // score when selecting a host. By default a value of 5 minutes is used. HostDecayDuration time.Duration // Deprecated: This function is no longer used due to changes in the // way hosts are selected. NodeRefreshInterval time.Duration `gorethink:"node_refresh_interval,omitempty"` // Deprecated: Use InitialCap instead MaxIdle int `gorethink:"max_idle,omitempty"` }
ConnectOpts is used to specify optional arguments when connecting to a cluster.
type Connection ¶
Connection is a connection to a rethinkdb database. Connection is not thread safe and should only be accessed be a single goroutine
func NewConnection ¶ added in v0.6.0
func NewConnection(address string, opts *ConnectOpts) (*Connection, error)
NewConnection creates a new connection to the database server
func (*Connection) Query ¶ added in v0.6.0
Query sends a Query to the database, returning both the raw Response and a Cursor which should be used to view the query's response.
This function is used internally by Run which should be used for most queries.
func (*Connection) Server ¶ added in v1.2.0
func (c *Connection) Server() (ServerResponse, error)
Server returns the server name and server UUID being used by a connection.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is the result of a query. Its cursor starts before the first row of the result set. A Cursor is not thread safe and should only be accessed by a single goroutine at any given time. Use Next to advance through the rows:
cursor, err := query.Run(session) ... defer cursor.Close() var response interface{} for cursor.Next(&response) { ... } err = cursor.Err() // get any error encountered during iteration ...
func (*Cursor) All ¶
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.
Also note that you are able to reuse the same variable multiple times as `All` zeroes the value before scanning in the result. It also attempts to reuse the existing slice without allocating any more space by either resizing or returning a selection of the slice if necessary.
func (*Cursor) Close ¶
Close closes the cursor, preventing further enumeration. If the end is encountered, the cursor is closed automatically. Close is idempotent.
func (*Cursor) Err ¶
Err returns nil if no errors happened during iteration, or the actual error otherwise.
func (*Cursor) Interface ¶
Interface retrieves all documents from the result set and returns the data as an interface{} and closes the cursor.
If the query returns multiple documents then a slice will be returned, otherwise a single value will be returned.
func (*Cursor) Listen ¶ added in v0.7.0
func (c *Cursor) Listen(channel interface{})
Listen listens for rows from the database and sends the result onto the given channel. The type that the row is scanned into is determined by the element type of the channel.
Also note that this function returns immediately.
cursor, err := r.Expr([]int{1,2,3}).Run(session) if err != nil { panic(err) } ch := make(chan int) cursor.Listen(ch) <- ch // 1 <- ch // 2 <- ch // 3
func (*Cursor) Next ¶
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.
Also note that you are able to reuse the same variable multiple times as `Next` zeroes the value before scanning in the result.
func (*Cursor) NextResponse ¶ added in v1.4.0
NextResponse retrieves the next raw response from the result set, blocking if necessary. Unlike Next the returned response is the raw JSON document returned from the database.
NextResponse returns false (and a nil byte slice) at the end of the result set or if an error happened.
func (*Cursor) One ¶
One retrieves a single document from the result set into the provided slice and closes the cursor.
Also note that you are able to reuse the same variable multiple times as `One` zeroes the value before scanning in the result.
func (*Cursor) Peek ¶
Peek behaves similarly to Next, retreiving the next document from the result set and blocking if necessary. Peek, however, does not progress the position of the cursor. This can be useful for expressions which can return different types to attempt to decode them into different interfaces.
Like Next, it will also automatically retrieve another batch of documents from the server when the current one is exhausted, or before that in background if possible.
Unlike Next, Peek does not progress the position of the cursor. Peek will return errors from decoding, but they will not be persisted in the cursor and therefore will not be available on cursor.Err(). This can be useful for expressions that can return different types to attempt to decode them into different interfaces.
Peek returns true if a document was successfully unmarshalled onto result, and false at the end of the result set or if an error happened. Peek also returns the error (if any) that occured
Example ¶
package main import ( "fmt" "time" test "gopkg.in/check.v1" ) type object struct { ID int64 `gorethink:"id,omitempty"` Name string `gorethink:"name"` Attrs []attr } type attr struct { Name string Value interface{} } func (s *RethinkSuite) TestCursorLiteral(c *test.C) { res, err := Expr(5).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response interface{} err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, 5) } func (s *RethinkSuite) TestCursorSlice(c *test.C) { res, err := Expr([]interface{}{1, 2, 3, 4, 5}).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response []interface{} err = res.All(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, []interface{}{1, 2, 3, 4, 5}) } func (s *RethinkSuite) TestCursorPartiallyNilSlice(c *test.C) { res, err := Expr(map[string]interface{}{ "item": []interface{}{ map[string]interface{}{"num": 1}, nil, }, }).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response map[string]interface{} err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, map[string]interface{}{ "item": []interface{}{ map[string]interface{}{"num": 1}, nil, }, }) } func (s *RethinkSuite) TestCursorMap(c *test.C) { res, err := Expr(map[string]interface{}{ "id": 2, "name": "Object 1", }).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response map[string]interface{} err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, map[string]interface{}{ "id": 2, "name": "Object 1", }) } func (s *RethinkSuite) TestCursorMapIntoInterface(c *test.C) { res, err := Expr(map[string]interface{}{ "id": 2, "name": "Object 1", }).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response interface{} err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, map[string]interface{}{ "id": 2, "name": "Object 1", }) } func (s *RethinkSuite) TestCursorMapNested(c *test.C) { res, err := Expr(map[string]interface{}{ "id": 2, "name": "Object 1", "attr": []interface{}{map[string]interface{}{ "name": "attr 1", "value": "value 1", }}, }).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response interface{} err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, map[string]interface{}{ "id": 2, "name": "Object 1", "attr": []interface{}{map[string]interface{}{ "name": "attr 1", "value": "value 1", }}, }) } func (s *RethinkSuite) TestCursorStruct(c *test.C) { res, err := Expr(map[string]interface{}{ "id": 2, "name": "Object 1", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response object err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, test.DeepEquals, object{ ID: 2, Name: "Object 1", Attrs: []attr{attr{ Name: "attr 1", Value: "value 1", }}, }) } func (s *RethinkSuite) TestCursorStructPseudoTypes(c *test.C) { var zeroTime time.Time t := time.Now() res, err := Expr(map[string]interface{}{ "T": time.Unix(t.Unix(), 0).In(time.UTC), "Z": zeroTime, "B": []byte("hello"), }).Run(session) c.Assert(err, test.IsNil) var response PseudoTypes err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") c.Assert(response.T.Equal(time.Unix(t.Unix(), 0)), test.Equals, true) c.Assert(response.Z.Equal(zeroTime), test.Equals, true) c.Assert(response.B, jsonEquals, []byte("hello")) } func (s *RethinkSuite) TestCursorAtomString(c *test.C) { res, err := Expr("a").Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response string err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, test.Equals, "a") } func (s *RethinkSuite) TestCursorAtomArray(c *test.C) { res, err := Expr([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") var response []int err = res.All(&response) c.Assert(err, test.IsNil) c.Assert(response, test.DeepEquals, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}) } func (s *RethinkSuite) TestEmptyResults(c *test.C) { DBCreate("test").Exec(session) DB("test").TableCreate("test").Exec(session) res, err := DB("test").Table("test").Get("missing value").Run(session) c.Assert(err, test.IsNil) c.Assert(res.IsNil(), test.Equals, true) res, err = DB("test").Table("test").Get("missing value").Run(session) c.Assert(err, test.IsNil) var response interface{} err = res.One(&response) c.Assert(err, test.Equals, ErrEmptyResult) c.Assert(res.IsNil(), test.Equals, true) res, err = Expr(nil).Run(session) c.Assert(err, test.IsNil) c.Assert(res.IsNil(), test.Equals, true) res, err = DB("test").Table("test").Get("missing value").Run(session) c.Assert(err, test.IsNil) c.Assert(res.IsNil(), test.Equals, true) res, err = DB("test").Table("test").GetAll("missing value", "another missing value").Run(session) c.Assert(err, test.IsNil) c.Assert(res.Next(&response), test.Equals, false) var obj object obj.Name = "missing value" res, err = DB("test").Table("test").Filter(obj).Run(session) c.Assert(err, test.IsNil) c.Assert(res.IsNil(), test.Equals, true) var objP *object res, err = DB("test").Table("test").Get("missing value").Run(session) res.Next(&objP) c.Assert(err, test.IsNil) c.Assert(objP, test.IsNil) } func (s *RethinkSuite) TestCursorAll(c *test.C) { // Ensure table + database exist DBCreate("test").Exec(session) DB("test").TableDrop("Table3").Exec(session) DB("test").TableCreate("Table3").Exec(session) DB("test").Table("Table3").IndexCreate("num").Exec(session) DB("test").Table("Table3").IndexWait().Exec(session) // Insert rows DB("test").Table("Table3").Insert([]interface{}{ map[string]interface{}{ "id": 2, "name": "Object 1", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }, map[string]interface{}{ "id": 3, "name": "Object 2", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }, }).Exec(session) // Test query query := DB("test").Table("Table3").OrderBy("id") res, err := query.Run(session) c.Assert(err, test.IsNil) var response []object err = res.All(&response) c.Assert(err, test.IsNil) c.Assert(response, test.HasLen, 2) c.Assert(response, test.DeepEquals, []object{ object{ ID: 2, Name: "Object 1", Attrs: []attr{attr{ Name: "attr 1", Value: "value 1", }}, }, object{ ID: 3, Name: "Object 2", Attrs: []attr{attr{ Name: "attr 1", Value: "value 1", }}, }, }) } func (s *RethinkSuite) TestCursorListen(c *test.C) { // Ensure table + database exist DBCreate("test").Exec(session) DB("test").TableDrop("Table3").Exec(session) DB("test").TableCreate("Table3").Exec(session) DB("test").Table("Table3").Wait().Exec(session) DB("test").Table("Table3").IndexCreate("num").Exec(session) DB("test").Table("Table3").IndexWait().Exec(session) // Insert rows DB("test").Table("Table3").Insert([]interface{}{ map[string]interface{}{ "id": 2, "name": "Object 1", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }, map[string]interface{}{ "id": 3, "name": "Object 2", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }, }).Exec(session) // Test query query := DB("test").Table("Table3").OrderBy("id") res, err := query.Run(session) c.Assert(err, test.IsNil) ch := make(chan object) res.Listen(ch) var response []object for v := range ch { response = append(response, v) } c.Assert(response, test.HasLen, 2) c.Assert(response, test.DeepEquals, []object{ object{ ID: 2, Name: "Object 1", Attrs: []attr{attr{ Name: "attr 1", Value: "value 1", }}, }, object{ ID: 3, Name: "Object 2", Attrs: []attr{attr{ Name: "attr 1", Value: "value 1", }}, }, }) } func (s *RethinkSuite) TestCursorChangesClose(c *test.C) { // Ensure table + database exist DBCreate("test").Exec(session) DB("test").TableDrop("Table3").Exec(session) DB("test").TableCreate("Table3").Exec(session) // Test query // res, err := DB("test").Table("Table3").Changes().Run(session) res, err := DB("test").Table("Table3").Changes().Run(session) c.Assert(err, test.IsNil) c.Assert(res, test.NotNil) // Ensure that the cursor can be closed err = res.Close() c.Assert(err, test.IsNil) } func (s *RethinkSuite) TestCursorReuseResult(c *test.C) { // Test query query := Expr([]interface{}{ map[string]interface{}{ "A": "a", }, map[string]interface{}{ "B": 1, }, map[string]interface{}{ "A": "a", }, map[string]interface{}{ "B": 1, }, map[string]interface{}{ "A": "a", "B": 1, }, }) res, err := query.Run(session) c.Assert(err, test.IsNil) var i int var result SimpleT for res.Next(&result) { switch i { case 0: c.Assert(result, test.DeepEquals, SimpleT{ A: "a", B: 0, }) case 1: c.Assert(result, test.DeepEquals, SimpleT{ A: "", B: 1, }) case 2: c.Assert(result, test.DeepEquals, SimpleT{ A: "a", B: 0, }) case 3: c.Assert(result, test.DeepEquals, SimpleT{ A: "", B: 1, }) case 4: c.Assert(result, test.DeepEquals, SimpleT{ A: "a", B: 1, }) default: c.Fatalf("Unexpected number of results") } i++ } c.Assert(res.Err(), test.IsNil) } func (s *RethinkSuite) TestCursorNextResponse(c *test.C) { res, err := Expr(5).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") b, ok := res.NextResponse() c.Assert(ok, test.Equals, true) c.Assert(b, jsonEquals, []byte(`5`)) } func (s *RethinkSuite) TestCursorNextResponse_object(c *test.C) { res, err := Expr(map[string]string{"foo": "bar"}).Run(session) c.Assert(err, test.IsNil) c.Assert(res.Type(), test.Equals, "Cursor") b, ok := res.NextResponse() c.Assert(ok, test.Equals, true) c.Assert(b, jsonEquals, []byte(`{"foo":"bar"}`)) } func (s *RethinkSuite) TestCursorPeek_idempotency(c *test.C) { res, err := Expr([]int{1, 2, 3}).Run(session) c.Assert(err, test.IsNil) var result int // Test idempotency for i := 0; i < 2; i++ { hasMore, err := res.Peek(&result) c.Assert(err, test.IsNil) c.Assert(result, test.Equals, 1) c.Assert(hasMore, test.Equals, true) } } func (s *RethinkSuite) TestCursorPeek_wrong_type(c *test.C) { res, err := Expr([]int{1, 2, 3}).Run(session) c.Assert(err, test.IsNil) // Test that wrongType doesn't break the cursor wrongType := struct { Name string Age int }{} hasMore, err := res.Peek(&wrongType) c.Assert(err, test.NotNil) c.Assert(hasMore, test.Equals, false) c.Assert(res.Err(), test.IsNil) } func (s *RethinkSuite) TestCursorPeek_usage(c *test.C) { res, err := Expr([]int{1, 2, 3}).Run(session) c.Assert(err, test.IsNil) var result int // Test that Skip progresses our cursor res.Skip() hasMore, err := res.Peek(&result) c.Assert(err, test.IsNil) c.Assert(result, test.Equals, 2) c.Assert(hasMore, test.Equals, true) // Test that we can use Next afterwards and we get the same result hasMore = res.Next(&result) c.Assert(result, test.Equals, 2) c.Assert(hasMore, test.Equals, true) } func (s *RethinkSuite) TestCursorSkip(c *test.C) { res, err := Expr([]int{1, 2, 3}).Run(session) c.Assert(err, test.IsNil) res.Skip() var result int hasMore := res.Next(&result) c.Assert(result, test.Equals, 2) c.Assert(hasMore, test.Equals, true) } func main() { res, err := Expr([]int{1, 2, 3}).Run(session) if err != nil { fmt.Print(err) return } var result, altResult int wasRead, err := res.Peek(&result) // Result is now 1 if err != nil { fmt.Print(err) return } else if !wasRead { fmt.Print("No data to read!") } res.Next(&altResult) // altResult is also 1, peek didn't progress the cursor res.Skip() // progress the cursor, skipping 2 res.Peek(&result) // result is now 3 }
Output:
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"` }
DeleteOpts contains the optional arguments for the Delete term
type DistanceOpts ¶ added in v0.5.0
type DistanceOpts struct { GeoSystem interface{} `gorethink:"geo_system,omitempty"` Unit interface{} `gorethink:"unit,omitempty"` }
DistanceOpts contains the optional arguments for the Distance term.
type DistinctOpts ¶ added in v0.4.0
type DistinctOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
DistinctOpts contains the optional arguments for the Distinct term
type DuringOpts ¶
type DuringOpts struct { LeftBound interface{} `gorethink:"left_bound,omitempty"` RightBound interface{} `gorethink:"right_bound,omitempty"` }
DuringOpts contains the optional arguments for the During term
type EqJoinOpts ¶
type EqJoinOpts struct { Index interface{} `gorethink:"index,omitempty"` Ordered interface{} `gorethink:"ordered,omitempty"` }
EqJoinOpts contains the optional arguments for the EqJoin term.
type ExecOpts ¶ added in v0.6.0
type ExecOpts struct { DB interface{} `gorethink:"db,omitempty"` Db interface{} `gorethink:"db,omitempty"` // Deprecated Profile interface{} `gorethink:"profile,omitempty"` Durability interface{} `gorethink:"durability,omitempty"` UseOutdated interface{} `gorethink:"use_outdated,omitempty"` // Deprecated ArrayLimit interface{} `gorethink:"array_limit,omitempty"` TimeFormat interface{} `gorethink:"time_format,omitempty"` GroupFormat interface{} `gorethink:"group_format,omitempty"` BinaryFormat interface{} `gorethink:"binary_format,omitempty"` GeometryFormat interface{} `gorethink:"geometry_format,omitempty"` MinBatchRows interface{} `gorethink:"min_batch_rows,omitempty"` MaxBatchRows interface{} `gorethink:"max_batch_rows,omitempty"` MaxBatchBytes interface{} `gorethink:"max_batch_bytes,omitempty"` MaxBatchSeconds interface{} `gorethink:"max_batch_seconds,omitempty"` FirstBatchScaledownFactor interface{} `gorethink:"first_batch_scaledown_factor,omitempty"` NoReply interface{} `gorethink:"noreply,omitempty"` Context context.Context `gorethink:"-"` }
ExecOpts contains the optional arguments for the Exec function and inherits its options from RunOpts, the only difference is the addition of the NoReply field.
When NoReply is true it causes the driver not to wait to receive the result and return immediately.
type FilterOpts ¶
type FilterOpts struct {
Default interface{} `gorethink:"default,omitempty"`
}
FilterOpts contains the optional arguments for the Filter term
type FoldOpts ¶
type FoldOpts struct { Emit interface{} `gorethink:"emit,omitempty"` FinalEmit interface{} `gorethink:"final_emit,omitempty"` }
FoldOpts contains the optional arguments for the Fold term
type GetAllOpts ¶
type GetAllOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
GetAllOpts contains the optional arguments for the GetAll term
type GetIntersectingOpts ¶ added in v0.5.0
type GetIntersectingOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
GetIntersectingOpts contains the optional arguments for the GetIntersecting term.
type GetNearestOpts ¶ added in v0.5.0
type GetNearestOpts struct { Index interface{} `gorethink:"index,omitempty"` MaxResults interface{} `gorethink:"max_results,omitempty"` MaxDist interface{} `gorethink:"max_dist,omitempty"` Unit interface{} `gorethink:"unit,omitempty"` GeoSystem interface{} `gorethink:"geo_system,omitempty"` }
GetNearestOpts contains the optional arguments for the GetNearest term.
type GroupOpts ¶
type GroupOpts struct { Index interface{} `gorethink:"index,omitempty"` Multi interface{} `gorethink:"multi,omitempty"` }
GroupOpts contains the optional arguments for the Group term
type HTTPOpts ¶ added in v1.0.0
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:"result_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"` }
HTTPOpts contains the optional arguments for the HTTP term
type HandshakeVersion ¶
type HandshakeVersion int
const ( HandshakeV1_0 HandshakeVersion = iota HandshakeV0_4 )
type ISO8601Opts ¶
type ISO8601Opts struct {
DefaultTimezone interface{} `gorethink:"default_timezone,omitempty"`
}
ISO8601Opts contains the optional arguments for the ISO8601 term
type IndexCreateOpts ¶
type IndexCreateOpts struct { Multi interface{} `gorethink:"multi,omitempty"` Geo interface{} `gorethink:"geo,omitempty"` }
IndexCreateOpts contains the optional arguments for the IndexCreate term
type IndexRenameOpts ¶ added in v0.4.0
type IndexRenameOpts struct {
Overwrite interface{} `gorethink:"overwrite,omitempty"`
}
IndexRenameOpts contains the optional arguments for the IndexRename term
type InsertOpts ¶
type InsertOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnChanges interface{} `gorethink:"return_changes,omitempty"` Conflict interface{} `gorethink:"conflict,omitempty"` }
InsertOpts contains the optional arguments for the Insert term
type JSOpts ¶
type JSOpts struct {
Timeout interface{} `gorethink:"timeout,omitempty"`
}
JSOpts contains the optional arguments for the JS term
type MaxOpts ¶
type MaxOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
MaxOpts contains the optional arguments for the Max term
type MinOpts ¶
type MinOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
MinOpts contains the optional arguments for the Min term
type Mock ¶
type Mock struct { ExpectedQueries []*MockQuery Queries []MockQuery // contains filtered or unexported fields }
Mock is used to mock query execution and verify that the expected queries are being executed. Mocks are used by creating an instance using NewMock and then passing this when running your queries instead of a session. For example:
mock := r.NewMock() mock.On(r.Table("test")).Return([]interface{}{data}, nil) cursor, err := r.Table("test").Run(mock) mock.AssertExpectations(t)
func NewMock ¶
func NewMock(opts ...ConnectOpts) *Mock
NewMock creates an instance of Mock, you can optionally pass ConnectOpts to the function, if passed any mocked query will be generated using those options.
func (*Mock) AssertExecuted ¶
AssertExecuted asserts that the method was executed. It can produce a false result when an argument is a pointer type and the underlying value changed after executing the mocked method.
func (*Mock) AssertExpectations ¶
AssertExpectations asserts that everything specified with On and Return was in fact executed as expected. Queries may have been executed in any order.
func (*Mock) AssertNotExecuted ¶
AssertNotExecuted asserts that the method was not executed. It can produce a false result when an argument is a pointer type and the underlying value changed after executing the mocked method.
func (*Mock) AssertNumberOfExecutions ¶
func (m *Mock) AssertNumberOfExecutions(t testingT, expectedQuery *MockQuery, expectedExecutions int) bool
AssertNumberOfExecutions asserts that the query was executed expectedExecutions times.
func (*Mock) IsConnected ¶
type MockQuery ¶
type MockQuery struct { // Holds the query and term Query Query // Holds the JSON representation of query BuiltQuery []byte // Holds the response that should be returned when this method is executed. Response interface{} // Holds the error that should be returned when this method is executed. Error error // The number of times to return the return arguments when setting // expectations. 0 means to always return the value. Repeatability int // Holds a channel that will be used to block the Return until it either // recieves a message or is closed. nil means it returns immediately. WaitFor <-chan time.Time // contains filtered or unexported fields }
MockQuery represents a mocked query and is used for setting expectations, as well as recording activity.
func (*MockQuery) After ¶
After sets how long to block until the query returns
mock.On(r.Table("test")).After(time.Second)
func (*MockQuery) On ¶
On chains a new expectation description onto the mocked interface. This allows syntax like.
Mock. On(r.Table("test")).Return(result, nil). On(r.Table("test2")).Return(nil, errors.New("Some Error"))
func (*MockQuery) Once ¶
Once indicates that that the mock should only return the value once.
mock.On(r.Table("test")).Return(result, nil).Once()
func (*MockQuery) Return ¶
Return specifies the return arguments for the expectation.
mock.On(r.Table("test")).Return(nil, errors.New("failed"))
func (*MockQuery) Times ¶
Times indicates that that the mock should only return the indicated number of times.
mock.On(r.Table("test")).Return(result, nil).Times(5)
type Node ¶ added in v0.7.0
Node represents a database server in the cluster
func (*Node) NoReplyWait ¶ added in v0.7.0
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 (*Node) Server ¶ added in v1.2.0
func (n *Node) Server() (ServerResponse, error)
Server returns the server name and server UUID being used by a connection.
func (*Node) SetInitialPoolCap ¶
SetInitialPoolCap sets the initial capacity of the connection pool.
func (*Node) SetMaxIdleConns ¶ added in v0.7.0
SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
func (*Node) SetMaxOpenConns ¶ added in v0.7.0
SetMaxOpenConns sets the maximum number of open connections to the database.
type OptArgs ¶
type OptArgs interface {
// contains filtered or unexported methods
}
OptArgs is an interface used to represent a terms optional arguments. All optional argument types have a toMap function, the returned map can be encoded and sent as part of the query.
type OrderByOpts ¶
type OrderByOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
OrderByOpts contains the optional arguments for the OrderBy term
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
A Pool is used to store a pool of connections to a single RethinkDB server
func NewPool ¶ added in v0.6.0
func NewPool(host Host, opts *ConnectOpts) (*Pool, error)
NewPool creates a new connection pool for the given host
func (*Pool) Close ¶
Close closes the database, releasing any open resources.
It is rare to Close a Pool, as the Pool handle is meant to be long-lived and shared between many goroutines.
func (*Pool) Ping ¶ added in v0.6.0
Ping verifies a connection to the database is still alive, establishing a connection if necessary.
func (*Pool) Server ¶ added in v1.2.0
func (p *Pool) Server() (ServerResponse, error)
Server returns the server name and server UUID being used by a connection.
func (*Pool) SetInitialPoolCap
deprecated
func (*Pool) SetMaxIdleConns
deprecated
added in
v0.6.0
func (*Pool) SetMaxOpenConns
deprecated
added in
v0.6.0
type Query ¶ added in v0.4.0
type Query struct { Type p.Query_QueryType Token int64 Term *Term Opts map[string]interface{} // contains filtered or unexported fields }
A Query represents a query ready to be sent to the database, A Query differs from a Term as it contains both a query type and token. These values are used by the database to determine if the query is continuing a previous request and also allows the driver to identify the response as they can come out of order.
type QueryExecutor ¶
type RQLAuthError ¶ added in v1.3.0
type RQLAuthError struct{ RQLDriverError }
type RQLAvailabilityError ¶ added in v1.3.0
type RQLAvailabilityError struct{ RQLRuntimeError }
type RQLClientError ¶ added in v1.0.0
type RQLClientError struct {
// contains filtered or unexported fields
}
type RQLCompileError ¶ added in v1.0.0
type RQLCompileError struct {
// contains filtered or unexported fields
}
type RQLConnectionError ¶ added in v1.0.0
type RQLConnectionError struct {
// contains filtered or unexported fields
}
RQLConnectionError represents an error when communicating with the database server.
type RQLDriverCompileError ¶ added in v1.3.0
type RQLDriverCompileError struct{ RQLCompileError }
type RQLDriverError ¶ added in v1.0.0
type RQLDriverError struct {
// contains filtered or unexported fields
}
RQLDriverError represents an unexpected error with the driver, if this error persists please create an issue.
type RQLInternalError ¶ added in v1.3.0
type RQLInternalError struct{ RQLRuntimeError }
type RQLNonExistenceError ¶ added in v1.3.0
type RQLNonExistenceError struct{ RQLQueryLogicError }
type RQLOpFailedError ¶ added in v1.3.0
type RQLOpFailedError struct{ RQLAvailabilityError }
type RQLOpIndeterminateError ¶ added in v1.3.0
type RQLOpIndeterminateError struct{ RQLAvailabilityError }
type RQLQueryLogicError ¶ added in v1.3.0
type RQLQueryLogicError struct{ RQLRuntimeError }
type RQLResourceLimitError ¶ added in v1.3.0
type RQLResourceLimitError struct{ RQLRuntimeError }
type RQLRuntimeError ¶ added in v1.0.0
type RQLRuntimeError struct {
// contains filtered or unexported fields
}
type RQLServerCompileError ¶ added in v1.3.0
type RQLServerCompileError struct{ RQLCompileError }
type RQLTimeoutError ¶ added in v1.3.0
type RQLTimeoutError struct {
// contains filtered or unexported fields
}
type RQLUserError ¶ added in v1.3.0
type RQLUserError struct{ RQLRuntimeError }
type RandomOpts ¶
type RandomOpts struct {
Float interface{} `gorethink:"float,omitempty"`
}
RandomOpts contains the optional arguments for the Random term.
type ReconfigureOpts ¶ added in v0.6.0
type ReconfigureOpts struct { Shards interface{} `gorethink:"shards,omitempty"` Replicas interface{} `gorethink:"replicas,omitempty"` DryRun interface{} `gorethink:"dry_run,omitempty"` EmergencyRepair interface{} `gorethink:"emergency_repair,omitempty"` NonVotingReplicaTags interface{} `gorethink:"nonvoting_replica_tags,omitempty"` PrimaryReplicaTag interface{} `gorethink:"primary_replica_tag,omitempty"` }
ReconfigureOpts contains the optional arguments for the Reconfigure term.
type ReplaceOpts ¶
type ReplaceOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnChanges interface{} `gorethink:"return_changes,omitempty"` NonAtomic interface{} `gorethink:"non_atomic,omitempty"` }
ReplaceOpts contains the optional arguments for the Replace term
type Response ¶ added in v0.4.0
type Response struct { Token int64 Type p.Response_ResponseType `json:"t"` ErrorType p.Response_ErrorType `json:"e"` Notes []p.Response_ResponseNote `json:"n"` Responses []json.RawMessage `json:"r"` Backtrace []interface{} `json:"b"` Profile interface{} `json:"p"` }
Response represents the raw response from a query, most of the time you should instead use a Cursor when reading from the database.
type RunOpts ¶
type RunOpts struct { DB interface{} `gorethink:"db,omitempty"` Db interface{} `gorethink:"db,omitempty"` // Deprecated Profile interface{} `gorethink:"profile,omitempty"` Durability interface{} `gorethink:"durability,omitempty"` UseOutdated interface{} `gorethink:"use_outdated,omitempty"` // Deprecated ArrayLimit interface{} `gorethink:"array_limit,omitempty"` TimeFormat interface{} `gorethink:"time_format,omitempty"` GroupFormat interface{} `gorethink:"group_format,omitempty"` BinaryFormat interface{} `gorethink:"binary_format,omitempty"` GeometryFormat interface{} `gorethink:"geometry_format,omitempty"` ReadMode interface{} `gorethink:"read_mode,omitempty"` MinBatchRows interface{} `gorethink:"min_batch_rows,omitempty"` MaxBatchRows interface{} `gorethink:"max_batch_rows,omitempty"` MaxBatchBytes interface{} `gorethink:"max_batch_bytes,omitempty"` MaxBatchSeconds interface{} `gorethink:"max_batch_seconds,omitempty"` FirstBatchScaledownFactor interface{} `gorethink:"first_batch_scaledown_factor,omitempty"` Context context.Context `gorethink:"-"` }
RunOpts contains the optional arguments for the Run function.
type ServerResponse ¶ added in v1.2.0
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
A Session represents a connection to a RethinkDB cluster and should be used when executing queries.
func Connect ¶
func Connect(opts ConnectOpts) (*Session, error)
Connect creates a new database session. To view the available connection options see ConnectOpts.
By default maxIdle and maxOpen are set to 1: passing values greater than the default (e.g. MaxIdle: "10", MaxOpen: "20") will provide a pool of re-usable connections.
Basic connection example:
session, err := r.Connect(r.ConnectOpts{ Host: "localhost:28015", Database: "test", AuthKey: "14daak1cad13dj", })
Cluster connection example:
session, err := r.Connect(r.ConnectOpts{ Hosts: []string{"localhost:28015", "localhost:28016"}, Database: "test", AuthKey: "14daak1cad13dj", })
Example ¶
package main import ( "log" r "gopkg.in/gorethink/gorethink.v3" ) var session *r.Session var url string func main() { var err error session, err = r.Connect(r.ConnectOpts{ Address: url, }) if err != nil { log.Fatalln(err.Error()) } }
Output:
Example (Cluster) ¶
package main import ( "log" r "gopkg.in/gorethink/gorethink.v3" ) var session *r.Session var url string func main() { var err error session, err = r.Connect(r.ConnectOpts{ Addresses: []string{url}, // Addresses: []string{url1, url2, url3, ...}, }) if err != nil { log.Fatalln(err.Error()) } }
Output:
Example (ConnectionPool) ¶
package main import ( "log" r "gopkg.in/gorethink/gorethink.v3" ) var session *r.Session var url string func main() { var err error session, err = r.Connect(r.ConnectOpts{ Address: url, InitialCap: 10, MaxOpen: 10, }) if err != nil { log.Fatalln(err.Error()) } }
Output:
func (*Session) Exec ¶ added in v0.7.0
Exec executes a ReQL query using the session to connect to the database
func (*Session) IsConnected ¶ added in v1.3.0
IsConnected returns true if session has a valid connection.
func (*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) Query ¶ added in v0.7.0
Query executes a ReQL query using the session to connect to the database
func (*Session) Server ¶ added in v1.2.0
func (s *Session) Server() (ServerResponse, error)
Server returns the server name and server UUID being used by a connection.
func (*Session) SetHosts ¶ added in v0.7.0
SetHosts resets the hosts used when connecting to the RethinkDB cluster
func (*Session) SetInitialPoolCap ¶
SetInitialPoolCap sets the initial capacity of the connection pool.
func (*Session) SetMaxIdleConns ¶
SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
func (*Session) SetMaxOpenConns ¶
SetMaxOpenConns sets the maximum number of open connections to the database.
type SliceOpts ¶
type SliceOpts struct { LeftBound interface{} `gorethink:"left_bound,omitempty"` RightBound interface{} `gorethink:"right_bound,omitempty"` }
SliceOpts contains the optional arguments for the Slice term
type TableCreateOpts ¶
type TableCreateOpts struct { PrimaryKey interface{} `gorethink:"primary_key,omitempty"` Durability interface{} `gorethink:"durability,omitempty"` Shards interface{} `gorethink:"shards,omitempty"` Replicas interface{} `gorethink:"replicas,omitempty"` PrimaryReplicaTag interface{} `gorethink:"primary_replica_tag,omitempty"` NonVotingReplicaTags interface{} `gorethink:"nonvoting_replica_tags,omitempty"` }
TableCreateOpts contains the optional arguments for the TableCreate term
type TableOpts ¶
type TableOpts struct { ReadMode interface{} `gorethink:"read_mode,omitempty"` UseOutdated interface{} `gorethink:"use_outdated,omitempty"` // Deprecated IdentifierFormat interface{} `gorethink:"identifier_format,omitempty"` }
TableOpts contains the optional arguments for the Table term
type Term ¶
type Term struct {
// contains filtered or unexported fields
}
A Term represents a query that is being built. Terms consist of a an array of "sub-terms" and a term type. When a Term is a sub-term the first element of the terms data is its parent Term.
When built the term becomes a JSON array, for more information on the format see http://rethinkdb.com/docs/writing-drivers/.
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
Asc is used by the OrderBy term to specify that the ordering be ascending (the default).
func Avg ¶
func Avg(args ...interface{}) Term
Avg returns the average of 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 Binary ¶ added in v0.4.0
func Binary(data interface{}) Term
Binary encapsulates binary data within a query.
The type of data binary accepts depends on the client language. In Go, it expects either a byte array/slice or a bytes.Buffer.
Only a limited subset of ReQL commands may be chained after binary:
- coerceTo can coerce binary objects to string types
- count will return the number of bytes in the object
- slice will treat bytes like array indexes (i.e., slice(10,20) will return bytes 10–19)
- typeOf returns PTYPE<BINARY>
- info will return information on a binary object.
func Branch ¶
func Branch(args ...interface{}) Term
Branch evaluates 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.
Example ¶
Return heroes and superheroes.
cur, err := DB("examples").Table("marvel").OrderBy("name").Map(Branch( Row.Field("victories").Gt(100), Row.Field("name").Add(" is a superhero"), Row.Field("name").Add(" is a hero"), )).Run(session) if err != nil { fmt.Print(err) return } var strs []string err = cur.All(&strs) if err != nil { fmt.Print(err) return } for _, str := range strs { fmt.Println(str) }
Output: Iron Man is a superhero Jubilee is a hero
func Ceil ¶ added in v1.1.0
func Ceil(args ...interface{}) Term
Ceil rounds the given value up, returning the smallest integer value greater than or equal to the given value (the value’s ceiling).
func Circle ¶ added in v0.5.0
func Circle(point, radius interface{}, optArgs ...CircleOpts) Term
Circle constructs a circular line or polygon. A circle in RethinkDB is a polygon or line approximating a circle of a given radius around a given center, consisting of a specified number of vertices (default 32).
func Contains ¶
func Contains(args ...interface{}) Term
Contains 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 Count ¶
func 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 DBCreate ¶ added in v1.0.0
func DBCreate(args ...interface{}) Term
DBCreate creates a database. A RethinkDB database is a collection of tables, similar to relational databases.
Note: that you can only use alphanumeric characters and underscores for the database name.
Example ¶
Create a database named ’superheroes’.
resp, err := DBCreate("superheroes").RunWrite(session) if err != nil { fmt.Print(err) } fmt.Printf("%d DB created", resp.DBsCreated)
Output: 1 DB created
func DBDrop ¶ added in v1.0.0
func DBDrop(args ...interface{}) Term
DBDrop drops a database. The database, all its tables, and corresponding data will be deleted.
Example ¶
Drop a database named ‘superheroes’.
// Setup database + tables DBCreate("superheroes").Exec(session) DB("superheroes").TableCreate("superheroes").Exec(session) DB("superheroes").TableCreate("battles").Exec(session) resp, err := DBDrop("superheroes").RunWrite(session) if err != nil { fmt.Print(err) } fmt.Printf("%d DB dropped, %d tables dropped", resp.DBsDropped, resp.TablesDropped)
Output: 1 DB dropped, 2 tables dropped
func DBList ¶ added in v1.0.0
func DBList(args ...interface{}) Term
DBList lists all database names in the system.
func Desc ¶
func Desc(args ...interface{}) Term
Desc is used by the OrderBy term to specify the ordering to be descending.
func Distance ¶ added in v0.5.0
func Distance(point1, point2 interface{}, optArgs ...DistanceOpts) Term
Distance calculates the Haversine distance between two points. At least one of the geometry objects specified must be a point.
func Distinct ¶
func Distinct(arg interface{}, optArgs ...DistinctOpts) Term
Distinct removes duplicate elements from the sequence.
func Do ¶
func Do(args ...interface{}) Term
Do evaluates 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
EpochTime returns a time object based on seconds since epoch
func Error ¶
func Error(args ...interface{}) Term
Error throws a runtime error. If called with no arguments inside the second argument to `default`, re-throw the current error.
Example ¶
Return an error
err := Error("this is a runtime error").Exec(session) fmt.Println(err)
Output:
func Expr ¶
func Expr(val interface{}) Term
Expr converts any value to an expression and is also used by many other terms such as Insert and Update. This function can convert the following basic Go types (bool, int, uint, string, float) and even pointers, maps and structs.
When evaluating structs they 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"`
Example (Int) ¶
Convert a Go integer to a ReQL object
cur, err := Expr(1).Run(session) if err != nil { fmt.Print(err) return } var res interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: 1
Example (Map) ¶
Convert a Go slice to a ReQL object
cur, err := Expr(map[string]interface{}{ "a": 1, "b": "b", }).Run(session) if err != nil { fmt.Print(err) return } var res interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: { "a": 1, "b": "b" }
Example (Slice) ¶
Convert a Go slice to a ReQL object
cur, err := Expr([]int{1, 2, 3}).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: [ 1, 2, 3 ]
Example (Struct) ¶
Convert a Go slice to a ReQL object
type ExampleTypeNested struct { N int } type ExampleTypeEmbed struct { C string } type ExampleTypeA struct { ExampleTypeEmbed A int B string Nested ExampleTypeNested } cur, err := Expr(ExampleTypeA{ A: 1, B: "b", ExampleTypeEmbed: ExampleTypeEmbed{ C: "c", }, Nested: ExampleTypeNested{ N: 2, }, }).Run(session) if err != nil { fmt.Print(err) return } var res interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: { "A": 1, "B": "b", "C": "c", "Nested": { "N": 2 } }
Example (StructTags) ¶
Convert a Go struct (with gorethink tags) to a ReQL object. The tags allow the field names to be changed.
type ExampleType struct { A int `gorethink:"field_a"` B string `gorethink:"field_b"` } cur, err := Expr(ExampleType{ A: 1, B: "b", }).Run(session) if err != nil { fmt.Print(err) return } var res interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: { "field_a": 1, "field_b": "b" }
func Floor ¶ added in v1.1.0
func Floor(args ...interface{}) Term
Floor rounds the given value down, returning the largest integer value less than or equal to the given value (the value’s floor).
func Ge ¶
func Ge(args ...interface{}) Term
Ge returns true if the first value is greater than or equal to the second.
func GeoJSON ¶ added in v1.0.0
func GeoJSON(args ...interface{}) Term
GeoJSON converts a GeoJSON object to a ReQL geometry object.
func Group ¶
func Group(fieldOrFunctions ...interface{}) Term
Group 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 GroupByIndex ¶
func GroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
GroupByIndex 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 Gt ¶
func Gt(args ...interface{}) Term
Gt returns true if the first value is greater than the second.
func HTTP ¶ added in v1.0.0
HTTP retrieves data from the specified URL over HTTP. The return type depends on the resultFormat option, which checks the Content-Type of the response by default.
func ISO8601 ¶
func ISO8601(date interface{}, optArgs ...ISO8601Opts) Term
ISO8601 returns a time object based on an ISO8601 formatted date-time string
func JS ¶ added in v1.0.0
JS creates a JavaScript expression which is evaluated by the database when running the query.
func JSON ¶ added in v1.0.0
func JSON(args ...interface{}) Term
JSON parses 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 Line ¶ added in v0.5.0
func Line(args ...interface{}) Term
Line constructs a geometry object of type Line. The line can be specified in one of two ways:
- Two or more two-item arrays, specifying longitude and latitude numbers of the line's vertices;
- Two or more Point objects specifying the line's vertices.
func Literal ¶
func Literal(args ...interface{}) Term
Literal replaces an object in a field instead of merging it with an existing object in a merge or update operation.
func Lt ¶
func Lt(args ...interface{}) Term
Lt returns true if the first value is less than the second.
func Map ¶ added in v0.6.0
func Map(args ...interface{}) Term
Map transform each element of the sequence by applying the given mapping function. It takes two arguments, a sequence and a function of type `func (r.Term) interface{}`.
For example this query doubles each element in an array:
r.Map([]int{1,3,6}, func (row r.Term) interface{} { return row.Mul(2) })
Example (MultipleSequences) ¶
Sum the elements of three sequences.
var sequence1 = []int{100, 200, 300, 400} var sequence2 = []int{10, 20, 30, 40} var sequence3 = []int{1, 2, 3, 4} cur, err := Map(sequence1, sequence2, sequence3, func(val1, val2, val3 Term) Term { return val1.Add(val2).Add(val3) }).Run(session) if err != nil { fmt.Print(err) return } var res []int err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output: [111 222 333 444]
func Max ¶
func Max(args ...interface{}) Term
Max 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 MaxIndex ¶
func MaxIndex(index interface{}, args ...interface{}) Term
MaxIndex 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 Min ¶
func Min(args ...interface{}) Term
Min 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 MinIndex ¶
func MinIndex(index interface{}, args ...interface{}) Term
MinIndex 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 MockAnything ¶
func MockAnything() Term
MockAnything can be used in place of any term, this is useful when you want mock similar queries or queries that you don't quite know the exact structure of.
func MultiGroup ¶
func MultiGroup(fieldOrFunctions ...interface{}) Term
MultiGroup 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.
Unlike Group single documents can be assigned to multiple groups, similar to the behavior of multi-indexes. When the grouping value is an array, documents will be placed in each group that corresponds to the elements of the array. If the array is empty the row will be ignored.
func MultiGroupByIndex ¶
func MultiGroupByIndex(index interface{}, fieldOrFunctions ...interface{}) Term
MultiGroupByIndex 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.
Unlike Group single documents can be assigned to multiple groups, similar to the behavior of multi-indexes. When the grouping value is an array, documents will be placed in each group that corresponds to the elements of the array. If the array is empty the row will be ignored.
func Now ¶
func Now(args ...interface{}) Term
Now returns a time object representing the current time in UTC
func Object ¶
func Object(args ...interface{}) Term
Object creates an object from a list of key-value pairs, where the keys must be strings.
func Point ¶ added in v0.5.0
func Point(lon, lat interface{}) Term
Point constructs a geometry object of type Point. The point is specified by two floating point numbers, the longitude (−180 to 180) and latitude (−90 to 90) of the point on a perfect sphere.
func Polygon ¶ added in v0.5.0
func Polygon(args ...interface{}) Term
Polygon constructs a geometry object of type Polygon. The Polygon can be specified in one of two ways:
- Three or more two-item arrays, specifying longitude and latitude numbers of the polygon's vertices;
- Three or more Point objects specifying the polygon's vertices.
func Random ¶
func Random(args ...interface{}) Term
Random generates a random number between given (or implied) bounds. Random takes zero, one or two arguments.
With zero arguments, the result will be a floating-point number in the range [0,1).
With one argument x, the result will be in the range [0,x), and will be an integer unless the Float option is set to true. Specifying a floating point number without the Float option will raise an error.
With two arguments x and y, the result will be in the range [x,y), and will be an integer unless the Float option is set to true. If x and y are equal an error will occur, unless the floating-point option has been specified, in which case x will be returned. Specifying a floating point number without the float option will raise an error.
Note: Any integer responses can be be coerced to floating-points, when unmarshaling to a Go floating-point type. 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 Range ¶ added in v0.6.0
func Range(args ...interface{}) Term
Range generates a stream of sequential integers in a specified range. It accepts 0, 1, or 2 arguments, all of which should be numbers.
func RawQuery ¶ added in v1.4.0
RawQuery creates a new query from a JSON string, this bypasses any encoding done by GoRethink. The query should not contain the query type or any options as this should be handled using the normal driver API.
THis query will only work if this is the only term in the query.
Example ¶
Execute a raw JSON query
cur, err := RawQuery([]byte(`"hello world"`)).Run(session) if err != nil { fmt.Print(err) return } var res interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } jsonPrint(res)
Output: "hello world"
func Round ¶ added in v1.1.0
func Round(args ...interface{}) Term
Round causes the input number to be rounded the given value to the nearest whole integer.
func Sum ¶
func Sum(args ...interface{}) Term
Sum returns the sum of 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 Table ¶
Table selects all documents in a table. This command can be chained with other commands to do further processing on the data.
There are two optional arguments.
- useOutdated: if true, this allows potentially out-of-date data to be returned, with potentially faster reads. It also allows you to perform reads from a secondary replica if a primary has failed. Default false.
- identifierFormat: possible values are name and uuid, with a default of name. If set to uuid, then system tables will refer to servers, databases and tables by UUID rather than name. (This only has an effect when used with system tables.)
func TableCreate ¶ added in v1.1.4
func TableCreate(name interface{}, optArgs ...TableCreateOpts) Term
TableCreate creates a table. A RethinkDB table is a collection of JSON documents.
Note: Only alphanumeric characters and underscores are valid for the table name.
func TableDrop ¶ added in v1.1.4
func TableDrop(args ...interface{}) Term
TableDrop deletes a table. The table and all its data will be deleted.
func TableList ¶ added in v1.1.4
func TableList(args ...interface{}) Term
TableList lists all table names in a database.
func UUID ¶ added in v0.5.0
func UUID(args ...interface{}) Term
UUID returns a UUID (universally unique identifier), a string that can be used as a unique ID. If a string is passed to uuid as an argument, the UUID will be deterministic, derived from the string’s SHA-1 hash.
func UnionWithOpts ¶
UnionWithOpts like Union concatenates two sequences however allows for optional arguments to be passed.
func Wait
deprecated
added in
v0.6.0
Wait for a table or all the tables in a database to be ready. A table may be temporarily unavailable after creation, rebalancing or reconfiguring. The wait command blocks until the given table (or database) is fully up to date.
Deprecated: This function is not supported by RethinkDB 2.3 and above.
func (Term) AtIndex ¶ added in v0.5.0
AtIndex gets a single field from an object or the nth element from a sequence.
func (Term) Avg ¶
Avg returns the average of 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
Between gets all documents between two keys. Accepts three optional arguments: index, leftBound, and rightBound. 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). leftBound or rightBound may be set to open or closed to indicate whether or not to include that endpoint of the range (by default, leftBound is closed and rightBound is open).
You may also use the special constants r.minval and r.maxval for boundaries, which represent “less than any index key” and “more than any index key” respectively. For instance, if you use r.minval as the lower key, then between will return all documents whose primary keys (or indexes) are less than the specified upper key.
func (Term) Branch ¶ added in v1.1.0
Branch evaluates 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 (Term) Ceil ¶ added in v1.1.0
Ceil rounds the given value up, returning the smallest integer value greater than or equal to the given value (the value’s ceiling).
func (Term) ChangeAt ¶
ChangeAt changes a value in an array at a given index. Returns the modified array.
func (Term) Changes ¶
func (t Term) Changes(optArgs ...ChangesOpts) Term
Changes returns an infinite stream of objects representing changes to a query.
func (Term) CoerceTo ¶
CoerceTo 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 ¶
ConcatMap concatenates one or more elements into a single sequence using a mapping function. ConcatMap works in a similar fashion to Map, applying the given function to each element in a sequence, but it will always return a single sequence.
func (Term) Config ¶ added in v0.6.0
Config can be used to read and/or update the configurations for individual tables or databases.
func (Term) Contains ¶
Contains 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 ¶
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 ¶
Date returns a new time object only based on the day, month and year (ie. the same day at 00:00).
func (Term) DayOfWeek ¶
DayOfWeek returns 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 ¶
DayOfYear returns the day of the year of a time object as a number between 1 and 366 (following ISO 8601 standard).
func (Term) Default ¶
Default handles 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.)
Example ¶
Suppose we want to retrieve the titles and authors of the table posts. In the case where the author field is missing or null, we want to retrieve the string "Anonymous".
cur, err := DB("examples").Table("posts").Map(map[string]interface{}{ "title": Row.Field("title"), "author": Row.Field("author").Default("Anonymous"), }).Run(session) if err != nil { fmt.Print(err) return } var res map[string]interface{} err = cur.One(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) Delete ¶
func (t Term) Delete(optArgs ...DeleteOpts) Term
Delete one or more documents from a table.
Example ¶
Delete a single document from the table posts.
resp, err := DB("examples").Table("posts").Get(2).Delete().RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row deleted", resp.Deleted)
Output: 1 row deleted
Example (Many) ¶
Delete all comments where the field status is published
resp, err := DB("examples").Table("posts").Filter(map[string]interface{}{ "status": "published", }).Delete().RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d rows deleted", resp.Deleted)
Output: 4 rows deleted
func (Term) DeleteAt ¶
DeleteAt removes an element from an array at a given index. Returns the modified array.
func (Term) Difference ¶
Difference removes the elements of one array from another array.
func (Term) Distance ¶ added in v0.5.0
func (t Term) Distance(point interface{}, optArgs ...DistanceOpts) Term
Distance calculates the Haversine distance between two points. At least one of the geometry objects specified must be a point.
func (Term) Distinct ¶
func (t Term) Distinct(optArgs ...DistinctOpts) Term
Distinct removes duplicate elements from the sequence.
func (Term) Do ¶
Do evaluates 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) During ¶
func (t Term) During(startTime, endTime interface{}, optArgs ...DuringOpts) Term
During returns true if a time is between two other times (by default, inclusive for the start, exclusive for the end).
func (Term) EqJoin ¶
func (t Term) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) Term
EqJoin is 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 QueryExecutor, optArgs ...ExecOpts) error
Exec runs the query but does not return the result. Exec will still wait for the response to be received unless the NoReply field is true.
err := r.DB("database").Table("table").Insert(doc).Exec(sess, r.ExecOpts{ NoReply: true, })
func (Term) Field ¶
Field gets 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.
Example ¶
Get john's age
cur, err := DB("examples").Table("users").Get("john").Field("age").Run(session) if err != nil { fmt.Print(err) return } var res int err = cur.One(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output: 19
func (Term) Fill ¶ added in v0.5.0
Fill converts a Line object into a Polygon object. If the last point does not specify the same coordinates as the first point, polygon will close the polygon by connecting them
func (Term) Filter ¶
func (t Term) Filter(f interface{}, optArgs ...FilterOpts) Term
Filter gets 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.
Example ¶
Get all users who are 30 years old.
// Fetch the row from the database res, err := DB("examples").Table("users").Filter(map[string]interface{}{ "age": 30, }).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() // Scan query result into the person variable var users []interface{} err = res.All(&users) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Printf("%d users", len(users))
Output: 2 users
Example (Function) ¶
Retrieve all users who have a gmail account (whose field email ends with @gmail.com).
// Fetch the row from the database res, err := DB("examples").Table("users").Filter(func(user Term) Term { return user.Field("email").Match("@gmail.com$") }).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() // Scan query result into the person variable var users []interface{} err = res.All(&users) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Printf("%d users", len(users))
Output: 1 users
Example (Row) ¶
Get all users who are more than 25 years old.
// Fetch the row from the database res, err := DB("examples").Table("users").Filter(Row.Field("age").Gt(25)).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() // Scan query result into the person variable var users []interface{} err = res.All(&users) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Printf("%d users", len(users))
Output: 3 users
func (Term) Floor ¶ added in v1.1.0
Floor rounds the given value down, returning the largest integer value less than or equal to the given value (the value’s floor).
func (Term) Fold ¶
Fold applies a function to a sequence in order, maintaining state via an accumulator. The Fold command returns either a single value or a new sequence.
In its first form, Fold operates like Reduce, returning a value by applying a combining function to each element in a sequence, passing the current element and the previous reduction result to the function. However, Fold has the following differences from Reduce:
- it is guaranteed to proceed through the sequence from first element to last.
- it passes an initial base value to the function with the first element in place of the previous reduction result.
In its second form, Fold operates like ConcatMap, returning a new sequence rather than a single value. When an emit function is provided, Fold will:
- proceed through the sequence in order and take an initial base value, as above.
- for each element in the sequence, call both the combining function and a separate emitting function with the current element and previous reduction result.
- optionally pass the result of the combining function to the emitting function.
If provided, the emitting function must return a list.
Example ¶
Concatenate words from a list.
cur, err := Expr([]string{"a", "b", "c"}).Fold("", func(acc, word Term) Term { return acc.Add(Branch(acc.Eq(""), "", ", ")).Add(word) }).Run(session) if err != nil { fmt.Print(err) return } var res string err = cur.One(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output: a, b, c
func (Term) ForEach ¶
ForEach loops over a sequence, evaluating the given write query for each element.
It takes one argument of type `func (r.Term) interface{}`, for example clones a table:
r.Table("table").ForEach(func (row r.Term) interface{} { return r.Table("new_table").Insert(row) })
func (Term) Get ¶
Get gets a document by primary key. If nothing was found, RethinkDB will return a nil value.
Example ¶
Find a document by ID.
// Fetch the row from the database res, err := DB("examples").Table("heroes").Get(2).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() if res.IsNil() { fmt.Print("Row not found") return } var hero map[string]interface{} err = res.One(&hero) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Print(hero["name"])
Output: Superman
Example (Merge) ¶
Find a document and merge another document with it.
// Fetch the row from the database res, err := DB("examples").Table("heroes").Get(4).Merge(map[string]interface{}{ "powers": []string{"speed"}, }).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() if res.IsNil() { fmt.Print("Row not found") return } var hero map[string]interface{} err = res.One(&hero) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Printf("%s: %v", hero["name"], hero["powers"])
Output: The Flash: [speed]
func (Term) GetAll ¶
GetAll gets all documents where the given value matches the value of the primary index. Multiple values can be passed this function if you want to select multiple documents. If the documents you are fetching have composite keys then each argument should be a slice. For more information see the examples.
Example ¶
Find a document by ID.
// Fetch the row from the database res, err := DB("examples").Table("heroes").GetAll(2).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() if res.IsNil() { fmt.Print("Row not found") return } var hero map[string]interface{} err = res.One(&hero) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Print(hero["name"])
Output: Superman
Example (Multiple) ¶
Find a document by ID.
// Fetch the row from the database res, err := DB("examples").Table("heroes").GetAll(1, 2).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() var heroes []map[string]interface{} err = res.All(&heroes) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Print(heroes[0]["name"])
Output: Superman
Example (OptArgs) ¶
Find all document with an indexed value.
// Fetch the row from the database res, err := DB("examples").Table("heroes").GetAll("man_of_steel").OptArgs(GetAllOpts{ Index: "code_name", }).Run(session) if err != nil { fmt.Print(err) return } defer res.Close() if res.IsNil() { fmt.Print("Row not found") return } var hero map[string]interface{} err = res.One(&hero) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Print(hero["name"])
Output: Superman
func (Term) GetAllByIndex ¶
GetAllByIndex gets all documents where the given value matches the value of the requested index.
Example ¶
Find all document with an indexed value.
// Fetch the row from the database res, err := DB("examples").Table("heroes").GetAllByIndex("code_name", "man_of_steel").Run(session) if err != nil { fmt.Print(err) return } defer res.Close() if res.IsNil() { fmt.Print("Row not found") return } var hero map[string]interface{} err = res.One(&hero) if err != nil { fmt.Printf("Error scanning database result: %s", err) return } fmt.Print(hero["name"])
Output: Superman
func (Term) GetIntersecting ¶ added in v0.5.0
func (t Term) GetIntersecting(args interface{}, optArgs ...GetIntersectingOpts) Term
GetIntersecting gets all documents where the given geometry object intersects the geometry object of the requested geospatial index.
func (Term) GetNearest ¶ added in v0.5.0
func (t Term) GetNearest(point interface{}, optArgs ...GetNearestOpts) Term
GetNearest gets all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).
func (Term) Grant ¶
Grant modifies access permissions for a user account, globally or on a per-database or per-table basis.
func (Term) Group ¶
Group 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.
Example ¶
Group games by player.
cur, err := DB("examples").Table("games").Group("player").Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) GroupByIndex ¶
GroupByIndex 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.
Example ¶
Group games by the index type.
cur, err := DB("examples").Table("games").GroupByIndex("type").Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) HasFields ¶
HasFields tests 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) InTimezone ¶
InTimezone 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) Includes ¶ added in v0.5.0
Includes tests whether a geometry object is completely contained within another. When applied to a sequence of geometry objects, includes acts as a filter, returning a sequence of objects from the sequence that include the argument.
func (Term) IndexCreate ¶
func (t Term) IndexCreate(name interface{}, optArgs ...IndexCreateOpts) Term
IndexCreate creates a new secondary index on a table. Secondary indexes improve the speed of many read queries at the slight cost of increased storage space and decreased write performance.
IndexCreate supports the creation of the following types of indexes, to create indexes using arbitrary expressions use IndexCreateFunc.
- Simple indexes based on the value of a single field.
- Geospatial indexes based on indexes of geometry objects, created when the geo optional argument is true.
Example ¶
Create a simple index based on the field name.
// Setup database DB("examples").TableDrop("table").Run(session) DB("examples").TableCreate("table").Run(session) response, err := DB("examples").Table("table").IndexCreate("name").RunWrite(session) if err != nil { Log.Fatalf("Error creating index: %s", err) } fmt.Printf("%d index created", response.Created)
Output: 1 index created
Example (Compound) ¶
Create a compound index based on the fields first_name and last_name.
// Setup database DB("examples").TableDrop("table").Run(session) DB("examples").TableCreate("table").Run(session) response, err := DB("examples").Table("table").IndexCreateFunc("full_name", func(row Term) interface{} { return []interface{}{row.Field("first_name"), row.Field("last_name")} }).RunWrite(session) if err != nil { Log.Fatalf("Error creating index: %s", err) } fmt.Printf("%d index created", response.Created)
Output: 1 index created
func (Term) IndexCreateFunc ¶
func (t Term) IndexCreateFunc(name, indexFunction interface{}, optArgs ...IndexCreateOpts) Term
IndexCreateFunc creates a new secondary index on a table. Secondary indexes improve the speed of many read queries at the slight cost of increased storage space and decreased write performance. The function takes a index name and RQL term as the index value , the term can be an anonymous function or a binary representation obtained from the function field of indexStatus.
It supports the creation of the following types of indexes.
- Simple indexes based on the value of a single field where the index has a different name to the field.
- Compound indexes based on multiple fields.
- Multi indexes based on arrays of values, created when the multi optional argument is true.
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.
func (Term) IndexStatus ¶
IndexStatus gets 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 ¶
IndexWait waits 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) InnerJoin ¶
InnerJoin 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 documents into a table. Accepts a single document or an array of documents.
Example (GeneratedKey) ¶
Insert a document without a defined primary key into the table posts where the primary key is id.
type Post struct { Title string `gorethink:"title"` Content string `gorethink:"content"` } resp, err := DB("examples").Table("posts").Insert(map[string]interface{}{ "title": "Lorem ipsum", "content": "Dolor sit amet", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row inserted, %d key generated", resp.Inserted, len(resp.GeneratedKeys))
Output: 1 row inserted, 1 key generated
Example (Map) ¶
Insert a document into the table posts using a map.
resp, err := DB("examples").Table("posts").Insert(map[string]interface{}{ "id": 2, "title": "Lorem ipsum", "content": "Dolor sit amet", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row inserted", resp.Inserted)
Output: 1 row inserted
Example (Multiple) ¶
Insert multiple documents into the table posts.
resp, err := DB("examples").Table("posts").Insert([]interface{}{ map[string]interface{}{ "title": "Lorem ipsum", "content": "Dolor sit amet", }, map[string]interface{}{ "title": "Lorem ipsum", "content": "Dolor sit amet", }, }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d rows inserted", resp.Inserted)
Output: 2 rows inserted
Example (Struct) ¶
Insert a document into the table posts using a struct.
type Post struct { ID int `gorethink:"id"` Title string `gorethink:"title"` Content string `gorethink:"content"` } resp, err := DB("examples").Table("posts").Insert(Post{ ID: 1, Title: "Lorem ipsum", Content: "Dolor sit amet", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row inserted", resp.Inserted)
Output: 1 row inserted
Example (Upsert) ¶
Insert a document into the table posts, replacing the document if it already exists.
resp, err := DB("examples").Table("posts").Insert(map[string]interface{}{ "id": 1, "title": "Lorem ipsum 2", }, InsertOpts{ Conflict: "replace", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 1 row replaced
func (Term) InsertAt ¶
InsertAt inserts a value in to an array at a given index. Returns the modified array.
func (Term) Intersects ¶ added in v0.5.0
Intersects tests whether two geometry objects intersect with one another. When applied to a sequence of geometry objects, intersects acts as a filter, returning a sequence of objects from the sequence that intersect with the argument.
func (Term) Map ¶
Map transforms each element of the sequence by applying the given mapping function. It takes one argument of type `func (r.Term) interface{}`.
For example this query doubles each element in an array:
r.Expr([]int{1,3,6}).Map(func (row r.Term) interface{} { return row.Mul(2) })
Example ¶
Return the first five squares.
cur, err := Expr([]int{1, 2, 3, 4, 5}).Map(func(val Term) Term { return val.Mul(val) }).Run(session) if err != nil { fmt.Print(err) return } var res []int err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output: [1 4 9 16 25]
func (Term) Match ¶
Match matches against a regular expression. If no match is found, returns null. If there is a match then an object with the following fields is returned:
str: The matched string start: The matched string’s start end: The matched string’s end groups: The capture groups defined with parentheses
Accepts RE2 syntax (https://code.google.com/p/re2/wiki/Syntax). You can enable case-insensitive matching by prefixing the regular expression with (?i). See the linked RE2 documentation for more flags.
The match command does not support backreferences.
func (Term) Max ¶
Max 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) MaxIndex ¶ added in v0.6.0
MaxIndex 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 ¶
Merge merges 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 ¶
Min 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) MinIndex ¶ added in v0.6.0
MinIndex 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) MockAnything ¶
func (Term) Month ¶
Month returns 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) MultiGroup ¶ added in v1.0.0
MultiGroup 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.
Unlike Group single documents can be assigned to multiple groups, similar to the behavior of multi-indexes. When the grouping value is an array, documents will be placed in each group that corresponds to the elements of the array. If the array is empty the row will be ignored.
Example ¶
Suppose that the table games2 has the following data:
[ { id: 1, matches: {'a': [1, 2, 3], 'b': [4, 5, 6]} }, { id: 2, matches: {'b': [100], 'c': [7, 8, 9]} }, { id: 3, matches: {'a': [10, 20], 'c': [70, 80]} } ]
Using MultiGroup we can group data by match A, B or C.
cur, err := DB("examples").Table("games2").MultiGroup(Row.Field("matches").Keys()).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) MultiGroupByIndex ¶ added in v1.0.0
MultiGroupByIndex 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.
Unlike Group single documents can be assigned to multiple groups, similar to the behavior of multi-indexes. When the grouping value is an array, documents will be placed in each group that corresponds to the elements of the array. If the array is empty the row will be ignored.
func (Term) OffsetsOf ¶ added in v0.7.0
OffsetsOf gets the indexes of an element in a sequence. If the argument is a predicate, get the indexes of all elements matching it.
func (Term) OrderBy ¶
OrderBy sorts the sequence by document values of the given key(s). To specify the ordering, wrap the attribute with either r.Asc or r.Desc (defaults to ascending).
Sorting without an index requires the server to hold the sequence in memory, and is limited to 100,000 documents (or the setting of the ArrayLimit option for run). Sorting with an index can be done on arbitrarily large tables, or after a between command using the same index.
Example (Compound) ¶
You can efficiently order using multiple fields by using a compound index. For example order by date and title.
cur, err := DB("examples").Table("posts").OrderBy(OrderByOpts{ Index: Desc("dateAndTitle"), }).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
Example (Index) ¶
Order all the posts using the index date.
cur, err := DB("examples").Table("posts").OrderBy(OrderByOpts{ Index: "date", }).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
Example (IndexDesc) ¶
Order all the posts using the index date in descending order.
cur, err := DB("examples").Table("posts").OrderBy(OrderByOpts{ Index: Desc("date"), }).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
Example (Multiple) ¶
If you have a sequence with fewer documents than the arrayLimit, you can order it by multiple fields without an index.
cur, err := DB("examples").Table("posts").OrderBy( "title", OrderByOpts{Index: Desc("date")}, ).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
Example (MultipleWithIndex) ¶
Notice that an index ordering always has highest precedence. The following query orders posts by date, and if multiple posts were published on the same date, they will be ordered by title.
cur, err := DB("examples").Table("posts").OrderBy( "title", OrderByOpts{Index: Desc("date")}, ).Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) OuterJoin ¶
OuterJoin 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 ¶
Pluck plucks out one or more attributes from either an object or a sequence of objects (projection).
func (Term) PolygonSub ¶ added in v0.5.0
PolygonSub "punches a hole" out of the parent polygon using the polygon passed to the function.
polygon1.PolygonSub(polygon2) -> polygon
In the example above polygon2 must be completely contained within polygon1 and must have no holes itself (it must not be the output of polygon_sub itself).
func (Term) ReadAll ¶
func (t Term) ReadAll(dest interface{}, s QueryExecutor, optArgs ...RunOpts) error
ReadAll is a shortcut method that runs the query on the given connection and reads all of the responses from the cursor before closing it.
It returns any errors encountered from running the query or reading the responses
func (Term) ReadOne ¶
func (t Term) ReadOne(dest interface{}, s QueryExecutor, optArgs ...RunOpts) error
ReadOne is a shortcut method that runs the query on the given connection and reads one response from the cursor before closing it.
It returns any errors encountered from running the query or reading the response
func (Term) Rebalance ¶ added in v0.6.0
Rebalance rebalances the shards of a table. When called on a database, all the tables in that database will be rebalanced.
func (Term) Reconfigure ¶ added in v0.6.0
func (t Term) Reconfigure(optArgs ...ReconfigureOpts) Term
Reconfigure a table's sharding and replication.
func (Term) Reduce ¶
Reduce produces a single value from a sequence through repeated application of a reduction function
It takes one argument of type `func (r.Term, r.Term) interface{}`, for example this query sums all elements in an array:
r.Expr([]int{1,3,6}).Reduce(func (left, right r.Term) interface{} { return left.Add(right) })
Example ¶
Return the number of documents in the table posts.
cur, err := DB("examples").Table("posts"). Map(func(doc Term) interface{} { return 1 }). Reduce(func(left, right Term) interface{} { return left.Add(right) }). Run(session) if err != nil { fmt.Print(err) return } var res int err = cur.One(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) Replace ¶
func (t Term) Replace(arg interface{}, optArgs ...ReplaceOpts) Term
Replace documents in a table. Accepts a JSON document or a ReQL expression, and replaces the original document with the new one. The new document must have the same primary key as the original document.
func (Term) Round ¶ added in v1.1.0
Round causes the input number to be rounded the given value to the nearest whole integer.
func (Term) Run ¶
func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error)
Run runs a query using the given connection.
rows, err := query.Run(sess) if err != nil { // error } var doc MyDocumentType for rows.Next(&doc) { // Do something with document }
func (Term) RunWrite ¶
func (t Term) RunWrite(s QueryExecutor, 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...).
If an error occurs when running the write query the first error is returned.
res, err := r.DB("database").Table("table").Insert(doc).RunWrite(sess)
func (Term) Sample ¶
Sample selects a given number of elements from a sequence with uniform random distribution. Selection is done without replacement.
func (Term) Seconds ¶
Seconds returns the seconds in a time object as a number between 0 and 59.999 (double precision).
func (Term) SetDifference ¶
SetDifference removes the elements of one array from another and return them as a set (an array with distinct values).
func (Term) SetInsert ¶
SetInsert adds a value to an array and return it as a set (an array with distinct values).
func (Term) SetIntersection ¶
SetIntersection calculates the intersection of two arrays returning values that occur in both of them as a set (an array with distinct values).
func (Term) SetUnion ¶
SetUnion adds several values to an array and return it as a set (an array with distinct values).
func (Term) SpliceAt ¶
SpliceAt inserts several values in to an array at a given index. Returns the modified array.
func (Term) Split ¶
Split 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) Sum ¶
Sum returns the sum of 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 ¶
Sync ensures that writes on a given table are written to permanent storage. Queries that specify soft durability 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 ¶
Table selects all documents in a table. This command can be chained with other commands to do further processing on the data.
There are two optional arguments.
- useOutdated: if true, this allows potentially out-of-date data to be returned, with potentially faster reads. It also allows you to perform reads from a secondary replica if a primary has failed. Default false.
- identifierFormat: possible values are name and uuid, with a default of name. If set to uuid, then system tables will refer to servers, databases and tables by UUID rather than name. (This only has an effect when used with system tables.)
func (Term) TableCreate ¶
func (t Term) TableCreate(name interface{}, optArgs ...TableCreateOpts) Term
TableCreate creates a table. A RethinkDB table is a collection of JSON documents.
Note: Only alphanumeric characters and underscores are valid for the table name.
Example ¶
Create a table named "table" with the default settings.
// Setup database DB("examples").TableDrop("table").Run(session) response, err := DB("examples").TableCreate("table").RunWrite(session) if err != nil { Log.Fatalf("Error creating table: %s", err) } fmt.Printf("%d table created", response.TablesCreated)
Output: 1 table created
func (Term) TimeOfDay ¶
TimeOfDay returns the number of seconds elapsed since the beginning of the day stored in the time object.
func (Term) ToEpochTime ¶
ToEpochTime converts a time object to its epoch time.
func (Term) ToGeoJSON ¶ added in v1.0.0
ToGeoJSON converts a ReQL geometry object to a GeoJSON object.
func (Term) Ungroup ¶
Ungroup takes a grouped stream or grouped data and turns it into an array of objects representing the groups. Any commands chained after Ungroup will operate on this array, rather than operating on each group individually. This is useful if you want to e.g. order the groups by the value of their reduction.
Example ¶
Ungrouping grouped data.
cur, err := DB("examples").Table("games"). Group("player"). Max("points").Field("points"). Ungroup(). Run(session) if err != nil { fmt.Print(err) return } var res []interface{} err = cur.All(&res) if err != nil { fmt.Print(err) return } fmt.Print(res)
Output:
func (Term) UnionWithOpts ¶
UnionWithOpts like Union concatenates two sequences however allows for optional arguments to be passed.
func (Term) Update ¶
func (t Term) Update(arg interface{}, optArgs ...UpdateOpts) Term
Update JSON documents in a table. Accepts a JSON document, a ReQL expression, or a combination of the two. You can pass options like returnChanges that will return the old and new values of the row you have modified.
Example ¶
Update the status of the post with id of 1 to published.
resp, err := DB("examples").Table("posts").Get(2).Update(map[string]interface{}{ "status": "published", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 1 row replaced
Example (All) ¶
Update the status of all posts to published.
resp, err := DB("examples").Table("posts").Update(map[string]interface{}{ "status": "published", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 4 row replaced
Example (Increment) ¶
Increment the field view of the post with id of 1. If the field views does not exist, it will be set to 0.
resp, err := DB("examples").Table("posts").Get(1).Update(map[string]interface{}{ "views": Row.Field("views").Add(1).Default(0), }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 1 row replaced
Example (Nested) ¶
Update bob's cell phone number.
resp, err := DB("examples").Table("users").Get("bob").Update(map[string]interface{}{ "contact": map[string]interface{}{ "phone": "408-555-4242", }, }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 1 row replaced
Example (SoftDurability) ¶
Update the status of the post with id of 1 using soft durability.
resp, err := DB("examples").Table("posts").Get(2).Update(map[string]interface{}{ "status": "draft", }, UpdateOpts{ Durability: "soft", }).RunWrite(session) if err != nil { fmt.Print(err) return } fmt.Printf("%d row replaced", resp.Replaced)
Output: 1 row replaced
func (Term) Wait ¶ added in v0.6.0
Wait for a table or all the tables in a database to be ready. A table may be temporarily unavailable after creation, rebalancing or reconfiguring. The wait command blocks until the given table (or database) is fully up to date.
func (Term) WithFields ¶
WithFields 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 ¶
Without is the opposite of pluck; takes an object or a sequence of objects, and returns them with the specified paths removed.
type UnionOpts ¶
type UnionOpts struct {
Interleave interface{} `gorethink:"interleave,omitempty"`
}
UnionOpts contains the optional arguments for the Slice term
type UpdateOpts ¶
type UpdateOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnChanges interface{} `gorethink:"return_changes,omitempty"` NonAtomic interface{} `gorethink:"non_atomic,omitempty"` Conflict interface{} `gorethink:"conflict,omitempty"` }
UpdateOpts contains the optional arguments for the Update term
type WaitOpts ¶ added in v0.7.0
type WaitOpts struct { WaitFor interface{} `gorethink:"wait_for,omitempty"` Timeout interface{} `gorethink:"timeout,omitempty"` }
WaitOpts contains the optional arguments for the Wait term.
type WriteResponse ¶
type WriteResponse struct { Errors int `gorethink:"errors"` Inserted int `gorethink:"inserted"` Updated int `gorethink:"updated"` Unchanged int `gorethink:"unchanged"` Replaced int `gorethink:"replaced"` Renamed int `gorethink:"renamed"` Skipped int `gorethink:"skipped"` Deleted int `gorethink:"deleted"` Created int `gorethink:"created"` DBsCreated int `gorethink:"dbs_created"` TablesCreated int `gorethink:"tables_created"` Dropped int `gorethink:"dropped"` DBsDropped int `gorethink:"dbs_dropped"` TablesDropped int `gorethink:"tables_dropped"` GeneratedKeys []string `gorethink:"generated_keys"` FirstError string `gorethink:"first_error"` // populated if Errors > 0 ConfigChanges []ChangeResponse `gorethink:"config_changes"` Changes []ChangeResponse }
WriteResponse is a helper type used when dealing with the response of a write query. It is also returned by the RunWrite function.
Source Files ¶
- cluster.go
- connection.go
- connection_handshake.go
- connection_helper.go
- cursor.go
- doc.go
- errors.go
- gorethink.go
- host.go
- mock.go
- node.go
- pool.go
- pseudotypes.go
- query.go
- query_admin.go
- query_aggregation.go
- query_control.go
- query_db.go
- query_geospatial.go
- query_helpers.go
- query_join.go
- query_manipulation.go
- query_math.go
- query_select.go
- query_string.go
- query_table.go
- query_time.go
- query_transformation.go
- query_write.go
- session.go
- utils.go