gopkg.in/rethinkdb/rethinkdb-go.v6@v6.2.2/README.md (about) 1 # RethinkDB-go - RethinkDB Driver for Go 2 3 [](https://github.com/rethinkdb/rethinkdb-go/releases) 4 [](https://godoc.org/github.com/rethinkdb/rethinkdb-go) 5 [](https://travis-ci.org/rethinkdb/rethinkdb-go) 6 7 [Go](http://golang.org/) driver for [RethinkDB](http://www.rethinkdb.com/) 8 9  10 11 Current version: v6.2.1 (RethinkDB v2.4) 12 13 Please note that this version of the driver only supports versions of RethinkDB using the v0.4 protocol (any versions of the driver older than RethinkDB 2.0 will not work). 14 15 If you need any help you can find me on the [RethinkDB slack](https://rethinkdb.slack.com/) in the #gorethink channel. 16 17 ## Installation 18 19 ``` 20 go get gopkg.in/rethinkdb/rethinkdb-go.v6 21 ``` 22 23 Replace `v6` with `v5` or `v4` to use previous versions. 24 25 ## Example 26 27 [embedmd]:# (example_test.go go) 28 ```go 29 package rethinkdb_test 30 31 import ( 32 "fmt" 33 "log" 34 35 r "gopkg.in/rethinkdb/rethinkdb-go.v6" 36 ) 37 38 func Example() { 39 session, err := r.Connect(r.ConnectOpts{ 40 Address: url, // endpoint without http 41 }) 42 if err != nil { 43 log.Fatalln(err) 44 } 45 46 res, err := r.Expr("Hello World").Run(session) 47 if err != nil { 48 log.Fatalln(err) 49 } 50 51 var response string 52 err = res.One(&response) 53 if err != nil { 54 log.Fatalln(err) 55 } 56 57 fmt.Println(response) 58 59 // Output: 60 // Hello World 61 } 62 ``` 63 64 ## Connection 65 66 ### Basic Connection 67 68 Setting up a basic connection with RethinkDB is simple: 69 70 [embedmd]:# (example_connect_test.go go /func ExampleConnect\(\) {/ /^}/) 71 ```go 72 func ExampleConnect() { 73 var err error 74 75 session, err = r.Connect(r.ConnectOpts{ 76 Address: url, 77 }) 78 if err != nil { 79 log.Fatalln(err.Error()) 80 } 81 } 82 ``` 83 84 See the [documentation](http://godoc.org/github.com/rethinkdb/rethinkdb-go#Connect) for a list of supported arguments to Connect(). 85 86 ### Connection Pool 87 88 The driver uses a connection pool at all times, by default it creates and frees connections automatically. It's safe for concurrent use by multiple goroutines. 89 90 To configure the connection pool `InitialCap`, `MaxOpen` and `Timeout` can be specified during connection. If you wish to change the value of `InitialCap` or `MaxOpen` during runtime then the functions `SetInitialPoolCap` and `SetMaxOpenConns` can be used. 91 92 [embedmd]:# (example_connect_test.go go /func ExampleConnect_connectionPool\(\) {/ /^}/) 93 ```go 94 func ExampleConnect_connectionPool() { 95 var err error 96 97 session, err = r.Connect(r.ConnectOpts{ 98 Address: url, 99 InitialCap: 10, 100 MaxOpen: 10, 101 }) 102 if err != nil { 103 log.Fatalln(err.Error()) 104 } 105 } 106 ``` 107 108 ### Connect to a cluster 109 110 To connect to a RethinkDB cluster which has multiple nodes you can use the following syntax. When connecting to a cluster with multiple nodes queries will be distributed between these nodes. 111 112 [embedmd]:# (example_connect_test.go go /func ExampleConnect_cluster\(\) {/ /^}/) 113 ```go 114 func ExampleConnect_cluster() { 115 var err error 116 117 session, err = r.Connect(r.ConnectOpts{ 118 Addresses: []string{url}, 119 // Addresses: []string{url1, url2, url3, ...}, 120 }) 121 if err != nil { 122 log.Fatalln(err.Error()) 123 } 124 } 125 ``` 126 127 When `DiscoverHosts` is true any nodes are added to the cluster after the initial connection then the new node will be added to the pool of available nodes used by RethinkDB-go. Unfortunately the canonical address of each server in the cluster **MUST** be set as otherwise clients will try to connect to the database nodes locally. For more information about how to set a RethinkDB servers canonical address set this page http://www.rethinkdb.com/docs/config-file/. 128 129 ## User Authentication 130 131 To login with a username and password you should first create a user, this can be done by writing to the `users` system table and then grant that user access to any tables or databases they need access to. This queries can also be executed in the RethinkDB admin console. 132 133 ```go 134 err := r.DB("rethinkdb").Table("users").Insert(map[string]string{ 135 "id": "john", 136 "password": "p455w0rd", 137 }).Exec(session) 138 ... 139 err = r.DB("blog").Table("posts").Grant("john", map[string]bool{ 140 "read": true, 141 "write": true, 142 }).Exec(session) 143 ... 144 ``` 145 146 Finally the username and password should be passed to `Connect` when creating your session, for example: 147 148 ```go 149 session, err := r.Connect(r.ConnectOpts{ 150 Address: "localhost:28015", 151 Database: "blog", 152 Username: "john", 153 Password: "p455w0rd", 154 }) 155 ``` 156 157 Please note that `DiscoverHosts` will not work with user authentication at this time due to the fact that RethinkDB restricts access to the required system tables. 158 159 ## Query Functions 160 161 This library is based on the official drivers so the code on the [API](http://www.rethinkdb.com/api/) page should require very few changes to work. 162 163 To view full documentation for the query functions check the [API reference](https://github.com/rethinkdb/rethinkdb-go/wiki/Go-ReQL-command-reference) or [GoDoc](http://godoc.org/github.com/rethinkdb/rethinkdb-go#Term) 164 165 Slice Expr Example 166 ```go 167 r.Expr([]interface{}{1, 2, 3, 4, 5}).Run(session) 168 ``` 169 Map Expr Example 170 ```go 171 r.Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Run(session) 172 ``` 173 Get Example 174 ```go 175 r.DB("database").Table("table").Get("GUID").Run(session) 176 ``` 177 Map Example (Func) 178 ```go 179 r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(func (row Term) interface{} { 180 return row.Add(1) 181 }).Run(session) 182 ``` 183 Map Example (Implicit) 184 ```go 185 r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(r.Row.Add(1)).Run(session) 186 ``` 187 Between (Optional Args) Example 188 ```go 189 r.DB("database").Table("table").Between(1, 10, r.BetweenOpts{ 190 Index: "num", 191 RightBound: "closed", 192 }).Run(session) 193 ``` 194 195 For any queries which use callbacks the function signature is important as your function needs to be a valid RethinkDB-go callback, you can see an example of this in the map example above. The simplified explanation is that all arguments must be of type `r.Term`, this is because of how the query is sent to the database (your callback is not actually executed in your Go application but encoded as JSON and executed by RethinkDB). The return argument can be anything you want it to be (as long as it is a valid return value for the current query) so it usually makes sense to return `interface{}`. Here is an example of a callback for the conflict callback of an insert operation: 196 197 ```go 198 r.Table("test").Insert(doc, r.InsertOpts{ 199 Conflict: func(id, oldDoc, newDoc r.Term) interface{} { 200 return newDoc.Merge(map[string]interface{}{ 201 "count": oldDoc.Add(newDoc.Field("count")), 202 }) 203 }, 204 }) 205 ``` 206 207 ### Optional Arguments 208 209 As shown above in the Between example optional arguments are passed to the function as a struct. Each function that has optional arguments as a related struct. This structs are named in the format FunctionNameOpts, for example BetweenOpts is the related struct for Between. 210 211 #### Cancelling queries 212 213 For query cancellation use `Context` argument at `RunOpts`. If `Context` is `nil` and `ReadTimeout` or `WriteTimeout` is not 0 from `ConnectionOpts`, `Context` will be formed by summation of these timeouts. 214 215 For unlimited timeouts for `Changes()` pass `context.Background()`. 216 217 ## Results 218 219 Different result types are returned depending on what function is used to execute the query. 220 221 - `Run` returns a cursor which can be used to view all rows returned. 222 - `RunWrite` returns a WriteResponse and should be used for queries such as Insert, Update, etc... 223 - `Exec` sends a query to the server and closes the connection immediately after reading the response from the database. If you do not wish to wait for the response then you can set the `NoReply` flag. 224 225 Example: 226 227 ```go 228 res, err := r.DB("database").Table("tablename").Get(key).Run(session) 229 if err != nil { 230 // error 231 } 232 defer res.Close() // Always ensure you close the cursor to ensure connections are not leaked 233 ``` 234 235 Cursors have a number of methods available for accessing the query results 236 237 - `Next` retrieves the next document from the result set, blocking if necessary. 238 - `All` retrieves all documents from the result set into the provided slice. 239 - `One` retrieves the first document from the result set. 240 241 Examples: 242 243 ```go 244 var row interface{} 245 for res.Next(&row) { 246 // Do something with row 247 } 248 if res.Err() != nil { 249 // error 250 } 251 ``` 252 253 ```go 254 var rows []interface{} 255 err := res.All(&rows) 256 if err != nil { 257 // error 258 } 259 ``` 260 261 ```go 262 var row interface{} 263 err := res.One(&row) 264 if err == r.ErrEmptyResult { 265 // row not found 266 } 267 if err != nil { 268 // error 269 } 270 ``` 271 272 ## Encoding/Decoding 273 When passing structs to Expr(And functions that use Expr such as Insert, Update) the structs are encoded into a map before being sent to the server. Each exported field is added to the map unless 274 275 - the field's tag is "-", or 276 - the field is empty and its tag specifies the "omitempty" option. 277 278 Each fields default name in the map is the field name but can be specified in the struct field's tag value. The "rethinkdb" key in 279 the struct field's tag value is the key name, followed by an optional comma 280 and options. Examples: 281 282 ```go 283 // Field is ignored by this package. 284 Field int `rethinkdb:"-"` 285 // Field appears as key "myName". 286 Field int `rethinkdb:"myName"` 287 // Field appears as key "myName" and 288 // the field is omitted from the object if its value is empty, 289 // as defined above. 290 Field int `rethinkdb:"myName,omitempty"` 291 // Field appears as key "Field" (the default), but 292 // the field is skipped if empty. 293 // Note the leading comma. 294 Field int `rethinkdb:",omitempty"` 295 // When the tag name includes an index expression 296 // a compound field is created 297 Field1 int `rethinkdb:"myName[0]"` 298 Field2 int `rethinkdb:"myName[1]"` 299 ``` 300 301 **NOTE:** It is strongly recommended that struct tags are used to explicitly define the mapping between your Go type and how the data is stored by RethinkDB. This is especially important when using an `Id` field as by default RethinkDB will create a field named `id` as the primary key (note that the RethinkDB field is lowercase but the Go version starts with a capital letter). 302 303 When encoding maps with non-string keys the key values are automatically converted to strings where possible, however it is recommended that you use strings where possible (for example `map[string]T`). 304 305 If you wish to use the `json` tags for RethinkDB-go then you can call `SetTags("rethinkdb", "json")` when starting your program, this will cause RethinkDB-go to check for `json` tags after checking for `rethinkdb` tags. By default this feature is disabled. This function will also let you support any other tags, the driver will check for tags in the same order as the parameters. 306 307 **NOTE:** Old-style `gorethink` struct tags are supported but deprecated. 308 309 ### Pseudo-types 310 311 RethinkDB contains some special types which can be used to store special value types, currently supports are binary values, times and geometry data types. RethinkDB-go supports these data types natively however there are some gotchas: 312 - Time types: To store times in RethinkDB with RethinkDB-go you must pass a `time.Time` value to your query, due to the way Go works type aliasing or embedding is not support here 313 - Binary types: To store binary data pass a byte slice (`[]byte`) to your query 314 - Geometry types: As Go does not include any built-in data structures for storing geometry data RethinkDB-go includes its own in the `github.com/rethinkdb/rethinkdb-go/types` package, Any of the types (`Geometry`, `Point`, `Line` and `Lines`) can be passed to a query to create a RethinkDB geometry type. 315 316 ### Compound Keys 317 318 RethinkDB unfortunately does not support compound primary keys using multiple fields however it does support compound keys using an array of values. For example if you wanted to create a compound key for a book where the key contained the author ID and book name then the ID might look like this `["author_id", "book name"]`. Luckily RethinkDB-go allows you to easily manage these keys while keeping the fields separate in your structs. For example: 319 320 ```go 321 type Book struct { 322 AuthorID string `rethinkdb:"id[0]"` 323 Name string `rethinkdb:"id[1]"` 324 } 325 // Creates the following document in RethinkDB 326 {"id": [AUTHORID, NAME]} 327 ``` 328 329 ### References 330 331 Sometimes you may want to use a Go struct that references a document in another table, instead of creating a new struct which is just used when writing to RethinkDB you can annotate your struct with the reference tag option. This will tell RethinkDB-go that when encoding your data it should "pluck" the ID field from the nested document and use that instead. 332 333 This is all quite complicated so hopefully this example should help. First lets assume you have two types `Author` and `Book` and you want to insert a new book into your database however you dont want to include the entire author struct in the books table. As you can see the `Author` field in the `Book` struct has some extra tags, firstly we have added the `reference` tag option which tells RethinkDB-go to pluck a field from the `Author` struct instead of inserting the whole author document. We also have the `rethinkdb_ref` tag which tells RethinkDB-go to look for the `id` field in the `Author` document, without this tag RethinkDB-go would instead look for the `author_id` field. 334 335 ```go 336 type Author struct { 337 ID string `rethinkdb:"id,omitempty"` 338 Name string `rethinkdb:"name"` 339 } 340 341 type Book struct { 342 ID string `rethinkdb:"id,omitempty"` 343 Title string `rethinkdb:"title"` 344 Author Author `rethinkdb:"author_id,reference" rethinkdb_ref:"id"` 345 } 346 ``` 347 348 The resulting data in RethinkDB should look something like this: 349 350 ```json 351 { 352 "author_id": "author_1", 353 "id": "book_1", 354 "title": "The Hobbit" 355 } 356 ``` 357 358 If you wanted to read back the book with the author included then you could run the following RethinkDB-go query: 359 360 ```go 361 r.Table("books").Get("1").Merge(func(p r.Term) interface{} { 362 return map[string]interface{}{ 363 "author_id": r.Table("authors").Get(p.Field("author_id")), 364 } 365 }).Run(session) 366 ``` 367 368 You are also able to reference an array of documents, for example if each book stored multiple authors you could do the following: 369 370 ```go 371 type Book struct { 372 ID string `rethinkdb:"id,omitempty"` 373 Title string `rethinkdb:"title"` 374 Authors []Author `rethinkdb:"author_ids,reference" rethinkdb_ref:"id"` 375 } 376 ``` 377 378 ```json 379 { 380 "author_ids": ["author_1", "author_2"], 381 "id": "book_1", 382 "title": "The Hobbit" 383 } 384 ``` 385 386 The query for reading the data back is slightly more complicated but is very similar: 387 388 ```go 389 r.Table("books").Get("book_1").Merge(func(p r.Term) interface{} { 390 return map[string]interface{}{ 391 "author_ids": r.Table("authors").GetAll(r.Args(p.Field("author_ids"))).CoerceTo("array"), 392 } 393 }) 394 ``` 395 396 ### Custom `Marshaler`s/`Unmarshaler`s 397 398 Sometimes the default behaviour for converting Go types to and from ReQL is not desired, for these situations the driver allows you to implement both the [`Marshaler`](https://godoc.org/github.com/rethinkdb/rethinkdb-go/encoding#Marshaler) and [`Unmarshaler`](https://godoc.org/github.com/rethinkdb/rethinkdb-go/encoding#Unmarshaler) interfaces. These interfaces might look familiar if you are using to using the `encoding/json` package however instead of dealing with `[]byte` the interfaces deal with `interface{}` values (which are later encoded by the `encoding/json` package when communicating with the database). 399 400 An good example of how to use these interfaces is in the [`types`](https://github.com/rethinkdb/rethinkdb-go/blob/master/types/geometry.go#L84-L106) package, in this package the `Point` type is encoded as the `GEOMETRY` pseudo-type instead of a normal JSON object. 401 402 On the other side, you can implement external encode/decode functions with [`SetTypeEncoding`](https://godoc.org/github.com/rethinkdb/rethinkdb-go/encoding#SetTypeEncoding) function. 403 404 ## Logging 405 406 By default the driver logs are disabled however when enabled the driver will log errors when it fails to connect to the database. If you would like more verbose error logging you can call `r.SetVerbose(true)`. 407 408 Alternatively if you wish to modify the logging behaviour you can modify the logger provided by `github.com/sirupsen/logrus`. For example the following code completely disable the logger: 409 410 ```go 411 // Enabled 412 r.Log.Out = os.Stderr 413 // Disabled 414 r.Log.Out = ioutil.Discard 415 ``` 416 417 ## Tracing 418 419 The driver supports [opentracing-go](https://github.com/opentracing/opentracing-go/). You can enable this feature by setting `UseOpentracing` to true in the `ConnectOpts`. Then driver will expect `opentracing.Span` in the `RunOpts.Context` and will start new child spans for queries. 420 Also you need to configure tracer in your program by yourself. 421 422 The driver starts span for the whole query, from the first byte is sent to the cursor closed, and second-level span for each query for fetching data. 423 424 So you can trace how much time you program spends for RethinkDB queries. 425 426 ## Mocking 427 428 The driver includes the ability to mock queries meaning that you can test your code without needing to talk to a real RethinkDB cluster, this is perfect for ensuring that your application has high unit test coverage. 429 430 To write tests with mocking you should create an instance of `Mock` and then setup expectations using `On` and `Return`. Expectations allow you to define what results should be returned when a known query is executed, they are configured by passing the query term you want to mock to `On` and then the response and error to `Return`, if a non-nil error is passed to `Return` then any time that query is executed the error will be returned, if no error is passed then a cursor will be built using the value passed to `Return`. Once all your expectations have been created you should then execute you queries using the `Mock` instead of a `Session`. 431 432 Here is an example that shows how to mock a query that returns multiple rows and the resulting cursor can be used as normal. 433 434 ```go 435 func TestSomething(t *testing.T) { 436 mock := r.NewMock() 437 mock.On(r.Table("people")).Return([]interface{}{ 438 map[string]interface{}{"id": 1, "name": "John Smith"}, 439 map[string]interface{}{"id": 2, "name": "Jane Smith"}, 440 }, nil) 441 442 cursor, err := r.Table("people").Run(mock) 443 if err != nil { 444 t.Errorf("err is: %v", err) 445 } 446 447 var rows []interface{} 448 err = cursor.All(&rows) 449 if err != nil { 450 t.Errorf("err is: %v", err) 451 } 452 453 // Test result of rows 454 455 mock.AssertExpectations(t) 456 } 457 ``` 458 459 If you want the cursor to block on some of the response values, you can pass in 460 a value of type `chan interface{}` and the cursor will block until a value is 461 available to read on the channel. Or you can pass in a function with signature 462 `func() interface{}`: the cursor will call the function (which may block). Here 463 is the example above adapted to use a channel. 464 465 ```go 466 func TestSomething(t *testing.T) { 467 mock := r.NewMock() 468 ch := make(chan []interface{}) 469 mock.On(r.Table("people")).Return(ch, nil) 470 go func() { 471 ch <- []interface{}{ 472 map[string]interface{}{"id": 1, "name": "John Smith"}, 473 map[string]interface{}{"id": 2, "name": "Jane Smith"}, 474 } 475 ch <- []interface{}{map[string]interface{}{"id": 3, "name": "Jack Smith"}} 476 close(ch) 477 }() 478 cursor, err := r.Table("people").Run(mock) 479 if err != nil { 480 t.Errorf("err is: %v", err) 481 } 482 483 var rows []interface{} 484 err = cursor.All(&rows) 485 if err != nil { 486 t.Errorf("err is: %v", err) 487 } 488 489 // Test result of rows 490 491 mock.AssertExpectations(t) 492 } 493 494 ``` 495 496 The mocking implementation is based on amazing https://github.com/stretchr/testify library, thanks to @stretchr for their awesome work! 497 498 ## Benchmarks 499 500 Everyone wants their project's benchmarks to be speedy. And while we know that RethinkDB and the RethinkDB-go driver are quite fast, our primary goal is for our benchmarks to be correct. They are designed to give you, the user, an accurate picture of writes per second (w/s). If you come up with a accurate test that meets this aim, submit a pull request please. 501 502 Thanks to @jaredfolkins for the contribution. 503 504 | Type | Value | 505 | ------------------------- | -------------- | 506 | **Model Name** | MacBook Pro | 507 | **Model Identifier** | MacBookPro11,3 | 508 | **Processor Name** | Intel Core i7 | 509 | **Processor Speed** | 2.3 GHz | 510 | **Number of Processors** | 1 | 511 | **Total Number of Cores** | 4 | 512 | **L2 Cache (per Core)** | 256 KB | 513 | **L3 Cache** | 6 MB | 514 | **Memory** | 16 GB | 515 516 ```bash 517 BenchmarkBatch200RandomWrites 20 557227775 ns/op 518 BenchmarkBatch200RandomWritesParallel10 30 354465417 ns/op 519 BenchmarkBatch200SoftRandomWritesParallel10 100 761639276 ns/op 520 BenchmarkRandomWrites 100 10456580 ns/op 521 BenchmarkRandomWritesParallel10 1000 1614175 ns/op 522 BenchmarkRandomSoftWrites 3000 589660 ns/op 523 BenchmarkRandomSoftWritesParallel10 10000 247588 ns/op 524 BenchmarkSequentialWrites 50 24408285 ns/op 525 BenchmarkSequentialWritesParallel10 1000 1755373 ns/op 526 BenchmarkSequentialSoftWrites 3000 631211 ns/op 527 BenchmarkSequentialSoftWritesParallel10 10000 263481 ns/op 528 ``` 529 530 ## Examples 531 532 Many functions have examples and are viewable in the godoc, alternatively view some more full features examples on the [wiki](https://github.com/rethinkdb/rethinkdb-go/wiki/Examples). 533 534 Another good place to find examples are the tests, almost every term will have a couple of tests that demonstrate how they can be used. 535 536 ## Further reading 537 538 - [RethinkDB-go Goes 1.0](https://www.compose.io/articles/gorethink-goes-1-0/) 539 - [Go, RethinkDB & Changefeeds](https://www.compose.io/articles/go-rethinkdb-and-changefeeds-part-1/) 540 - [Build an IRC bot in Go with RethinkDB changefeeds](http://rethinkdb.com/blog/go-irc-bot/) 541 542 ## License 543 544 Copyright 2013 Daniel Cannon 545 546 Licensed under the Apache License, Version 2.0 (the "License"); 547 you may not use this file except in compliance with the License. 548 You may obtain a copy of the License at 549 550 http://www.apache.org/licenses/LICENSE-2.0 551 552 Unless required by applicable law or agreed to in writing, software 553 distributed under the License is distributed on an "AS IS" BASIS, 554 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 555 See the License for the specific language governing permissions and 556 limitations under the License.