|
12 | 12 | # See the License for the specific language governing permissions and
|
13 | 13 | # limitations under the License.
|
14 | 14 | import warnings
|
| 15 | +from decimal import Decimal |
15 | 16 |
|
16 | 17 | import numpy as np
|
17 | 18 | import pandas as pd
|
|
25 | 26 | import pymongo.errors
|
26 | 27 | from bson import encode
|
27 | 28 | from bson.codec_options import TypeEncoder, TypeRegistry
|
| 29 | +from bson.decimal128 import Decimal128 |
28 | 30 | from bson.raw_bson import RawBSONDocument
|
29 | 31 | from numpy import ndarray
|
30 | 32 | from pyarrow import Schema as ArrowSchema
|
@@ -416,6 +418,18 @@ def transform_python(self, _):
|
416 | 418 | return
|
417 | 419 |
|
418 | 420 |
|
| 421 | +class _DecimalCodec(TypeEncoder): |
| 422 | + """A custom type codec for Decimal objects.""" |
| 423 | + |
| 424 | + @property |
| 425 | + def python_type(self): |
| 426 | + return Decimal |
| 427 | + |
| 428 | + def transform_python(self, value): |
| 429 | + """Transform an Decimal object into a BSON Decimal128 object""" |
| 430 | + return Decimal128(value) |
| 431 | + |
| 432 | + |
419 | 433 | def write(collection, tabular, *, exclude_none: bool = False):
|
420 | 434 | """Write data from `tabular` into the given MongoDB `collection`.
|
421 | 435 |
|
@@ -469,9 +483,9 @@ def write(collection, tabular, *, exclude_none: bool = False):
|
469 | 483 |
|
470 | 484 | tabular_gen = _tabular_generator(tabular, exclude_none=exclude_none)
|
471 | 485 |
|
472 |
| - # Handle Pandas NA objects. |
| 486 | + # Add handling for special case types. |
473 | 487 | codec_options = collection.codec_options
|
474 |
| - type_registry = TypeRegistry([_PandasNACodec()]) |
| 488 | + type_registry = TypeRegistry([_PandasNACodec(), _DecimalCodec()]) |
475 | 489 | codec_options = codec_options.with_options(type_registry=type_registry)
|
476 | 490 |
|
477 | 491 | while cur_offset < tab_size:
|
|
0 commit comments