Create a new or get an existing capped PyMongo collection.
(cls)
| 237 | |
| 238 | @classmethod |
| 239 | def _get_capped_collection(cls): |
| 240 | """Create a new or get an existing capped PyMongo collection.""" |
| 241 | db = cls._get_db() |
| 242 | collection_name = cls._get_collection_name() |
| 243 | |
| 244 | # Get max document limit and max byte size from meta. |
| 245 | max_size = cls._meta.get("max_size") or 10 * 2**20 # 10MB default |
| 246 | max_documents = cls._meta.get("max_documents") |
| 247 | |
| 248 | # MongoDB will automatically raise the size to make it a multiple of |
| 249 | # 256 bytes. We raise it here ourselves to be able to reliably compare |
| 250 | # the options below. |
| 251 | if max_size % 256: |
| 252 | max_size = (max_size // 256 + 1) * 256 |
| 253 | |
| 254 | # If the collection already exists and has different options |
| 255 | # (i.e. isn't capped or has different max/size), raise an error. |
| 256 | if collection_name in list_collection_names( |
| 257 | db, include_system_collections=True |
| 258 | ): |
| 259 | collection = db[collection_name] |
| 260 | options = collection.options() |
| 261 | if options.get("max") != max_documents or options.get("size") != max_size: |
| 262 | raise InvalidCollectionError( |
| 263 | 'Cannot create collection "{}" as a capped ' |
| 264 | "collection as it already exists".format(cls._collection) |
| 265 | ) |
| 266 | |
| 267 | return collection |
| 268 | |
| 269 | # Create a new capped collection. |
| 270 | opts = {"capped": True, "size": max_size} |
| 271 | if max_documents: |
| 272 | opts["max"] = max_documents |
| 273 | |
| 274 | return db.create_collection(collection_name, **opts) |
| 275 | |
| 276 | @classmethod |
| 277 | def _get_timeseries_collection(cls): |
no test coverage detected