blob: fdc792cd1624daa6b9742d47b3bce9388a2c4e15 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package driver
8
9import (
10 "context"
11
12 "github.com/mongodb/mongo-go-driver/x/bsonx"
13 "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore"
14 "github.com/mongodb/mongo-go-driver/x/mongo/driver/session"
15 "github.com/mongodb/mongo-go-driver/x/mongo/driver/topology"
16 "github.com/mongodb/mongo-go-driver/x/mongo/driver/uuid"
17 "github.com/mongodb/mongo-go-driver/x/network/command"
18 "github.com/mongodb/mongo-go-driver/x/network/description"
19)
20
21// ReadCursor handles the full dispatch cycle and execution of a read command against the provided topology and returns
22// a Cursor over the resulting BSON reader.
23func ReadCursor(
24 ctx context.Context,
25 cmd command.Read,
26 topo *topology.Topology,
27 selecctor description.ServerSelector,
28 clientID uuid.UUID,
29 pool *session.Pool,
30 cursorOpts ...bsonx.Elem,
31) (*BatchCursor, error) {
32
33 ss, err := topo.SelectServer(ctx, selecctor)
34 if err != nil {
35 return nil, err
36 }
37
38 desc := ss.Description()
39 conn, err := ss.Connection(ctx)
40 if err != nil {
41 return nil, err
42 }
43 defer conn.Close()
44
45 if cmd.Session == nil && topo.SupportsSessions() {
46 cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit)
47 if err != nil {
48 return nil, err
49 }
50 }
51
52 rdr, err := cmd.RoundTrip(ctx, desc, conn)
53 if err != nil {
54 if cmd.Session != nil && cmd.Session.SessionType == session.Implicit {
55 cmd.Session.EndSession()
56 }
57 return nil, err
58 }
59
60 cursor, err := NewBatchCursor(bsoncore.Document(rdr), cmd.Session, cmd.Clock, ss.Server, cursorOpts...)
61 if err != nil {
62 if cmd.Session != nil && cmd.Session.SessionType == session.Implicit {
63 cmd.Session.EndSession()
64 }
65 return nil, err
66 }
67
68 return cursor, nil
69}