Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion mongodb/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,25 @@ module github.com/philippgille/gokv/mongodb
go 1.20

require (
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8
go.mongodb.org/mongo-driver v1.13.1
github.com/philippgille/gokv/encoding v0.6.0
github.com/philippgille/gokv/test v0.6.0
github.com/philippgille/gokv/util v0.6.0
)

require (
github.com/go-test/deep v1.0.4 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/philippgille/gokv v0.6.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/text v0.7.0 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
)
51 changes: 51 additions & 0 deletions mongodb/go.sum
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8 h1:DujepqpGd1hyOd7aW59XpK7Qymp8iy83xq74fLr21is=
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q=
github.com/go-test/deep v1.0.4 h1:u2CU3YKy9I2pmu9pX0eq50wCgjfGIt539SqR7FbHiho=
github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/philippgille/gokv v0.5.1-0.20191011213304-eb77f15b9c61/go.mod h1:OCoWPt+mbYuTO1FUVrQ2SxQU0oaaHBsn6lRhFX3JHOc=
github.com/philippgille/gokv v0.6.0 h1:fNEx/tSwV73nzlYd3iRYB8F+SEVJNNFzH1gsaT8SK2c=
github.com/philippgille/gokv v0.6.0/go.mod h1:tjXRFw9xDHgxLS8WJdfYotKGWp8TWqu4RdXjMDG/XBo=
Expand All @@ -16,5 +24,48 @@ github.com/philippgille/gokv/test v0.6.0 h1:pe4HsmywhKSNFlrtkFMnSP4K4wHlVQPUhYSv
github.com/philippgille/gokv/test v0.6.0/go.mod h1:yawxKr4W1Qk0RqvZwiZSs6QYrXTV3iJHt43IpH8k7AI=
github.com/philippgille/gokv/util v0.6.0 h1:GrTxVENzKBxs8lB3tnaA88mKOuVPT7atZPplxX+PNmo=
github.com/philippgille/gokv/util v0.6.0/go.mod h1:ovoDHZ2Svr7YX972SPPJQRXbhHEy3Gb20HRH/Tr9BiQ=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver v1.13.1 h1:YIc7HTYsKndGK4RFzJ3covLz1byri52x0IoMB0Pt/vk=
go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
105 changes: 63 additions & 42 deletions mongodb/mongodb.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
package mongodb

import (
"context"
"time"

"github.com/globalsign/mgo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"

"github.com/philippgille/gokv/encoding"
"github.com/philippgille/gokv/util"
)

var setOpt = options.Replace().SetUpsert(true)

// item is the document that's stored in the MongoDB collection.
// mgo (un-)marshalls it to/from bson automatically, when reading from / writing to MongoDB.
// It sounds like (un-)marshalling twice is inefficient, but the mgo (un-)marshalling
// only allows maps and structs.
// Having the gokv package user's value marshalled by ourselves allows any value to be used,
// so the MongoDB implementation works the same as any other gokv.Store implementation.
// mongo (un-)marshalls it to/from BSON automatically, when reading from / writing to MongoDB.
// In a previous version where we used github.com/globalsign/mgo, we had to do this
// in order to support all types that a gokv value can have, including strings and other simple values,
// because mgo only supported marshalling of structs and maps.
// See https://github.com/globalsign/mgo/blob/113d3961e7311526535a1ef7042196563d442761/bson/bson.go#L538.
// Now with the official MongoDB driver there's `bson.MarshalValue()` for simple values,
// but we still need to use a struct to be able to use the "_id" field as key (see below).
// And bson.MarshalValue() requires marshallers to be registered, whereas with our
// codecs the user can just define custom marshal methods on their types.
type item struct {
// There are advantages and disavantages regarding the use of a string as "_id" instead of MongoDB's default ObjectId.
// We can't use the ObjectId because we only have the key that the gokv package user passes us as parameter.
Expand All @@ -32,19 +41,18 @@ type item struct {
// - https://github.com/mongodb/docs/blob/e1b05bac8616fdfac13bedd79516a5ac33d4afdf/source/reference/bson-types.txt#L41
// - https://github.com/mongodb/docs/blob/85171fd9fcc1cf2a5dc6f297b2b026c86bfbfd9d/source/indexes.txt#L46
// - https://github.com/mongodb/docs/blob/81d03d2463bc995a451759ce44087fe7ecd4db74/source/core/sharding-shard-key.txt#L91
//
// There are multiple ways to tag for mgo: https://github.com/globalsign/mgo/blob/113d3961e7311526535a1ef7042196563d442761/bson/bson.go#L538.
// But without "bson" go_vet says: "struct field tag `_id` not compatible with reflect.StructTag.Get: bad syntax for struct tag pair"
K string `bson:"_id"`
V []byte // "v" will be used as field name
}

// Client is a gokv.Store implementation for MongoDB.
type Client struct {
c *mgo.Collection
// Only needed for closing.
session *mgo.Session
codec encoding.Codec
c *mongo.Collection
codec encoding.Codec

// Client and cancel are required on call to `Close()`
client *mongo.Client
cancel context.CancelFunc
}

// Set stores the given value for the given key.
Expand All @@ -62,12 +70,13 @@ func (c Client) Set(k string, v any) error {
}

item := item{
// K needs to be specified, otherwise an update operation (on an existing document) would lead to the "_id" being overwritten by "",
// K needs to be specified, otherwise an update operation (on an existing document)
// would lead to the "_id" being overwritten by "",
// which 1) we don't want of course and 2) leads to an error anyway.
K: k,
V: data,
}
_, err = c.c.UpsertId(k, item)
_, err = c.c.ReplaceOne(context.Background(), bson.D{{"_id", k}}, item, setOpt)
if err != nil {
return err
}
Expand All @@ -87,9 +96,9 @@ func (c Client) Get(k string, v any) (found bool, err error) {
}

item := new(item)
err = c.c.FindId(k).One(item)
err = c.c.FindOne(context.Background(), bson.D{{"_id", k}}).Decode(item)
// If no value was found return false
if err == mgo.ErrNotFound {
if err == mongo.ErrNoDocuments {
return false, nil
} else if err != nil {
return false, err
Expand All @@ -107,29 +116,27 @@ func (c Client) Delete(k string) error {
return err
}

err := c.c.RemoveId(k)
if err != mgo.ErrNotFound {
return err
}
return nil
_, err := c.c.DeleteOne(context.Background(), bson.D{{"_id", k}})
// No need to check for mongo.ErrNoDocuments, because DeleteOne() doesn't return
// any error if no document was deleted. This differs from a previous version
// where we used mgo.
return err
}

// Close closes the client.
// It must be called to release any open resources.
func (c Client) Close() error {
c.session.Close()
return nil
c.cancel()
return c.client.Disconnect(context.Background())
}

// Options are the options for the MongoDB client.
type Options struct {
// Seed servers for the initial connection to the MongoDB cluster.
// Format: [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options].
// E.g.: "localhost" (the port defaults to 27017).
// Optional ("localhost" by default).
// E.g.: "mongodb://localhost" (the port defaults to 27017).
// Optional ("mongodb://localhost" by default).
// For a detailed documentation and more examples see https://github.com/mongodb/docs/blob/01fa14decadc116b09ecdeae049e6744f16bf97f/source/reference/connection-string.txt.
// For the options you need to stick to the mgo documentation (the package that gokv uses) instead of the official MongoDB documentation:
// https://github.com/globalsign/mgo/blob/113d3961e7311526535a1ef7042196563d442761/session.go#L236.
ConnectionString string
// The name of the database to use.
// Optional ("gokv" by default).
Expand All @@ -145,7 +152,7 @@ type Options struct {
// DefaultOptions is an Options object with default values.
// ConnectionString: "localhost", DatabaseName: "gokv", CollectionName: "item", Codec: encoding.JSON
var DefaultOptions = Options{
ConnectionString: "localhost",
ConnectionString: "mongodb://localhost",
DatabaseName: "gokv",
CollectionName: "item",
Codec: encoding.JSON,
Expand All @@ -154,32 +161,46 @@ var DefaultOptions = Options{
// NewClient creates a new MongoDB client.
//
// You must call the Close() method on the client when you're done working with it.
func NewClient(options Options) (Client, error) {
func NewClient(opts Options) (Client, error) {
result := Client{}

// Set default values
if options.ConnectionString == "" {
options.ConnectionString = DefaultOptions.ConnectionString
if opts.ConnectionString == "" {
opts.ConnectionString = DefaultOptions.ConnectionString
}
if options.DatabaseName == "" {
options.DatabaseName = DefaultOptions.DatabaseName
if opts.DatabaseName == "" {
opts.DatabaseName = DefaultOptions.DatabaseName
}
if options.CollectionName == "" {
options.CollectionName = DefaultOptions.CollectionName
if opts.CollectionName == "" {
opts.CollectionName = DefaultOptions.CollectionName
}
if options.Codec == nil {
options.Codec = DefaultOptions.Codec
if opts.Codec == nil {
opts.Codec = DefaultOptions.Codec
}

session, err := mgo.DialWithTimeout(options.ConnectionString, 2*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(opts.ConnectionString))
if err != nil {
return result, err
}
c := session.DB(options.DatabaseName).C(options.CollectionName)

// The above `Connect` doesn't block for server discovery. But like with other
// gokv store implementations, we want to ensure that after client creation
// it's ready to use. So we call `Ping` to block until the server is discovered.
pingCtx, pingCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer pingCancel()
err = client.Ping(pingCtx, readpref.Primary())
if err != nil {
return result, err
}

c := client.Database(opts.DatabaseName).Collection(opts.CollectionName)

result.c = c
result.session = session
result.codec = options.Codec
result.codec = opts.Codec
result.client = client
result.cancel = cancel

return result, nil
}
22 changes: 15 additions & 7 deletions mongodb/mongodb_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package mongodb_test

import (
"context"
"log"
"strings"
"testing"
"time"

"github.com/globalsign/mgo"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"

"github.com/philippgille/gokv/encoding"
"github.com/philippgille/gokv/mongodb"
"github.com/philippgille/gokv/test"
Expand Down Expand Up @@ -100,11 +105,11 @@ func TestErrors(t *testing.T) {

// Test bad connection string
options := mongodb.Options{
ConnectionString: "forceError!",
ConnectionString: "mongodb://forceError!",
}
_, err = mongodb.NewClient(options)
if err.Error() != "no reachable servers" {
t.Errorf(`Expected a "no reachable servers" error, but instead got: %v`, err)
if !strings.Contains(err.Error(), "no such host") {
t.Errorf(`Expected a "no such host" error, but instead got: %v`, err)
}
}

Expand Down Expand Up @@ -188,13 +193,16 @@ func TestClose(t *testing.T) {

// checkConnection returns true if a connection could be made, false otherwise.
func checkConnection() bool {
session, err := mgo.DialWithTimeout("localhost", 2*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost"))
if err != nil {
log.Printf("An error occurred during testing the connection to the server: %v\n", err)
return false
}
defer session.Close()
if err = session.Ping(); err != nil {
defer client.Disconnect(ctx)
if err = client.Ping(ctx, readpref.Primary()); err != nil {
log.Printf("An error occurred during testing the connection to the server: %v\n", err)
return false
}
Expand Down