def __init__(self, database, name, write_concern=None, codec_options=None): if not isinstance(name, (bytes, unicode)): raise TypeError( "TxMongo: name must be an instance of (bytes, unicode).") if not name or ".." in name: raise InvalidName("TxMongo: collection names cannot be empty.") if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")): msg = "TxMongo: collection names must not contain '$', '{0}'".format( repr(name)) raise InvalidName(msg) if name[0] == "." or name[-1] == ".": msg = "TxMongo: collection names must not start or end with '.', '{0}'".format( repr(name)) raise InvalidName(msg) if "\x00" in name: raise InvalidName( "TxMongo: collection names must not contain the null character." ) self._database = database self._collection_name = unicode(name) self.__write_concern = write_concern self.__codec_options = codec_options
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring`. Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): any additional rename options should be passed as keyword arguments (i.e. ``dropTarget=True``) .. versionadded:: 1.7 support for accepting keyword arguments for rename options """ if not isinstance(new_name, basestring): raise TypeError("new_name must be an instance of basestring") if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in new_name and not new_name.startswith("oplog.$main"): raise InvalidName("collection names must not contain '$'") new_name = "%s.%s" % (self.__database.name, new_name) self.__database.connection.admin.command("renameCollection", self.__full_name, to=new_name, **kwargs)
def __check_name(self, name): for invalid_char in [" ", ".", "$", "/", "\\"]: if invalid_char in name: raise InvalidName("database names cannot contain the " "character %r" % invalid_char) if not name: raise InvalidName("database name cannot be the empty string")
def __init__(self, database, name, create=False, **kwargs): super(Collection, self).__init__() if not isinstance(name, string_type): raise TypeError("name must be an instance " "of %s" % (string_type.__name__, )) if not name or ".." in name: raise InvalidName("collection names cannot be empty") if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")): raise InvalidName("collection names must not " "contain '$': %r" % name) if name[0] == "." or name[-1] == ".": raise InvalidName("collection names must not start " "or end with '.': %r" % name) if "\x00" in name: raise InvalidName("collection names must not contain the " "null character") collation = validate_collation_or_none(kwargs.pop('collation', None)) self.__database = database self.__name = _unicode(name) self.__full_name = _UJOIN % (self.__database.name, self.__name) if create or kwargs or collation: self.__create(kwargs, collation)
def rename(self, new_name): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring`. Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection """ if not isinstance(new_name, basestring): raise TypeError("new_name must be an instance of basestring") if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if "$" in new_name: raise InvalidName("collection names must not contain '$'") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") rename_command = SON([("renameCollection", self.__full_name), ("to", "%s.%s" % (self.__database.name, new_name))]) self.__database.connection.admin.command(rename_command)
def _check_database_name(name): """Check if a database name is valid.""" if not name: raise InvalidName("database name cannot be the empty string") for invalid_char in [" ", ".", "$", "/", "\\", "\x00"]: if invalid_char in name: raise InvalidName("database names cannot contain the " "character %r" % invalid_char)
def _check_database_name(name): """Check if a database name is valid.""" if not name: raise InvalidName("database name cannot be the empty string") for invalid_char in [' ', '.', '$', '/', '\\', '\x00', '"']: if invalid_char in name: raise InvalidName("database names cannot contain the " "character %r" % invalid_char)
def __init__(self, database, name, options=None): """Get / create a Mongo collection. Raises :class:`TypeError` if `name` is not an instance of :class:`basestring`. Raises :class:`~pymongo.errors.InvalidName` if `name` is not a valid collection name. Raises :class:`TypeError` if `options` is not an instance of :class:`dict`. If `options` is non-empty a create command will be sent to the database. Otherwise the collection will be created implicitly on first use. :Parameters: - `database`: the database to get a collection from - `name`: the name of the collection to get - `options`: dictionary of collection options. see :meth:`~pymongo.database.Database.create_collection` for details. .. mongodoc:: collections """ if not isinstance(name, basestring): raise TypeError("name must be an instance of basestring") if options is not None and not isinstance(options, dict): raise TypeError("options must be an instance of dict") if not name or ".." in name: raise InvalidName("collection names cannot be empty") if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")): raise InvalidName("collection names must not " "contain '$': %r" % name) if name[0] == "." or name[-1] == ".": raise InvalidName("collecion names must not start " "or end with '.': %r" % name) if "\x00" in name: raise InvalidName("collection names must not contain the " "null character") self.__database = database self.__name = unicode(name) self.__full_name = u"%s.%s" % (self.__database.name, self.__name) # TODO remove the callable_value wrappers after deprecation is complete self.__database_w = helpers.callable_value(self.__database, "Collection.database") self.__name_w = helpers.callable_value(self.__name, "Collection.name") self.__full_name_w = helpers.callable_value(self.__full_name, "Collection.full_name") if options is not None: self.__create(options)
def check_collection_name(self, collection_name): ''' Can use collection instance as well, but then this function needs to be async. The criteria didn't say anything about "waiting on a response from DB" ''' if not collection_name or ".." in collection_name: raise InvalidName("collection names cannot be empty") if collection_name[0] == "." or collection_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in collection_name and not collection_name.startswith( "oplog.$main"): raise InvalidName("collection names must not contain '$'") if collection_name.startswith("service."): raise InvalidName("collection names cannot start with service") if "\x00" in collection_name: raise InvalidName( "collection names must not contain the null character") return True
def __getattr__(self, name): """Get a collection of this database by name. Raises InvalidName if an invalid collection name is used or if the collection name is not in the collections list. :Parameters: - `name`: the name of the collection to get """ if name not in self._collections: raise InvalidName( 'Collection {name} is not in collections list'.format( name=name, )) return Collection(self, name)
def _element_to_bson(key, value, check_keys): if not isinstance(key, basestring): raise InvalidDocument("documents must have only string keys, " "key was %r" % key) if check_keys: if key.startswith("$"): raise InvalidName("key %r must not start with '$'" % key) if "." in key: raise InvalidName("key %r must not contain '.'" % key) name = _make_c_string(key, True) if isinstance(value, float): return "\x01" + name + struct.pack("<d", value) # Use Binary w/ subtype 3 for UUID instances try: import uuid if isinstance(value, uuid.UUID): value = Binary(value.bytes, subtype=3) except ImportError: pass if isinstance(value, Binary): subtype = value.subtype if subtype == 2: value = struct.pack("<i", len(value)) + value return "\x05%s%s%s%s" % (name, struct.pack( "<i", len(value)), chr(subtype), value) if isinstance(value, Code): cstring = _make_c_string(value) scope = _dict_to_bson(value.scope, False, False) full_length = struct.pack("<i", 8 + len(cstring) + len(scope)) length = struct.pack("<i", len(cstring)) return "\x0F" + name + full_length + length + cstring + scope if isinstance(value, str): cstring = _make_c_string(value) length = struct.pack("<i", len(cstring)) return "\x02" + name + length + cstring if isinstance(value, unicode): cstring = _make_c_string(value) length = struct.pack("<i", len(cstring)) return "\x02" + name + length + cstring if isinstance(value, dict): return "\x03" + name + _dict_to_bson(value, check_keys, False) if isinstance(value, (list, tuple)): as_dict = SON(zip([str(i) for i in range(len(value))], value)) return "\x04" + name + _dict_to_bson(as_dict, check_keys, False) if isinstance(value, ObjectId): return "\x07" + name + value.binary if value is True: return "\x08" + name + "\x01" if value is False: return "\x08" + name + "\x00" if isinstance(value, (int, long)): # TODO this is a really ugly way to check for this... if value > 2**64 / 2 - 1 or value < -2**64 / 2: raise OverflowError("MongoDB can only handle up to 8-byte ints") if value > 2**32 / 2 - 1 or value < -2**32 / 2: return "\x12" + name + struct.pack("<q", value) return "\x10" + name + struct.pack("<i", value) if isinstance(value, datetime.datetime): millis = int( calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000) return "\x09" + name + struct.pack("<q", millis) if value is None: return "\x0A" + name if isinstance(value, _RE_TYPE): pattern = value.pattern flags = "" if value.flags & re.IGNORECASE: flags += "i" if value.flags & re.LOCALE: flags += "l" if value.flags & re.MULTILINE: flags += "m" if value.flags & re.DOTALL: flags += "s" if value.flags & re.UNICODE: flags += "u" if value.flags & re.VERBOSE: flags += "x" return "\x0B" + name + _make_c_string(pattern, True) + \ _make_c_string(flags) if isinstance(value, DBRef): return _element_to_bson(key, value.as_doc(), False) raise InvalidDocument("cannot convert value of type %s to bson" % type(value))
def __init__(self, database, name, options=None, create=False, **kwargs): """Get / create a Mongo collection. Raises :class:`TypeError` if `name` is not an instance of :class:`basestring`. Raises :class:`~pymongo.errors.InvalidName` if `name` is not a valid collection name. Any additional keyword arguments will be used as options passed to the create command. See :meth:`~pymongo.database.Database.create_collection` for valid options. If `create` is ``True`` or additional keyword arguments are present a create command will be sent. Otherwise, a create command will not be sent and the collection will be created implicitly on first use. :Parameters: - `database`: the database to get a collection from - `name`: the name of the collection to get - `options`: DEPRECATED dictionary of collection options - `create` (optional): if ``True``, force collection creation even without options being set - `**kwargs` (optional): additional keyword arguments will be passed as options for the create collection command .. versionchanged:: 1.5 deprecating `options` in favor of kwargs .. versionadded:: 1.5 the `create` parameter .. mongodoc:: collections """ super(Collection, self).__init__(slave_okay=database.slave_okay, safe=database.safe, **(database.get_lasterror_options())) if not isinstance(name, basestring): raise TypeError("name must be an instance of basestring") if options is not None: warnings.warn("the options argument to Collection is deprecated " "and will be removed. please use kwargs instead.", DeprecationWarning) if not isinstance(options, dict): raise TypeError("options must be an instance of dict") options.update(kwargs) elif kwargs: options = kwargs if not name or ".." in name: raise InvalidName("collection names cannot be empty") if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")): raise InvalidName("collection names must not " "contain '$': %r" % name) if name[0] == "." or name[-1] == ".": raise InvalidName("collection names must not start " "or end with '.': %r" % name) if "\x00" in name: raise InvalidName("collection names must not contain the " "null character") self.__database = database self.__name = unicode(name) self.__full_name = u"%s.%s" % (self.__database.name, self.__name) if create or options is not None: self.__create(options)
def __init__(self, database, name, create=False, **kwargs): """Get / create a Mongo collection. Raises :class:`TypeError` if `name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `name` is not a valid collection name. Any additional keyword arguments will be used as options passed to the create command. See :meth:`~pymongo.database.Database.create_collection` for valid options. If `create` is ``True`` or additional keyword arguments are present a create command will be sent. Otherwise, a create command will not be sent and the collection will be created implicitly on first use. :Parameters: - `database`: the database to get a collection from - `name`: the name of the collection to get - `create` (optional): if ``True``, force collection creation even without options being set - `**kwargs` (optional): additional keyword arguments will be passed as options for the create collection command .. versionchanged:: 2.2 Removed deprecated argument: options .. versionadded:: 2.1 uuid_subtype attribute .. versionchanged:: 1.5 deprecating `options` in favor of kwargs .. versionadded:: 1.5 the `create` parameter .. mongodoc:: collections """ super(Collection, self).__init__(slave_okay=database.slave_okay, read_preference=database.read_preference, safe=database.safe, **(database.get_lasterror_options())) if not isinstance(name, basestring): raise TypeError("name must be an instance " "of %s" % (basestring.__name__, )) if not name or ".." in name: raise InvalidName("collection names cannot be empty") if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")): raise InvalidName("collection names must not " "contain '$': %r" % name) if name[0] == "." or name[-1] == ".": raise InvalidName("collection names must not start " "or end with '.': %r" % name) if "\x00" in name: raise InvalidName("collection names must not contain the " "null character") self.__database = database self.__name = unicode(name) self.__uuid_subtype = OLD_UUID_SUBTYPE self.__full_name = u"%s.%s" % (self.__database.name, self.__name) if create or kwargs: self.__create(kwargs)