/
database.go
81 lines (65 loc) · 2.28 KB
/
database.go
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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package mongo
import (
"context"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo/private/cluster"
"github.com/mongodb/mongo-go-driver/mongo/private/ops"
"github.com/mongodb/mongo-go-driver/mongo/readconcern"
"github.com/mongodb/mongo-go-driver/mongo/readpref"
"github.com/mongodb/mongo-go-driver/mongo/writeconcern"
)
// Database performs operations on a given database.
type Database struct {
client *Client
name string
readConcern *readconcern.ReadConcern
writeConcern *writeconcern.WriteConcern
readPreference *readpref.ReadPref
readSelector cluster.ServerSelector
writeSelector cluster.ServerSelector
}
func newDatabase(client *Client, name string) *Database {
db := &Database{
client: client,
name: name,
readPreference: client.readPreference,
readConcern: client.readConcern,
writeConcern: client.writeConcern,
}
latencySelector := cluster.LatencySelector(client.localThreshold)
db.readSelector = cluster.CompositeSelector([]cluster.ServerSelector{
readpref.Selector(db.readPreference),
latencySelector,
})
db.writeSelector = readpref.Selector(readpref.Primary())
return db
}
// Client returns the Client the database was created from.
func (db *Database) Client() *Client {
return db.client
}
// Name returns the name of the database.
func (db *Database) Name() string {
return db.name
}
// Collection gets a handle for a given collection in the database.
func (db *Database) Collection(name string) *Collection {
return newCollection(db, name)
}
// RunCommand runs a command on the database. A user can supply a custom
// context to this method, or nil to default to context.Background().
func (db *Database) RunCommand(ctx context.Context, command interface{}) (bson.Reader, error) {
if ctx == nil {
ctx = context.Background()
}
s, err := db.client.selectServer(ctx, readpref.Selector(readpref.Primary()), readpref.Primary())
if err != nil {
return nil, err
}
return ops.RunCommand(ctx, s, db.Name(), command)
}