Documentation ¶
Overview ¶
Go driver for RethinkDB
Current supported RethinkDB version: 1.11 For more in depth information on how to use RethinkDB check out the API docs at http://rethinkdb.com/api
Example ¶
package main import ( "fmt" r "github.com/dancannon/gorethink" "log" "os" ) var session *r.Session var url string func init() { // Needed for wercker. By default url is "localhost:28015" url = os.Getenv("WERCKER_RETHINKDB_URL") if url == "" { url = "localhost:28015" } } func main() { session, err := r.Connect(map[string]interface{}{ "address": url, }) if err != nil { log.Fatalln(err.Error()) } row, err := r.Expr("Hello World").RunRow(session) if err != nil { log.Fatalln(err.Error()) } var response string err = row.Scan(&response) if err != nil { log.Fatalln(err.Error()) } fmt.Println(response) }
Output:
Index ¶
- Variables
- func TestOnBorrow(c *Connection, t time.Time) error
- type BetweenOpts
- type CloseOpts
- type Conn
- type Connection
- type DeleteOpts
- type DuringOpts
- type EqJoinOpts
- type ISO8601Opts
- type IndexCreateOpts
- type InsertOpts
- type OptArgs
- type Pool
- type ReplaceOpts
- type ResultRow
- type ResultRows
- func (r *ResultRows) Close() error
- func (r *ResultRows) Count() (count int, more bool)
- func (r *ResultRows) Err() error
- func (r *ResultRows) IsNil() bool
- func (r *ResultRows) Next() bool
- func (r *ResultRows) Profile() interface{}
- func (r *ResultRows) Scan(dest interface{}) error
- func (r *ResultRows) ScanAll(dest interface{}) error
- type RqlClientError
- type RqlCompileError
- type RqlConnectionError
- type RqlDriverError
- type RqlRuntimeError
- type RqlTerm
- func Add(args ...interface{}) RqlTerm
- func And(args ...interface{}) RqlTerm
- func April() RqlTerm
- func Asc(arg interface{}) RqlTerm
- func August() RqlTerm
- func Avg(arg interface{}) RqlTerm
- func Branch(test, trueBranch, falseBranch interface{}) RqlTerm
- func Count() RqlTerm
- func Db(name interface{}) RqlTerm
- func DbCreate(name interface{}) RqlTerm
- func DbDrop(name interface{}) RqlTerm
- func DbList() RqlTerm
- func December() RqlTerm
- func Desc(arg interface{}) RqlTerm
- func Div(args ...interface{}) RqlTerm
- func Do(args ...interface{}) RqlTerm
- func EpochTime(epochtime interface{}) RqlTerm
- func Eq(args ...interface{}) RqlTerm
- func Error(message interface{}) RqlTerm
- func Expr(value interface{}) RqlTerm
- func February() RqlTerm
- func Friday() RqlTerm
- func Ge(args ...interface{}) RqlTerm
- func Gt(args ...interface{}) RqlTerm
- func ISO8601(date interface{}, optArgs ...ISO8601Opts) RqlTerm
- func January() RqlTerm
- func Js(js interface{}) RqlTerm
- func Json(json interface{}) RqlTerm
- func July() RqlTerm
- func June() RqlTerm
- func Le(args ...interface{}) RqlTerm
- func Literal(args ...interface{}) RqlTerm
- func Lt(args ...interface{}) RqlTerm
- func March() RqlTerm
- func May() RqlTerm
- func Mod(args ...interface{}) RqlTerm
- func Monday() RqlTerm
- func Mul(args ...interface{}) RqlTerm
- func Ne(args ...interface{}) RqlTerm
- func Not(args ...interface{}) RqlTerm
- func November() RqlTerm
- func Now() RqlTerm
- func October() RqlTerm
- func Or(args ...interface{}) RqlTerm
- func Saturday() RqlTerm
- func September() RqlTerm
- func Sub(args ...interface{}) RqlTerm
- func Sum(arg interface{}) RqlTerm
- func Sunday() RqlTerm
- func Table(name interface{}, optArgs ...TableOpts) RqlTerm
- func Thursday() RqlTerm
- func Time(year, month, day, hour, min, sec interface{}, tz string) RqlTerm
- func Tuesday() RqlTerm
- func Wednesday() RqlTerm
- func (t RqlTerm) Add(args ...interface{}) RqlTerm
- func (t RqlTerm) And(args ...interface{}) RqlTerm
- func (t RqlTerm) Append(arg interface{}) RqlTerm
- func (t RqlTerm) Between(lowerKey, upperKey interface{}, optArgs ...BetweenOpts) RqlTerm
- func (t RqlTerm) ChangeAt(index, value interface{}) RqlTerm
- func (t RqlTerm) CoerceTo(typeName interface{}) RqlTerm
- func (t RqlTerm) ConcatMap(f interface{}) RqlTerm
- func (t RqlTerm) Contains(args ...interface{}) RqlTerm
- func (t RqlTerm) Count() RqlTerm
- func (t RqlTerm) CountFiltered(f interface{}) RqlTerm
- func (t RqlTerm) Date() RqlTerm
- func (t RqlTerm) Day() RqlTerm
- func (t RqlTerm) DayOfWeek() RqlTerm
- func (t RqlTerm) DayOfYear() RqlTerm
- func (t RqlTerm) Default(value interface{}) RqlTerm
- func (t RqlTerm) Delete(optArgs ...DeleteOpts) RqlTerm
- func (t RqlTerm) DeleteAt(index interface{}) RqlTerm
- func (t RqlTerm) DeleteAtRange(index, endIndex interface{}) RqlTerm
- func (t RqlTerm) Difference(arg interface{}) RqlTerm
- func (t RqlTerm) Distinct() RqlTerm
- func (t RqlTerm) Div(args ...interface{}) RqlTerm
- func (t RqlTerm) Do(f interface{}) RqlTerm
- func (t RqlTerm) During(startTime, endTime interface{}, optArgs ...DuringOpts) RqlTerm
- func (t RqlTerm) Eq(args ...interface{}) RqlTerm
- func (t RqlTerm) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) RqlTerm
- func (t RqlTerm) Exec(s *Session, optArgs ...RunOpts) error
- func (t RqlTerm) Field(field interface{}) RqlTerm
- func (t RqlTerm) Filter(f interface{}) RqlTerm
- func (t RqlTerm) ForEach(f interface{}) RqlTerm
- func (t RqlTerm) Ge(args ...interface{}) RqlTerm
- func (t RqlTerm) Get(key interface{}) RqlTerm
- func (t RqlTerm) GetAll(keys ...interface{}) RqlTerm
- func (t RqlTerm) GetAllByIndex(index interface{}, keys ...interface{}) RqlTerm
- func (t RqlTerm) GroupBy(collector interface{}, args ...interface{}) RqlTerm
- func (t RqlTerm) GroupedMapReduce(grouping, mapping, reduction, base interface{}) RqlTerm
- func (t RqlTerm) Gt(args ...interface{}) RqlTerm
- func (t RqlTerm) HasFields(fields ...interface{}) RqlTerm
- func (t RqlTerm) Hours() RqlTerm
- func (t RqlTerm) InTimezone(tz interface{}) RqlTerm
- func (t RqlTerm) IndexCreate(name interface{}, optArgs ...IndexCreateOpts) RqlTerm
- func (t RqlTerm) IndexCreateFunc(name, f interface{}, optArgs ...IndexCreateOpts) RqlTerm
- func (t RqlTerm) IndexDrop(name interface{}) RqlTerm
- func (t RqlTerm) IndexList() RqlTerm
- func (t RqlTerm) IndexStatus(indexes ...interface{}) RqlTerm
- func (t RqlTerm) IndexWait(indexes ...interface{}) RqlTerm
- func (t RqlTerm) IndexesOf(arg interface{}) RqlTerm
- func (t RqlTerm) Info() RqlTerm
- func (t RqlTerm) InnerJoin(other, predicate interface{}) RqlTerm
- func (t RqlTerm) Insert(arg interface{}, optArgs ...InsertOpts) RqlTerm
- func (t RqlTerm) InsertAt(index, value interface{}) RqlTerm
- func (t RqlTerm) IsEmpty() RqlTerm
- func (t RqlTerm) Keys() RqlTerm
- func (t RqlTerm) Le(args ...interface{}) RqlTerm
- func (t RqlTerm) Limit(n interface{}) RqlTerm
- func (t RqlTerm) Lt(args ...interface{}) RqlTerm
- func (t RqlTerm) Map(f interface{}) RqlTerm
- func (t RqlTerm) Match(regexp interface{}) RqlTerm
- func (t RqlTerm) Merge(arg interface{}) RqlTerm
- func (t RqlTerm) Minutes() RqlTerm
- func (t RqlTerm) Mod(args ...interface{}) RqlTerm
- func (t RqlTerm) Month() RqlTerm
- func (t RqlTerm) Mul(args ...interface{}) RqlTerm
- func (t RqlTerm) Ne(args ...interface{}) RqlTerm
- func (t RqlTerm) Not() RqlTerm
- func (t RqlTerm) Nth(n interface{}) RqlTerm
- func (t RqlTerm) Or(args ...interface{}) RqlTerm
- func (t RqlTerm) OrderBy(args ...interface{}) RqlTerm
- func (t RqlTerm) OuterJoin(other, predicate interface{}) RqlTerm
- func (t RqlTerm) Pluck(fields ...interface{}) RqlTerm
- func (t RqlTerm) Prepend(arg interface{}) RqlTerm
- func (t RqlTerm) Reduce(f, base interface{}) RqlTerm
- func (t RqlTerm) Replace(arg interface{}, optArgs ...ReplaceOpts) RqlTerm
- func (t RqlTerm) Run(s *Session, optArgs ...RunOpts) (*ResultRows, error)
- func (t RqlTerm) RunRow(s *Session, optArgs ...RunOpts) (*ResultRow, error)
- func (t RqlTerm) RunWrite(s *Session, optArgs ...RunOpts) (WriteResponse, error)
- func (t RqlTerm) Sample(n interface{}) RqlTerm
- func (t RqlTerm) Seconds() RqlTerm
- func (t RqlTerm) SetDifference(arg interface{}) RqlTerm
- func (t RqlTerm) SetInsert(arg interface{}) RqlTerm
- func (t RqlTerm) SetIntersection(arg interface{}) RqlTerm
- func (t RqlTerm) SetUnion(arg interface{}) RqlTerm
- func (t RqlTerm) Skip(n interface{}) RqlTerm
- func (t RqlTerm) Slice(lower, upper interface{}) RqlTerm
- func (t RqlTerm) SpliceAt(index, value interface{}) RqlTerm
- func (t RqlTerm) String() string
- func (t RqlTerm) Sub(args ...interface{}) RqlTerm
- func (t RqlTerm) Sync() RqlTerm
- func (t RqlTerm) Table(name interface{}, optArgs ...TableOpts) RqlTerm
- func (t RqlTerm) TableCreate(name interface{}, optArgs ...TableCreateOpts) RqlTerm
- func (t RqlTerm) TableDrop(name interface{}) RqlTerm
- func (t RqlTerm) TableList() RqlTerm
- func (t RqlTerm) TimeOfDay() RqlTerm
- func (t RqlTerm) Timezone() RqlTerm
- func (t RqlTerm) ToEpochTime() RqlTerm
- func (t RqlTerm) ToISO8601() RqlTerm
- func (t RqlTerm) TypeOf() RqlTerm
- func (t RqlTerm) Union(arg interface{}) RqlTerm
- func (t RqlTerm) Update(arg interface{}, optArgs ...UpdateOpts) RqlTerm
- func (t RqlTerm) WithFields(selectors ...interface{}) RqlTerm
- func (t RqlTerm) Without(fields ...interface{}) RqlTerm
- func (t RqlTerm) Year() RqlTerm
- func (t RqlTerm) Zip() RqlTerm
- type RunOpts
- type Session
- func (s *Session) Close(optArgs ...CloseOpts) error
- func (s *Session) NoReplyWait()
- func (s *Session) Reconnect(optArgs ...CloseOpts) error
- func (s *Session) SetMaxIdleConns(n int)
- func (s *Session) SetMaxOpenConns(n int)
- func (s *Session) SetTimeout(timeout time.Duration)
- func (s *Session) Use(database string)
- type TableCreateOpts
- type TableOpts
- type UpdateOpts
- type WriteResponse
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrPoolExhausted = errors.New("gorethink: connection pool exhausted")
var Row = newRqlTerm("Doc", p.Term_IMPLICIT_VAR, []interface{}{}, map[string]interface{}{})
Returns the currently visited document.
Functions ¶
func TestOnBorrow ¶
func TestOnBorrow(c *Connection, t time.Time) error
Types ¶
type BetweenOpts ¶
type BetweenOpts struct { Index interface{} `gorethink:"index,omitempty"` LeftBound interface{} `gorethink:"left_bound,omitempty"` RightBound interface{} `gorethink:"right_bound,omitempty"` }
type Connection ¶
type Connection struct { // embed the net.Conn type, so that we can effectively define new methods on // it (interfaces do not allow that) net.Conn // contains filtered or unexported fields }
connection is a connection to a rethinkdb database
func Dial ¶
func Dial(s *Session) (*Connection, error)
Reconnect closes the previous connection and attempts to connect again.
func (*Connection) Close ¶
func (c *Connection) Close() error
func (*Connection) SendQuery ¶
func (c *Connection) SendQuery(s *Session, q *p.Query, t RqlTerm, opts map[string]interface{}) (*ResultRows, error)
type DeleteOpts ¶
type DeleteOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnVals interface{} `gorethink:"return_vals,omitempty"` }
type DuringOpts ¶
type DuringOpts struct { LeftBound interface{} `gorethink:"left_bound,omitempty"` RightBound interface{} `gorethink:"right_bound,omitempty"` }
type EqJoinOpts ¶
type EqJoinOpts struct {
Index interface{} `gorethink:"index,omitempty"`
}
type ISO8601Opts ¶
type ISO8601Opts struct {
DefaultTimezone interface{} `gorethink:"default_timezone,omitempty"`
}
type IndexCreateOpts ¶
type IndexCreateOpts struct {
Multi interface{} `gorethink:"multi,omitempty"`
}
type InsertOpts ¶
type InsertOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnVals interface{} `gorethink:"return_vals,omitempty"` CacheSize interface{} `gorethink:"cache_size,omitempty"` Upsert interface{} `gorethink:"upsert,omitempty"` }
type Pool ¶
type Pool struct { Session *Session // Maximum number of idle connections in the pool. MaxIdle int // Maximum number of connections allocated by the pool at a given time. // When zero, there is no limit on the number of connections in the pool. MaxActive int // Close connections after remaining idle for this duration. If the value // is zero, then idle connections are not closed. Applications should set // the timeout to a value less than the server's timeout. IdleTimeout time.Duration // contains filtered or unexported fields }
Pool maintains a pool of connections. The application calls the Get method to get a connection from the pool and the connection's Close method to return the connection's resources to the pool.
func (*Pool) ActiveCount ¶
ActiveCount returns the number of active connections in the pool.
type ReplaceOpts ¶
type ReplaceOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnVals interface{} `gorethink:"return_vals,omitempty"` NotAtomic interface{} `gorethink:"non_atomic,omitempty"` }
type ResultRow ¶
type ResultRow struct {
// contains filtered or unexported fields
}
ResultRow contains the result of a RunRow query
func (*ResultRow) IsNil ¶
Tests if the result is nil. RethinkDB returns an nil value on Get queries when nothing is found.
func (*ResultRow) Scan ¶
Scan copies the result from the matched row into the value pointed at by dest. If more than one row is returned by the query then Scan returns the first and ignores the rest. If no row is found then Scan returns an error.
RethinkDB returns an nil value on Get queries when nothing is found, and Scan won't fail in this case.
type ResultRows ¶
type ResultRows struct {
// contains filtered or unexported fields
}
ResultRows contains the result of a query. Its cursor starts before the first row of the result set. Use Next to advance through the rows.
func (*ResultRows) Close ¶
func (r *ResultRows) Close() error
Close closes the Rows, preventing further enumeration. If the end is encountered, the Rows are closed automatically. Close is idempotent.
func (*ResultRows) Count ¶
func (r *ResultRows) Count() (count int, more bool)
Returns the number of rows currently in the buffer. If only a partial response was returned from the server then the more flag is set to true.
func (*ResultRows) Err ¶
func (r *ResultRows) Err() error
Err returns the error, if any, that was encountered during iteration.
func (*ResultRows) Next ¶
func (r *ResultRows) Next() bool
Next prepares the next row for reading. It returns true on success or false if there are no more rows. Every call to scan must be preceeded by a call to next. If all rows in the buffer have been read and a partial sequence was returned then Next will load more from the database
func (*ResultRows) Profile ¶
func (r *ResultRows) Profile() interface{}
func (*ResultRows) Scan ¶
func (r *ResultRows) Scan(dest interface{}) error
Scan copies the result in the current row into the value pointed at by dest.
If an argument is of type *interface{}, Scan copies the value provided by the database without conversion.
If the value is a struct then Scan traverses the result recursively and attempts to match the keys returned by the database to the name used by the structs field (either the struct field name or its key).
func (*ResultRows) ScanAll ¶
func (r *ResultRows) ScanAll(dest interface{}) error
ScanAll copies all the rows in the result buffer into the value pointed at by dest.
type RqlClientError ¶
type RqlClientError struct {
// contains filtered or unexported fields
}
type RqlCompileError ¶
type RqlCompileError struct {
// contains filtered or unexported fields
}
type RqlConnectionError ¶
type RqlConnectionError struct {
// contains filtered or unexported fields
}
func (RqlConnectionError) Error ¶
func (e RqlConnectionError) Error() string
func (RqlConnectionError) String ¶
func (e RqlConnectionError) String() string
type RqlDriverError ¶
type RqlDriverError struct {
// contains filtered or unexported fields
}
func (RqlDriverError) Error ¶
func (e RqlDriverError) Error() string
func (RqlDriverError) String ¶
func (e RqlDriverError) String() string
type RqlRuntimeError ¶
type RqlRuntimeError struct {
// contains filtered or unexported fields
}
type RqlTerm ¶
type RqlTerm struct {
// contains filtered or unexported fields
}
func Avg ¶
func Avg(arg interface{}) RqlTerm
Compute the average value of the given attribute for the group.
func Branch ¶
func Branch(test, trueBranch, falseBranch interface{}) RqlTerm
Evaluate one of two control paths based on the value of an expression. branch is effectively an if renamed due to language constraints.
The type of the result is determined by the type of the branch that gets executed.
func DbCreate ¶
func DbCreate(name interface{}) RqlTerm
Create a database. A RethinkDB database is a collection of tables, similar to relational databases.
If successful, the operation returns an object: {created: 1}. If a database with the same name already exists the operation throws RqlRuntimeError.
Note: that you can only use alphanumeric characters and underscores for the database name.
func DbDrop ¶
func DbDrop(name interface{}) RqlTerm
Drop a database. The database, all its tables, and corresponding data will be deleted.
If successful, the operation returns the object {dropped: 1}. If the specified database doesn't exist a RqlRuntimeError is thrown.
func Do ¶
func Do(args ...interface{}) RqlTerm
Evaluate the expr in the context of one or more value bindings. The type of the result is the type of the value returned from expr.
func EpochTime ¶
func EpochTime(epochtime interface{}) RqlTerm
Returns a time object based on seconds since epoch
func Error ¶
func Error(message interface{}) RqlTerm
Throw a runtime error. If called with no arguments inside the second argument to `default`, re-throw the current error.
func Expr ¶
func Expr(value interface{}) RqlTerm
Expr converts any value to an expression. Internally it uses the `json` module to convert any literals, so any type annotations or methods understood by that module can be used. If the value cannot be converted, an error is returned at query .Run(session) time.
If you want to call expression methods on an object that is not yet an expression, this is the function you want.
func Ge ¶
func Ge(args ...interface{}) RqlTerm
Ge returns true if the first value is greater than or equal to the second.
func Gt ¶
func Gt(args ...interface{}) RqlTerm
Gt returns true if the first value is greater than the second.
func ISO8601 ¶
func ISO8601(date interface{}, optArgs ...ISO8601Opts) RqlTerm
Returns a time object based on an ISO8601 formatted date-time string
Optional arguments (see http://www.rethinkdb.com/api/#js:dates_and_times-iso8601 for more information): "default_timezone" (string)
func Le ¶
func Le(args ...interface{}) RqlTerm
Le returns true if the first value is less than or equal to the second.
func Lt ¶
func Lt(args ...interface{}) RqlTerm
Lt returns true if the first value is less than the second.
func Table ¶
Select all documents in a table. This command can be chained with other commands to do further processing on the data.
Optional arguments (see http://www.rethinkdb.com/api/#js:selecting_data-table for more information): "use_outdated" (boolean - defaults to false)
func (RqlTerm) Between ¶
func (t RqlTerm) Between(lowerKey, upperKey interface{}, optArgs ...BetweenOpts) RqlTerm
Get all documents between two keys. Accepts three optional arguments: `index`, `left_bound`, and `right_bound`. If `index` is set to the name of a secondary index, `between` will return all documents where that index's value is in the specified range (it uses the primary key by default). `left_bound` or `right_bound` may be set to `open` or `closed` to indicate whether or not to include that endpoint of the range (by default, `left_bound` is closed and `right_bound` is open).
func (RqlTerm) 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 (RqlTerm) ConcatMap ¶
Flattens a sequence of arrays returned by the mapping function into a single sequence.
func (RqlTerm) 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 (RqlTerm) CountFiltered ¶
Count the number of elements in the sequence. CountFiltered uses the argument passed to it to filter the results before counting.
func (RqlTerm) Date ¶
Return a new time object only based on the day, month and year (ie. the same day at 00:00).
func (RqlTerm) DayOfWeek ¶
Return the day of week of a time object as a number between 1 and 7 (following ISO 8601 standard). For your convenience, the terms r.Monday(), r.Tuesday() etc. are defined and map to the appropriate integer.
func (RqlTerm) DayOfYear ¶
Return the day of the year of a time object as a number between 1 and 366 (following ISO 8601 standard).
func (RqlTerm) Default ¶
Handle non-existence errors. Tries to evaluate and return its first argument. If an error related to the absence of a value is thrown in the process, or if its first argument returns null, returns its second argument. (Alternatively, the second argument may be a function which will be called with either the text of the non-existence error or null.)
func (RqlTerm) Delete ¶
func (t RqlTerm) Delete(optArgs ...DeleteOpts) RqlTerm
Delete one or more documents from a table. The optional argument return_vals will return the old value of the row you're deleting when set to true (only valid for single-row deletes). The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting.
func (RqlTerm) DeleteAt ¶
Remove an element from an array at a given index. Returns the modified array.
func (RqlTerm) DeleteAtRange ¶
Remove the elements between the given range. Returns the modified array.
func (RqlTerm) Difference ¶
Remove the elements of one array from another array.
func (RqlTerm) Do ¶
Evaluate the expr in the context of one or more value bindings. The type of the result is the type of the value returned from expr.
func (RqlTerm) During ¶
func (t RqlTerm) During(startTime, endTime interface{}, optArgs ...DuringOpts) RqlTerm
Returns true if a time is between two other times (by default, inclusive for the start, exclusive for the end).
Optional arguments (see http://www.rethinkdb.com/api/#js:dates_and_times-during for more information): "left_bound" and "right_bound" ("open" for exclusive or "closed" for inclusive)
func (RqlTerm) EqJoin ¶
func (t RqlTerm) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) RqlTerm
An efficient join that looks up elements in the right table by primary key.
Optional arguments: "index" (string - name of the index to use in right table instead of the primary key)
func (RqlTerm) Exec ¶
Exec runs the query but does not return the result (It also automatically sets the noreply option).
func (RqlTerm) Field ¶
Get a single field from an object. If called on a sequence, gets that field from every object in the sequence, skipping objects that lack it.
func (RqlTerm) Filter ¶
Get all the documents for which the given predicate is true.
Filter can be called on a sequence, selection, or a field containing an array of elements. The return type is the same as the type on which the function was called on. The body of every filter is wrapped in an implicit `.default(false)`, and the default value can be changed by passing the optional argument `default`. Setting this optional argument to `r.error()` will cause any non-existence errors to abort the filter.
func (RqlTerm) Get ¶
Get a document by primary key. If nothing was found, RethinkDB will return a nil value.
Example ¶
type Person struct { Id string `gorethink:"id, omitempty"` FirstName string `gorethink:"first_name"` LastName string `gorethink:"last_name"` Gender string `gorethink:"gender"` } sess, err := r.Connect(map[string]interface{}{ "address": url, }) // Setup table r.Db("test").TableDrop("table").Run(sess) r.Db("test").TableCreate("table").Run(sess) r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess) // Fetch the row from the database row, err := r.Db("test").Table("table").Get("1").RunRow(sess) if err != nil { log.Fatalf("Error finding person: %s", err) } if row.IsNil() { log.Fatalf("Person not found") } // Scan query result into the person variable var person Person err = row.Scan(&person) if err != nil { log.Fatalf("Error scanning database result: %s", err) } fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
Output: John Smith (M)
func (RqlTerm) GetAll ¶
Get all documents where the given value matches the value of the primary index.
Example (Compound) ¶
type Person struct { Id string `gorethink:"id, omitempty"` FirstName string `gorethink:"first_name"` LastName string `gorethink:"last_name"` Gender string `gorethink:"gender"` } sess, err := r.Connect(map[string]interface{}{ "address": url, }) // Setup table r.Db("test").TableDrop("table").Run(sess) r.Db("test").TableCreate("table").Run(sess) r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess) r.Db("test").Table("table").IndexCreateFunc("full_name", func(row r.RqlTerm) interface{} { return []interface{}{row.Field("first_name"), row.Field("last_name")} }).Run(sess) // Fetch the row from the database row, err := r.Db("test").Table("table").GetAllByIndex("full_name", []interface{}{"John", "Smith"}).RunRow(sess) if err != nil { log.Fatalf("Error finding person: %s", err) } if row.IsNil() { log.Fatalf("Person not found") } // Scan query result into the person variable var person Person row.Scan(&person) fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
Output: John Smith (M)
func (RqlTerm) GetAllByIndex ¶
Get all documents where the given value matches the value of the requested index.
func (RqlTerm) GroupBy ¶
Groups elements by the values of the given attributes and then applies the given reduction. Though similar to GroupedMapReduce, GroupBy takes a standardized object for specifying the reduction. Can be used with a number of predefined common reductions
func (RqlTerm) GroupedMapReduce ¶
Partition the sequence into groups based on the grouping function. The elements of each group are then mapped using the mapping function and reduced using the reduction function.
func (RqlTerm) HasFields ¶
Test if an object has all of the specified fields. An object has a field if it has the specified key and that key maps to a non-null value. For instance,
the object `{'a':1,'b':2,'c':null}` has the fields `a` and `b`.
func (RqlTerm) 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 (RqlTerm) IndexCreate ¶
func (t RqlTerm) IndexCreate(name interface{}, optArgs ...IndexCreateOpts) RqlTerm
Create a new secondary index on this table.
A multi index can be created by passing an optional multi argument. Multi indexes
functions should return arrays and allow you to query based on whether a value is present in the returned array. The example would allow us to get heroes who possess a specific ability (the field 'abilities' is an array).
Example ¶
sess, err := r.Connect(map[string]interface{}{ "address": url, }) // Setup database r.Db("test").TableDrop("table").Run(sess) r.Db("test").TableCreate("table").Run(sess) response, err := r.Db("test").Table("table").IndexCreate("name").RunWrite(sess) if err != nil { log.Fatalf("Error creating index: %s", err) } fmt.Printf("%d index created", response.Created)
Output: 1 index created
Example (Compound) ¶
sess, err := r.Connect(map[string]interface{}{ "address": url, }) // Setup database r.Db("test").TableDrop("table").Run(sess) r.Db("test").TableCreate("table").Run(sess) response, err := r.Db("test").Table("table").IndexCreateFunc("full_name", func(row r.RqlTerm) interface{} { return []interface{}{row.Field("first_name"), row.Field("last_name")} }).RunWrite(sess) if err != nil { log.Fatalf("Error creating index: %s", err) } fmt.Printf("%d index created", response.Created)
Output: 1 index created
func (RqlTerm) IndexCreateFunc ¶
func (t RqlTerm) IndexCreateFunc(name, f interface{}, optArgs ...IndexCreateOpts) RqlTerm
Create a new secondary index on this table based on the value of the function passed.
A compound index can be created by returning an array of values to use as the secondary index key.
func (RqlTerm) IndexStatus ¶
Get the status of the specified indexes on this table, or the status of all indexes on this table if no indexes are specified.
func (RqlTerm) IndexWait ¶
Wait for the specified indexes on this table to be ready, or for all indexes on this table to be ready if no indexes are specified.
func (RqlTerm) IndexesOf ¶
Get the indexes of an element in a sequence. If the argument is a predicate, get the indexes of all elements matching it.
func (RqlTerm) 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 (RqlTerm) Insert ¶
func (t RqlTerm) Insert(arg interface{}, optArgs ...InsertOpts) RqlTerm
Insert JSON documents into a table. Accepts a single JSON document or an array of documents. You may also pass the optional argument durability with value 'hard' or 'soft', to override the table or query's default durability setting, or the optional argument return_vals, which will return the value of the row you're inserting (and the old value if you use upsert) when set to true.
table.Insert(map[string]interface{}{"name": "Joe", "email": "joe@example.com"}).RunWrite(sess) table.Insert([]interface{}{map[string]interface{}{"name": "Joe"}, map[string]interface{}{"name": "Paul"}}).RunWrite(sess)
func (RqlTerm) InsertAt ¶
Insert a value in to an array at a given index. Returns the modified array.
func (RqlTerm) Match ¶
Match against a regular expression. Returns a match object containing the matched string, that string's start/end position, and the capture groups.
Expr("id:0,name:mlucy,foo:bar").Match("name:(\\w+)").Field("groups").Nth(0).Field("str")
func (RqlTerm) Merge ¶
Merge two objects together to construct a new object with properties from both. Gives preference to attributes from other when there is a conflict.
func (RqlTerm) Month ¶
Return the month of a time object as a number between 1 and 12. For your convenience, the terms r.January(), r.February() etc. are defined and map to the appropriate integer.
func (RqlTerm) OrderBy ¶
Sort the sequence by document values of the given key(s). To specify the index to use for ordering us a last argument in the following form:
map[string]interface{}{"index": "index-name"}
OrderBy defaults to ascending ordering. To explicitly specify the ordering, wrap the attribute with either Asc or Desc.
query.OrderBy("name") query.OrderBy(Asc("name")) query.OrderBy(Desc("name"))
func (RqlTerm) OuterJoin ¶
Computes a left outer join by retaining each row in the left table even if no match was found in the right table.
func (RqlTerm) Pluck ¶
Plucks out one or more attributes from either an object or a sequence of objects (projection).
func (RqlTerm) Reduce ¶
Produce a single value from a sequence through repeated application of a reduction function.
The reduce function gets invoked repeatedly not only for the input values but also for results of previous reduce invocations. The type and format of the object that is passed in to reduce must be the same with the one returned from reduce.
func (RqlTerm) Replace ¶
func (t RqlTerm) Replace(arg interface{}, optArgs ...ReplaceOpts) RqlTerm
Replace documents in a table. Accepts a JSON document or a RQL expression, and replaces the original document with the new one. The new document must have the same primary key as the original document. The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting. The optional argument return_vals will return the old and new values of the row you're modifying when set to true (only valid for single-row replacements). The optional argument non_atomic lets you permit non-atomic updates.
func (RqlTerm) Run ¶
func (t RqlTerm) Run(s *Session, optArgs ...RunOpts) (*ResultRows, error)
Run runs a query using the given connection.
rows, err := query.Run(sess) if err != nil { // error } for rows.Next() { doc := MyDocumentType{} err := r.Scan(&doc) // Do something with row }
func (RqlTerm) RunRow ¶
Run runs a query using the given connection but unlike Run returns ResultRow. This function should be used if your query only returns a single row.
row, err := query.RunRow(sess, r.RunOpts{ UseOutdated: true, }) if err != nil { // error } if row.IsNil() { // nothing was found } err = row.Scan(&doc)
func (RqlTerm) RunWrite ¶
func (t RqlTerm) RunWrite(s *Session, optArgs ...RunOpts) (WriteResponse, error)
RunWrite runs a query using the given connection but unlike Run automatically scans the result into a variable of type WriteResponse. This function should be used if you are running a write query (such as Insert, Update, TableCreate, etc...)
Optional arguments : "db", "use_outdated" (defaults to false), "noreply" (defaults to false) and "time_format".
res, err := r.Db("database").Table("table").Insert(doc).RunWrite(sess, r.RunOpts{ NoReply: true, })
func (RqlTerm) Sample ¶
Select a given number of elements from a sequence with uniform random distribution. Selection is done without replacement.
func (RqlTerm) Seconds ¶
Return the seconds in a time object as a number between 0 and 59.999 (double precision).
func (RqlTerm) SetDifference ¶
Remove the elements of one array from another and return them as a set (an array with distinct values).
func (RqlTerm) SetInsert ¶
Add a value to an array and return it as a set (an array with distinct values).
func (RqlTerm) SetIntersection ¶
Intersect two arrays returning values that occur in both of them as a set (an array with distinct values).
func (RqlTerm) SetUnion ¶
Add a several values to an array and return it as a set (an array with distinct values).
func (RqlTerm) SpliceAt ¶
Insert several values in to an array at a given index. Returns the modified array.
func (RqlTerm) Sync ¶
Sync ensures that writes on a given table are written to permanent storage. Queries that specify soft durability (Durability: "soft") do not give such guarantees, so sync can be used to ensure the state of these queries. A call to sync does not return until all previous writes to the table are persisted.
func (RqlTerm) Table ¶
Select all documents in a table. This command can be chained with other commands to do further processing on the data.
Optional arguments (see http://www.rethinkdb.com/api/#js:selecting_data-table for more information): "use_outdated" (boolean - defaults to false)
func (RqlTerm) TableCreate ¶
func (t RqlTerm) TableCreate(name interface{}, optArgs ...TableCreateOpts) RqlTerm
Create a table. A RethinkDB table is a collection of JSON documents.
If successful, the operation returns an object: {created: 1}. If a table with the same name already exists, the operation throws RqlRuntimeError.
Note: that you can only use alphanumeric characters and underscores for the table name.
r.Db("database").TableCreate("table", "durability", "soft").Run(sess)
Example ¶
sess, err := r.Connect(map[string]interface{}{ "address": url, }) // Setup database r.Db("test").TableDrop("table").Run(sess) response, err := r.Db("test").TableCreate("table").RunWrite(sess) if err != nil { log.Fatalf("Error creating table: %s", err) } fmt.Printf("%d table created", response.Created)
Output: 1 table created
func (RqlTerm) TableDrop ¶
Drop a table. The table and all its data will be deleted.
If successful, the operation returns an object: {dropped: 1}. If the specified table doesn't exist a RqlRuntimeError is thrown.
func (RqlTerm) TimeOfDay ¶
Return the number of seconds elapsed since the beginning of the day stored in the time object.
func (RqlTerm) ToEpochTime ¶
Convert a time object to its epoch time.
func (RqlTerm) Update ¶
func (t RqlTerm) Update(arg interface{}, optArgs ...UpdateOpts) RqlTerm
Update JSON documents in a table. Accepts a JSON document, a RQL expression, or a combination of the two. The optional argument durability with value 'hard' or 'soft' will override the table or query's default durability setting. The optional argument return_vals will return the old and new values of the row you're modifying when set to true (only valid for single-row updates). The optional argument non_atomic lets you permit non-atomic updates.
func (RqlTerm) WithFields ¶
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.)
type RunOpts ¶
type RunOpts struct { Db interface{} `gorethink:"db,omitempty"` Profile interface{} `gorethink:"profile,omitempty"` UseOutdated interface{} `gorethink:"use_outdated,omitempty"` NoReply interface{} `gorethink:"noreply,omitempty"` TimeFormat interface{} `gorethink:"time_format,omitempty"` }
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
func Connect ¶
Connect creates a new database session.
Supported arguments include token, address, database, timeout, authkey, and timeFormat. Pool options include maxIdle, maxActive and idleTimeout.
By default maxIdle and maxActive are set to 1: passing values greater than the default (e.g. maxIdle: "10", maxActive: "20") will provide a pool of re-usable connections.
Basic connection example:
var session *r.Session session, err := r.Connect(map[string]interface{}{ "address": "localhost:28015", "database": "test", "authkey": "14daak1cad13dj", })
func (*Session) SetMaxIdleConns ¶
SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
If MaxOpenConns is greater than 0 but less than the new MaxIdleConns then the new MaxIdleConns will be reduced to match the MaxOpenConns limit
If n <= 0, no idle connections are retained.
func (*Session) SetMaxOpenConns ¶
SetMaxOpenConns sets the maximum number of open connections to the database.
If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit
If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).
func (*Session) SetTimeout ¶
SetTimeout causes any future queries that are run on this session to timeout after the given duration, returning a timeout error. Set to zero to disable.
type TableCreateOpts ¶
type TableCreateOpts struct { PrimaryKey interface{} `gorethink:"primary_key,omitempty"` Durability interface{} `gorethink:"durability,omitempty"` CacheSize interface{} `gorethink:"cache_size,omitempty"` DataCenter interface{} `gorethink:"datacenter,omitempty"` }
type UpdateOpts ¶
type UpdateOpts struct { Durability interface{} `gorethink:"durability,omitempty"` ReturnVals interface{} `gorethink:"return_vals,omitempty"` NotAtomic interface{} `gorethink:"non_atomic,omitempty"` }
type WriteResponse ¶
type WriteResponse struct { Errors int Created int Inserted int Updated int Unchanged int Replaced int Deleted int GeneratedKeys []string `gorethink:"generated_keys"` FirstError string `gorethink:"first_error"` // populated if Errors > 0 NewValue interface{} `gorethink:"new_val"` OldValue interface{} `gorethink:"old_val"` }
Source Files ¶
- connection.go
- datum.go
- doc.go
- errors.go
- pool.go
- query.go
- query_aggregation.go
- query_control.go
- query_db.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_utils.go
- query_write.go
- results.go
- session.go
- utils.go