7 'ascending': pymongo.ASCENDING,
8 'descending': pymongo.DESCENDING,
10 '2dsphere': pymongo.GEOSPHERE,
11 'hashed': pymongo.HASHED,
16def create_collection(collection):
18 collection.database.create_collection(collection.name)
19 except pymongo.errors.CollectionInvalid:
23def shard_collection(collection, sharding):
24 db_admin = collection.database.client.admin
26 db_admin.command(
'enablesharding', collection.database.name)
27 except pymongo.errors.OperationFailure
as exc:
30 kwargs = _get_kwargs_for_shard_func(sharding)
31 if not _is_collection_sharded(collection):
32 db_admin.command(
'shardcollection', collection.full_name, **kwargs)
35def ensure_db_indexes(dbase, db_settings, sharding_enabled=True):
36 for alias, value
in db_settings.items():
37 collection = getattr(dbase, alias,
None)
38 if collection
is not None:
39 create_collection(collection)
41 indexes = value.get(
'indexes')
44 _ensure_index(index, collection)
45 index_info = collection.index_information()
46 assert len(index_info) == len(indexes) + 1, (
47 'Collection {} have {} indexes, but must have {} '.format(
55 sharding = value.get(
'sharding')
57 shard_collection(collection, sharding)
60def _ensure_index(index, collection):
61 arg, kwargs = _get_args_for_ensure_func(index)
62 kwargs.pop(
'expireAfterSeconds',
None)
64 collection.create_index(arg, **kwargs)
65 except pymongo.errors.OperationFailure
as exc:
67 'ensure_index() failed for {}: {}'.format(collection.name, exc),
71def _get_args_for_ensure_func(index):
73 for key, value
in index.items():
75 if isinstance(value, str):
77 elif isinstance(value, list):
80 arg.append((obj[
'name'], SORT_STR_TO_PYMONGO[obj[
'type']]))
84 if 'background' not in kwargs:
85 kwargs[
'background'] =
True
90def _get_kwargs_for_shard_func(sharding):
93 for key, value
in sharding.items():
95 sharding_key: dict[str, typing.Any]
96 if isinstance(value, str):
97 sharding_key = {value: 1}
98 elif isinstance(value, list):
101 sharding_key[obj[
'name']] = SORT_STR_TO_PYMONGO[obj[
'type']]
103 raise ValueError(
'Cannot handle key: {!r}'.format(value))
104 kwargs[
'key'] = sharding_key
111def _is_collection_sharded(collection):
112 collstats = collection.database.command(
'collstats', collection.name)
113 return collstats.get(
'sharded')