blob: 2a4f41308be8fd0201b3b270000a335130efc978 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// 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
7package command
8
9import (
10 "errors"
11 "strings"
12)
13
14// Namespace encapsulates a database and collection name, which together
15// uniquely identifies a collection within a MongoDB cluster.
16type Namespace struct {
17 DB string
18 Collection string
19}
20
21// NewNamespace returns a new Namespace for the
22// given database and collection.
23func NewNamespace(db, collection string) Namespace { return Namespace{DB: db, Collection: collection} }
24
25// ParseNamespace parses a namespace string into a Namespace.
26//
27// The namespace string must contain at least one ".", the first of which is the separator
28// between the database and collection names. If not, the default (invalid) Namespace is returned.
29func ParseNamespace(name string) Namespace {
30 index := strings.Index(name, ".")
31 if index == -1 {
32 return Namespace{}
33 }
34
35 return Namespace{
36 DB: name[:index],
37 Collection: name[index+1:],
38 }
39}
40
41// FullName returns the full namespace string, which is the result of joining the database
42// name and the collection name with a "." character.
43func (ns *Namespace) FullName() string {
44 return strings.Join([]string{ns.DB, ns.Collection}, ".")
45}
46
47// Validate validates the namespace.
48func (ns *Namespace) Validate() error {
49 if err := ns.validateDB(); err != nil {
50 return err
51 }
52
53 return ns.validateCollection()
54}
55
56// validateDB ensures the database name is not an empty string, contain a ".",
57// or contain a " ".
58func (ns *Namespace) validateDB() error {
59 if ns.DB == "" {
60 return errors.New("database name cannot be empty")
61 }
62 if strings.Contains(ns.DB, " ") {
63 return errors.New("database name cannot contain ' '")
64 }
65 if strings.Contains(ns.DB, ".") {
66 return errors.New("database name cannot contain '.'")
67 }
68
69 return nil
70}
71
72// validateCollection ensures the collection name is not an empty string.
73func (ns *Namespace) validateCollection() error {
74 if ns.Collection == "" {
75 return errors.New("collection name cannot be empty")
76 }
77
78 return nil
79}