Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // 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 | |
| 7 | package driver |
| 8 | |
| 9 | import ( |
| 10 | "errors" |
| 11 | |
| 12 | "github.com/mongodb/mongo-go-driver/bson" |
| 13 | "github.com/mongodb/mongo-go-driver/bson/bsoncodec" |
| 14 | "github.com/mongodb/mongo-go-driver/x/bsonx" |
| 15 | "github.com/mongodb/mongo-go-driver/x/mongo/driver/session" |
| 16 | ) |
| 17 | |
| 18 | // ErrCollation is caused if a collation is given for an invalid server version. |
| 19 | var ErrCollation = errors.New("collation cannot be set for server versions < 3.4") |
| 20 | |
| 21 | // ErrArrayFilters is caused if array filters are given for an invalid server version. |
| 22 | var ErrArrayFilters = errors.New("array filters cannot be set for server versions < 3.6") |
| 23 | |
| 24 | func interfaceToDocument(val interface{}, registry *bsoncodec.Registry) (bsonx.Doc, error) { |
| 25 | if val == nil { |
| 26 | return bsonx.Doc{}, nil |
| 27 | } |
| 28 | |
| 29 | if registry == nil { |
| 30 | registry = bson.DefaultRegistry |
| 31 | } |
| 32 | |
| 33 | if bs, ok := val.([]byte); ok { |
| 34 | // Slight optimization so we'll just use MarshalBSON and not go through the codec machinery. |
| 35 | val = bson.Raw(bs) |
| 36 | } |
| 37 | |
| 38 | // TODO(skriptble): Use a pool of these instead. |
| 39 | buf := make([]byte, 0, 256) |
| 40 | b, err := bson.MarshalAppendWithRegistry(registry, buf, val) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | return bsonx.ReadDoc(b) |
| 45 | } |
| 46 | |
| 47 | func interfaceToElement(key string, i interface{}, registry *bsoncodec.Registry) (bsonx.Elem, error) { |
| 48 | switch conv := i.(type) { |
| 49 | case string: |
| 50 | return bsonx.Elem{key, bsonx.String(conv)}, nil |
| 51 | case bsonx.Doc: |
| 52 | return bsonx.Elem{key, bsonx.Document(conv)}, nil |
| 53 | default: |
| 54 | doc, err := interfaceToDocument(i, registry) |
| 55 | if err != nil { |
| 56 | return bsonx.Elem{}, err |
| 57 | } |
| 58 | |
| 59 | return bsonx.Elem{key, bsonx.Document(doc)}, nil |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func closeImplicitSession(sess *session.Client) { |
| 64 | if sess != nil && sess.SessionType == session.Implicit { |
| 65 | sess.EndSession() |
| 66 | } |
| 67 | } |