1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
|
package rethinkdb
import (
"bytes"
"encoding/json"
"errors"
"reflect"
"sync"
"github.com/opentracing/opentracing-go"
"golang.org/x/net/context"
"gopkg.in/rethinkdb/rethinkdb-go.v6/encoding"
p "gopkg.in/rethinkdb/rethinkdb-go.v6/ql2"
)
var (
errNilCursor = errors.New("cursor is nil")
errCursorClosed = errors.New("connection connClosed, cannot read cursor")
)
func newCursor(ctx context.Context, conn *Connection, cursorType string, token int64, term *Term, opts map[string]interface{}) *Cursor {
if cursorType == "" {
cursorType = "Cursor"
}
connOpts := &ConnectOpts{}
if conn != nil {
connOpts = conn.opts
}
cursor := &Cursor{
conn: conn,
connOpts: connOpts,
token: token,
cursorType: cursorType,
term: term,
opts: opts,
buffer: make([]interface{}, 0),
responses: make([]json.RawMessage, 0),
ctx: ctx,
}
return cursor
}
// 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
// ...
type Cursor struct {
releaseConn func() error
conn *Connection
connOpts *ConnectOpts
token int64
cursorType string
term *Term
opts map[string]interface{}
ctx context.Context
mu sync.RWMutex
lastErr error
fetching bool
closed bool
finished bool
isAtom bool
isSingleValue bool
pendingSkips int
buffer []interface{}
responses []json.RawMessage
profile interface{}
}
// Profile returns the information returned from the query profiler.
func (c *Cursor) Profile() interface{} {
if c == nil {
return nil
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.profile
}
// Type returns the cursor type (by default "Cursor")
func (c *Cursor) Type() string {
if c == nil {
return "Cursor"
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.cursorType
}
// Err returns nil if no errors happened during iteration, or the actual
// error otherwise.
func (c *Cursor) Err() error {
if c == nil {
return errNilCursor
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.lastErr
}
// Close closes the cursor, preventing further enumeration. If the end is
// encountered, the cursor is connClosed automatically. Close is idempotent.
func (c *Cursor) Close() error {
if c == nil {
return errNilCursor
}
c.mu.Lock()
defer c.mu.Unlock()
var err error
// If cursor is already connClosed return immediately
closed := c.closed
if closed {
return nil
}
// Get connection and check its valid, don't need to lock as this is only
// set when the cursor is created
conn := c.conn
if conn == nil {
return nil
}
if conn.isClosed() {
return nil
}
// Stop any unfinished queries
if !c.finished {
_, _, err = conn.Query(c.ctx, newStopQuery(c.token))
}
if c.releaseConn != nil {
if err := c.releaseConn(); err != nil {
return err
}
}
if span := opentracing.SpanFromContext(c.ctx); span != nil {
span.Finish()
}
c.closed = true
c.conn = nil
c.buffer = nil
c.responses = nil
return err
}
// 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 (c *Cursor) Next(dest interface{}) bool {
if c == nil {
return false
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return false
}
hasMore, err := c.nextLocked(dest, true)
if c.handleErrorLocked(err) != nil {
c.mu.Unlock()
c.Close()
return false
}
c.mu.Unlock()
if !hasMore {
c.Close()
}
return hasMore
}
func (c *Cursor) nextLocked(dest interface{}, progressCursor bool) (bool, error) {
for {
if err := c.seekCursor(true); err != nil {
return false, err
}
if c.closed {
return false, nil
}
if len(c.buffer) == 0 && c.finished {
return false, nil
}
if len(c.buffer) > 0 {
data := c.buffer[0]
if progressCursor {
c.buffer = c.buffer[1:]
}
err := encoding.Decode(dest, data)
if err != nil {
return false, err
}
return true, nil
}
}
}
// 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
func (c *Cursor) Peek(dest interface{}) (bool, error) {
if c == nil {
return false, errNilCursor
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return false, nil
}
hasMore, err := c.nextLocked(dest, false)
if _, isDecodeErr := err.(*encoding.DecodeTypeError); isDecodeErr {
c.mu.Unlock()
return false, err
}
if c.handleErrorLocked(err) != nil {
c.mu.Unlock()
c.Close()
return false, err
}
c.mu.Unlock()
return hasMore, nil
}
// Skip progresses the cursor by one record. It is useful after a successful
// Peek to avoid duplicate decoding work.
func (c *Cursor) Skip() {
if c == nil {
return
}
c.mu.Lock()
defer c.mu.Unlock()
c.pendingSkips++
}
// 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 (c *Cursor) NextResponse() ([]byte, bool) {
if c == nil {
return nil, false
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, false
}
b, hasMore, err := c.nextResponseLocked()
if c.handleErrorLocked(err) != nil {
c.mu.Unlock()
c.Close()
return nil, false
}
c.mu.Unlock()
if !hasMore {
c.Close()
}
return b, hasMore
}
func (c *Cursor) nextResponseLocked() ([]byte, bool, error) {
for {
if err := c.seekCursor(false); err != nil {
return nil, false, err
}
if len(c.responses) == 0 && c.finished {
return nil, false, nil
}
if len(c.responses) > 0 {
var response json.RawMessage
response, c.responses = c.responses[0], c.responses[1:]
return []byte(response), true, nil
}
}
}
// 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 (c *Cursor) All(result interface{}) error {
if c == nil {
return errNilCursor
}
resultv := reflect.ValueOf(result)
if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
panic("result argument must be a slice address")
}
slicev := resultv.Elem()
slicev = slicev.Slice(0, slicev.Cap())
elemt := slicev.Type().Elem()
i := 0
for {
if slicev.Len() == i {
elemp := reflect.New(elemt)
if !c.Next(elemp.Interface()) {
break
}
slicev = reflect.Append(slicev, elemp.Elem())
slicev = slicev.Slice(0, slicev.Cap())
} else {
if !c.Next(slicev.Index(i).Addr().Interface()) {
break
}
}
i++
}
resultv.Elem().Set(slicev.Slice(0, i))
if err := c.Err(); err != nil {
_ = c.Close()
return err
}
if err := c.Close(); err != nil {
return err
}
return nil
}
// 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 (c *Cursor) One(result interface{}) error {
if c == nil {
return errNilCursor
}
if c.IsNil() {
c.Close()
return ErrEmptyResult
}
hasResult := c.Next(result)
if err := c.Err(); err != nil {
c.Close()
return err
}
if err := c.Close(); err != nil {
return err
}
if !hasResult {
return ErrEmptyResult
}
return nil
}
// 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 (c *Cursor) Interface() (interface{}, error) {
if c == nil {
return nil, errNilCursor
}
var results []interface{}
var result interface{}
for c.Next(&result) {
results = append(results, result)
}
if err := c.Err(); err != nil {
return nil, err
}
c.mu.RLock()
isSingleValue := c.isSingleValue
c.mu.RUnlock()
if isSingleValue {
if len(results) == 0 {
return nil, nil
}
return results[0], nil
}
return results, nil
}
// 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 (c *Cursor) Listen(channel interface{}) {
go func() {
channelv := reflect.ValueOf(channel)
if channelv.Kind() != reflect.Chan {
panic("input argument must be a channel")
}
elemt := channelv.Type().Elem()
for {
elemp := reflect.New(elemt)
if !c.Next(elemp.Interface()) {
break
}
channelv.Send(elemp.Elem())
}
c.Close()
channelv.Close()
}()
}
// IsNil tests if the current row is nil.
func (c *Cursor) IsNil() bool {
if c == nil {
return true
}
c.mu.RLock()
defer c.mu.RUnlock()
if len(c.buffer) > 0 {
return c.buffer[0] == nil
}
if len(c.responses) > 0 {
response := c.responses[0]
if response == nil {
return true
}
if string(response) == "null" {
return true
}
return false
}
return true
}
// fetchMore fetches more rows from the database.
//
// If wait is true then it will wait for the database to reply otherwise it
// will return after sending the continue query.
func (c *Cursor) fetchMore() error {
var err error
if !c.fetching {
c.fetching = true
if c.closed {
return errCursorClosed
}
q := Query{
Type: p.Query_CONTINUE,
Token: c.token,
}
c.mu.Unlock()
_, _, err = c.conn.Query(c.ctx, q)
c.mu.Lock()
}
return err
}
// handleError sets the value of lastErr to err if lastErr is not yet set.
func (c *Cursor) handleError(err error) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.handleErrorLocked(err)
}
func (c *Cursor) handleErrorLocked(err error) error {
if c.lastErr == nil {
c.lastErr = err
}
return c.lastErr
}
// extend adds the result of a continue query to the cursor.
func (c *Cursor) extend(response *Response) {
c.mu.Lock()
defer c.mu.Unlock()
c.extendLocked(response)
}
func (c *Cursor) extendLocked(response *Response) {
c.responses = append(c.responses, response.Responses...)
c.finished = response.Type != p.Response_SUCCESS_PARTIAL
c.fetching = false
c.isAtom = response.Type == p.Response_SUCCESS_ATOM
}
// seekCursor takes care of loading more data if needed and applying pending skips
//
// bufferResponse determines whether the response will be parsed into the buffer
func (c *Cursor) seekCursor(bufferResponse bool) error {
if c.lastErr != nil {
return c.lastErr
}
if len(c.buffer) == 0 && len(c.responses) == 0 && c.closed {
return errCursorClosed
}
// Loop over loading data, applying skips as necessary and loading more data as needed
// until either the cursor is connClosed or finished, or we have applied all outstanding
// skips and data is available
for {
c.applyPendingSkips(bufferResponse) // if we are buffering the responses, skip can drain from the buffer
if bufferResponse && len(c.buffer) == 0 && len(c.responses) > 0 {
if err := c.bufferNextResponse(); err != nil {
return err
}
continue // go around the loop again to re-apply pending skips
} else if len(c.buffer) == 0 && len(c.responses) == 0 && !c.finished {
// We skipped all of our data, load some more
if err := c.fetchMore(); err != nil {
return err
}
if c.closed {
return nil
}
continue // go around the loop again to re-apply pending skips
}
return nil
}
}
// applyPendingSkips applies all pending skips to the buffer and
// returns whether there are more pending skips to be applied
//
// if drainFromBuffer is true, we will drain from the buffer, otherwise
// we drain from the responses
func (c *Cursor) applyPendingSkips(drainFromBuffer bool) (stillPending bool) {
if c.pendingSkips == 0 {
return false
}
if drainFromBuffer {
if len(c.buffer) > c.pendingSkips {
c.buffer = c.buffer[c.pendingSkips:]
c.pendingSkips = 0
return false
}
c.pendingSkips -= len(c.buffer)
c.buffer = c.buffer[:0]
return c.pendingSkips > 0
}
if len(c.responses) > c.pendingSkips {
c.responses = c.responses[c.pendingSkips:]
c.pendingSkips = 0
return false
}
c.pendingSkips -= len(c.responses)
c.responses = c.responses[:0]
return c.pendingSkips > 0
}
// bufferResponse reads a single response and stores the result into the buffer
// if the response is from an atomic response, it will check if the
// response contains multiple records and store them all into the buffer
func (c *Cursor) bufferNextResponse() error {
if c.closed {
return errCursorClosed
}
// If there are no responses, nothing to do
if len(c.responses) == 0 {
return nil
}
response := c.responses[0]
c.responses = c.responses[1:]
var value interface{}
decoder := json.NewDecoder(bytes.NewBuffer(response))
if c.connOpts.UseJSONNumber {
decoder.UseNumber()
}
err := decoder.Decode(&value)
if err != nil {
return err
}
value, err = recursivelyConvertPseudotype(value, c.opts)
if err != nil {
return err
}
// If response is an ATOM then try and convert to an array
if data, ok := value.([]interface{}); ok && c.isAtom {
c.buffer = append(c.buffer, data...)
} else if value == nil {
c.buffer = append(c.buffer, nil)
} else {
c.buffer = append(c.buffer, value)
// If this is the only value in the response and the response was an
// atom then set the single value flag
if c.isAtom {
c.isSingleValue = true
}
}
return nil
}
|