Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID
(self, document: Mapping)
| 139 | return self._storage |
| 140 | |
| 141 | def insert(self, document: Mapping) -> int: |
| 142 | """ |
| 143 | Insert a new document into the table. |
| 144 | |
| 145 | :param document: the document to insert |
| 146 | :returns: the inserted document's ID |
| 147 | """ |
| 148 | |
| 149 | # Make sure the document implements the ``Mapping`` interface |
| 150 | if not isinstance(document, Mapping): |
| 151 | raise ValueError('Document is not a Mapping') |
| 152 | |
| 153 | # First, we get the document ID for the new document |
| 154 | if isinstance(document, self.document_class): |
| 155 | # For a `Document` object we use the specified ID |
| 156 | doc_id = document.doc_id |
| 157 | |
| 158 | # We also reset the stored next ID so the next insert won't |
| 159 | # re-use document IDs by accident when storing an old value |
| 160 | self._next_id = None |
| 161 | else: |
| 162 | # In all other cases we use the next free ID |
| 163 | doc_id = self._get_next_id() |
| 164 | |
| 165 | # Now, we update the table and add the document |
| 166 | def updater(table: dict): |
| 167 | if doc_id in table: |
| 168 | raise ValueError(f'Document with ID {str(doc_id)} ' |
| 169 | f'already exists') |
| 170 | |
| 171 | # By calling ``dict(document)`` we convert the data we got to a |
| 172 | # ``dict`` instance even if it was a different class that |
| 173 | # implemented the ``Mapping`` interface |
| 174 | table[doc_id] = dict(document) |
| 175 | |
| 176 | # See below for details on ``Table._update`` |
| 177 | self._update_table(updater) |
| 178 | |
| 179 | return doc_id |
| 180 | |
| 181 | def insert_multiple(self, documents: Iterable[Mapping]) -> List[int]: |
| 182 | """ |