Skip to content

Commit 9ff076f

Browse files
committed
Add transactions examples for docs
GODRIVER-422 GODRIVER-828 GODRIVER-788 Change-Id: I5927c58c4ecf89ab8124c87066b394ca6a6b8dc8
1 parent f30f25a commit 9ff076f

File tree

12 files changed

+360
-109
lines changed

12 files changed

+360
-109
lines changed

examples/documentation_examples/examples.go

Lines changed: 239 additions & 58 deletions
Large diffs are not rendered by default.

examples/documentation_examples/examples_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,26 @@ package documentation_examples_test
1111

1212
import (
1313
"context"
14+
"os"
1415
"testing"
16+
"time"
1517

1618
"github.com/mongodb/mongo-go-driver/examples/documentation_examples"
1719
"github.com/mongodb/mongo-go-driver/internal/testutil"
1820
"github.com/mongodb/mongo-go-driver/mongo"
1921
"github.com/mongodb/mongo-go-driver/mongo/options"
22+
"github.com/mongodb/mongo-go-driver/x/bsonx"
2023
"github.com/stretchr/testify/require"
2124
)
2225

2326
func TestDocumentationExamples(t *testing.T) {
27+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
28+
defer cancel()
29+
2430
cs := testutil.ConnString(t)
2531
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(cs.String()))
2632
require.NoError(t, err)
33+
defer client.Disconnect(ctx)
2734

2835
db := client.Database("documentation_examples")
2936

@@ -37,3 +44,36 @@ func TestDocumentationExamples(t *testing.T) {
3744
documentation_examples.UpdateExamples(t, db)
3845
documentation_examples.DeleteExamples(t, db)
3946
}
47+
48+
func TestTransactionExamples(t *testing.T) {
49+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
50+
defer cancel()
51+
cs := testutil.ConnString(t)
52+
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(cs.String()))
53+
require.NoError(t, err)
54+
defer client.Disconnect(ctx)
55+
56+
ver, err := getServerVersion(ctx, client)
57+
if err != nil || testutil.CompareVersions(t, ver, "4.0") < 0 || os.Getenv("TOPOLOGY") != "replica_set" {
58+
t.Skip("server does not support transactions")
59+
}
60+
err = documentation_examples.TransactionsExamples(ctx, client)
61+
require.NoError(t, err)
62+
}
63+
64+
func getServerVersion(ctx context.Context, client *mongo.Client) (string, error) {
65+
serverStatus, err := client.Database("admin").RunCommand(
66+
ctx,
67+
bsonx.Doc{{"serverStatus", bsonx.Int32(1)}},
68+
).DecodeBytes()
69+
if err != nil {
70+
return "", err
71+
}
72+
73+
version, err := serverStatus.LookupErr("version")
74+
if err != nil {
75+
return "", err
76+
}
77+
78+
return version.StringValue(), nil
79+
}

mongo/change_stream.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -177,13 +177,13 @@ func parseOptions(csType StreamType, opts *options.ChangeStreamOptions, registry
177177
func (cs *ChangeStream) runCommand(ctx context.Context, replaceOptions bool) error {
178178
ss, err := cs.client.topology.SelectServer(ctx, cs.db.writeSelector)
179179
if err != nil {
180-
return err
180+
return replaceErrors(err)
181181
}
182182

183183
desc := ss.Description()
184184
conn, err := ss.Connection(ctx)
185185
if err != nil {
186-
return err
186+
return replaceErrors(err)
187187
}
188188
defer conn.Close()
189189

@@ -213,13 +213,13 @@ func (cs *ChangeStream) runCommand(ctx context.Context, replaceOptions bool) err
213213
rdr, err := readCmd.RoundTrip(ctx, desc, conn)
214214
if err != nil {
215215
cs.sess.EndSession(ctx)
216-
return err
216+
return replaceErrors(err)
217217
}
218218

219219
batchCursor, err := driver.NewBatchCursor(bsoncore.Document(rdr), readCmd.Session, readCmd.Clock, ss.Server, cs.getMoreOpts...)
220220
if err != nil {
221221
cs.sess.EndSession(ctx)
222-
return err
222+
return replaceErrors(err)
223223
}
224224
cursor, err := newCursor(batchCursor, cs.registry)
225225
if err != nil {
@@ -483,7 +483,7 @@ func (cs *ChangeStream) Decode(out interface{}) error {
483483
// Err returns the current error.
484484
func (cs *ChangeStream) Err() error {
485485
if cs.err != nil {
486-
return cs.err
486+
return replaceErrors(cs.err)
487487
}
488488
if cs.cursor == nil {
489489
return nil
@@ -498,7 +498,7 @@ func (cs *ChangeStream) Close(ctx context.Context) error {
498498
return nil // cursor is already closed
499499
}
500500

501-
return cs.cursor.Close(ctx)
501+
return replaceErrors(cs.cursor.Close(ctx))
502502
}
503503

504504
// StreamType represents the type of a change stream.

mongo/change_stream_spec_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818
"github.com/mongodb/mongo-go-driver/internal/testutil/helpers"
1919
"github.com/mongodb/mongo-go-driver/mongo/options"
2020
"github.com/mongodb/mongo-go-driver/x/bsonx"
21-
"github.com/mongodb/mongo-go-driver/x/network/command"
2221
)
2322

2423
const csTestsDir = "../data/change-streams"
@@ -84,14 +83,14 @@ func getStreamOptions(test *csTest) *options.ChangeStreamOptions {
8483
}
8584

8685
func changeStreamCompareErrors(t *testing.T, expected map[string]interface{}, actual error) {
87-
if cmdErr, ok := actual.(command.Error); ok {
86+
if cmdErr, ok := actual.(CommandError); ok {
8887
expectedCode := int32(expected["code"].(float64))
8988

9089
if cmdErr.Code != expectedCode {
9190
t.Fatalf("error code mismatch. expected %d, got %d", expectedCode, cmdErr.Code)
9291
}
9392
} else {
94-
t.Fatalf("error was not of type command.Error")
93+
t.Fatalf("error was not of type CommandError")
9594
}
9695
}
9796

mongo/change_stream_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,19 @@ package mongo
88

99
import (
1010
"context"
11-
"github.com/mongodb/mongo-go-driver/mongo/options"
1211
"os"
1312
"testing"
1413
"time"
1514

15+
"github.com/mongodb/mongo-go-driver/mongo/options"
16+
1617
"github.com/mongodb/mongo-go-driver/bson"
1718
"github.com/mongodb/mongo-go-driver/bson/bsontype"
1819
"github.com/mongodb/mongo-go-driver/bson/primitive"
1920
"github.com/mongodb/mongo-go-driver/internal/testutil/helpers"
2021
"github.com/mongodb/mongo-go-driver/mongo/writeconcern"
2122
"github.com/mongodb/mongo-go-driver/x/bsonx"
2223
"github.com/mongodb/mongo-go-driver/x/mongo/driver"
23-
"github.com/mongodb/mongo-go-driver/x/network/command"
2424
"github.com/stretchr/testify/require"
2525
)
2626

@@ -55,7 +55,7 @@ func (er *errorCursor) DecodeBytes() (bson.Raw, error) {
5555
}
5656

5757
func (er *errorCursor) Err() error {
58-
return command.Error{
58+
return CommandError{
5959
Code: er.errCode,
6060
}
6161
}
@@ -270,7 +270,7 @@ func TestChangeStream(t *testing.T) {
270270

271271
_, err = coll.Watch(context.Background(), Pipeline{})
272272
require.Error(t, err)
273-
if _, ok := err.(command.Error); !ok {
273+
if _, ok := err.(CommandError); !ok {
274274
t.Errorf("Should have returned command error, but got %T", err)
275275
}
276276
})
@@ -424,7 +424,7 @@ func TestChangeStream_ReplicaSet(t *testing.T) {
424424
cs := stream
425425
cs.cursor = &Cursor{
426426
bc: driver.NewEmptyBatchCursor(),
427-
err: command.Error{
427+
err: CommandError{
428428
Code: tc.errCode,
429429
},
430430
}

mongo/client.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ func NewClient(opts ...*options.ClientOptions) (*Client, error) {
9191

9292
client.topology, err = topology.New(client.topologyOptions...)
9393
if err != nil {
94-
return nil, replaceTopologyErr(err)
94+
return nil, replaceErrors(err)
9595
}
9696

9797
return client, nil
@@ -102,7 +102,7 @@ func NewClient(opts ...*options.ClientOptions) (*Client, error) {
102102
func (c *Client) Connect(ctx context.Context) error {
103103
err := c.topology.Connect(ctx)
104104
if err != nil {
105-
return replaceTopologyErr(err)
105+
return replaceErrors(err)
106106
}
107107

108108
return nil
@@ -123,7 +123,7 @@ func (c *Client) Disconnect(ctx context.Context) error {
123123
}
124124

125125
c.endSessions(ctx)
126-
return replaceTopologyErr(c.topology.Disconnect(ctx))
126+
return replaceErrors(c.topology.Disconnect(ctx))
127127
}
128128

129129
// Ping verifies that the client can connect to the topology.
@@ -139,7 +139,7 @@ func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error {
139139
}
140140

141141
_, err := c.topology.SelectServer(ctx, description.ReadPrefSelector(rp))
142-
return replaceTopologyErr(err)
142+
return replaceErrors(err)
143143
}
144144

145145
// StartSession starts a new session.
@@ -169,7 +169,7 @@ func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)
169169

170170
sess, err := session.NewClientSession(c.topology.SessionPool, c.id, session.Explicit, coreOpts)
171171
if err != nil {
172-
return nil, replaceTopologyErr(err)
172+
return nil, replaceErrors(err)
173173
}
174174

175175
sess.RetryWrite = c.retryWrites
@@ -458,7 +458,7 @@ func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...
458458
opts...,
459459
)
460460
if err != nil {
461-
return ListDatabasesResult{}, replaceTopologyErr(err)
461+
return ListDatabasesResult{}, replaceErrors(err)
462462
}
463463

464464
return (ListDatabasesResult{}).fromResult(res), nil

mongo/collection.go

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel,
196196
}
197197
}
198198

199-
return &BulkWriteResult{}, replaceTopologyErr(err)
199+
return &BulkWriteResult{}, replaceErrors(err)
200200
}
201201

202202
return &BulkWriteResult{
@@ -331,7 +331,7 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
331331
case command.ErrUnacknowledgedWrite:
332332
return &InsertManyResult{InsertedIDs: result}, ErrUnacknowledgedWrite
333333
default:
334-
return nil, replaceTopologyErr(err)
334+
return nil, replaceErrors(err)
335335
}
336336
if len(res.WriteErrors) > 0 || res.WriteConcernError != nil {
337337
bwErrors := make([]BulkWriteError, 0, len(res.WriteErrors))
@@ -504,7 +504,7 @@ func (coll *Collection) updateOrReplaceOne(ctx context.Context, filter,
504504
opts...,
505505
)
506506
if err != nil && err != command.ErrUnacknowledgedWrite {
507-
return nil, replaceTopologyErr(err)
507+
return nil, replaceErrors(err)
508508
}
509509

510510
res := &UpdateResult{
@@ -617,7 +617,7 @@ func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, upda
617617
opts...,
618618
)
619619
if err != nil && err != command.ErrUnacknowledgedWrite {
620-
return nil, replaceTopologyErr(err)
620+
return nil, replaceErrors(err)
621621
}
622622
res := &UpdateResult{
623623
MatchedCount: r.MatchedCount,
@@ -735,11 +735,11 @@ func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{},
735735
if wce, ok := err.(result.WriteConcernError); ok {
736736
return nil, *convertWriteConcernError(&wce)
737737
}
738-
return nil, replaceTopologyErr(err)
738+
return nil, replaceErrors(err)
739739
}
740740

741741
cursor, err := newCursor(batchCursor, coll.registry)
742-
return cursor, replaceTopologyErr(err)
742+
return cursor, replaceErrors(err)
743743
}
744744

745745
// CountDocuments gets the number of documents matching the filter.
@@ -789,7 +789,7 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{},
789789
countOpts,
790790
)
791791

792-
return count, replaceTopologyErr(err)
792+
return count, replaceErrors(err)
793793
}
794794

795795
// EstimatedDocumentCount gets an estimate of the count of documents in a collection using collection metadata.
@@ -837,7 +837,7 @@ func (coll *Collection) EstimatedDocumentCount(ctx context.Context,
837837
countOpts,
838838
)
839839

840-
return count, replaceTopologyErr(err)
840+
return count, replaceErrors(err)
841841
}
842842

843843
// Distinct finds the distinct values for a specified field across a single
@@ -886,7 +886,7 @@ func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter i
886886
opts...,
887887
)
888888
if err != nil {
889-
return nil, replaceTopologyErr(err)
889+
return nil, replaceErrors(err)
890890
}
891891

892892
return res.Values, nil
@@ -937,11 +937,11 @@ func (coll *Collection) Find(ctx context.Context, filter interface{},
937937
opts...,
938938
)
939939
if err != nil {
940-
return nil, replaceTopologyErr(err)
940+
return nil, replaceErrors(err)
941941
}
942942

943943
cursor, err := newCursor(batchCursor, coll.registry)
944-
return cursor, replaceTopologyErr(err)
944+
return cursor, replaceErrors(err)
945945
}
946946

947947
// FindOne returns up to one document that matches the model.
@@ -1012,11 +1012,11 @@ func (coll *Collection) FindOne(ctx context.Context, filter interface{},
10121012
findOpts...,
10131013
)
10141014
if err != nil {
1015-
return &SingleResult{err: replaceTopologyErr(err)}
1015+
return &SingleResult{err: replaceErrors(err)}
10161016
}
10171017

10181018
cursor, err := newCursor(batchCursor, coll.registry)
1019-
return &SingleResult{cur: cursor, reg: coll.registry, err: replaceTopologyErr(err)}
1019+
return &SingleResult{cur: cursor, reg: coll.registry, err: replaceErrors(err)}
10201020
}
10211021

10221022
// FindOneAndDelete find a single document and deletes it, returning the
@@ -1066,7 +1066,7 @@ func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}
10661066
)
10671067

10681068
if err != nil {
1069-
return &SingleResult{err: replaceTopologyErr(err)}
1069+
return &SingleResult{err: replaceErrors(err)}
10701070
}
10711071

10721072
if res.WriteConcernError != nil {
@@ -1132,7 +1132,7 @@ func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{
11321132
opts...,
11331133
)
11341134
if err != nil {
1135-
return &SingleResult{err: replaceTopologyErr(err)}
1135+
return &SingleResult{err: replaceErrors(err)}
11361136
}
11371137

11381138
if res.WriteConcernError != nil {
@@ -1201,7 +1201,7 @@ func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}
12011201
opts...,
12021202
)
12031203
if err != nil {
1204-
return &SingleResult{err: replaceTopologyErr(err)}
1204+
return &SingleResult{err: replaceErrors(err)}
12051205
}
12061206

12071207
if res.WriteConcernError != nil {
@@ -1259,7 +1259,7 @@ func (coll *Collection) Drop(ctx context.Context) error {
12591259
coll.client.topology.SessionPool,
12601260
)
12611261
if err != nil && !command.IsNotFound(err) {
1262-
return replaceTopologyErr(err)
1262+
return replaceErrors(err)
12631263
}
12641264
return nil
12651265
}

0 commit comments

Comments
 (0)