diff options
Diffstat (limited to 'src/mongo/gotools/common/db/namespaces.go')
-rw-r--r-- | src/mongo/gotools/common/db/namespaces.go | 61 |
1 files changed, 35 insertions, 26 deletions
diff --git a/src/mongo/gotools/common/db/namespaces.go b/src/mongo/gotools/common/db/namespaces.go index 908687b1c56..8530b16aa5e 100644 --- a/src/mongo/gotools/common/db/namespaces.go +++ b/src/mongo/gotools/common/db/namespaces.go @@ -2,13 +2,23 @@ package db import ( "fmt" - "github.com/mongodb/mongo-tools/common/bsonutil" + "strings" + "github.com/mongodb/mongo-tools/common/log" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" - "strings" ) +type CollectionInfo struct { + Name string `bson:"name"` + Type string `bson:"type"` + Options *bson.D `bson:"options"` +} + +func (ci *CollectionInfo) IsView() bool { + return ci.Type == "view" +} + // IsNoCmd reeturns true if err indicates a query command is not supported, // otherwise, returns false. func IsNoCmd(err error) bool { @@ -124,7 +134,7 @@ func getCollectionsPre28(database *mgo.Database, name string) (*mgo.Iter, error) return iter, nil } -func GetCollectionOptions(coll *mgo.Collection) (*bson.D, error) { +func GetCollectionInfo(coll *mgo.Collection) (*CollectionInfo, error) { iter, useFullName, err := GetCollections(coll.Database, coll.Name) if err != nil { return nil, err @@ -134,33 +144,32 @@ func GetCollectionOptions(coll *mgo.Collection) (*bson.D, error) { if useFullName { comparisonName = coll.FullName } - collInfo := &bson.D{} + + collInfo := &CollectionInfo{} for iter.Next(collInfo) { - name, err := bsonutil.FindValueByKey("name", collInfo) - if err != nil { - collInfo = nil - continue - } - if nameStr, ok := name.(string); ok { - if nameStr == comparisonName { - // we've found the collection we're looking for - break + if collInfo.Name == comparisonName { + if useFullName { + collName, err := StripDBFromNamespace(collInfo.Name, coll.Database.Name) + if err != nil { + return nil, err + } + collInfo.Name = collName } - } else { - collInfo = nil - continue + break } } + if err := iter.Err(); err != nil { + return nil, err + } + return collInfo, nil +} - if collInfo != nil { - optsInterface, _ := bsonutil.FindValueByKey("options", collInfo) - if optsInterface != nil { - optsD, ok := optsInterface.(bson.D) - if !ok { - return nil, fmt.Errorf("Cannot unmarshal collection options for collection %v.%v", coll.Database, coll.Name) - } - return &optsD, nil - } +func StripDBFromNamespace(namespace string, dbName string) (string, error) { + namespacePrefix := dbName + "." + // if the collection info came from querying system.indexes (2.6 or earlier) then the + // "name" we get includes the db name as well, so we must remove it + if strings.HasPrefix(namespace, namespacePrefix) { + return namespace[len(namespacePrefix):], nil } - return nil, iter.Err() + return "", fmt.Errorf("namespace '%v' format is invalid - expected to start with '%v'", namespace, namespacePrefix) } |