Skip to content

Commit 9ed3c63

Browse files
authored
MONGOID-5360 Warn when defining field types of BSON::Int64/Decimal128 and other unsupported types (#5291)
* MONGOID-5360 warn on BSON::* types and add docs * MONGOID-5360 only warn on Int32/64 and Decimal128 * MONGOID-5360 reword the warning * MONGOID-5360 reword warning * Update lib/mongoid/fields.rb * Update lib/mongoid/fields.rb * MONGOID-5360 update message and freeze array
1 parent f563bc0 commit 9ed3c63

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

docs/reference/fields.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,13 @@ Mongoid also recognizes the string ``"Boolean"`` as an alias for the
8989

9090
To define custom field types, refer to :ref:`Custom Field Types <custom-field-types>` below.
9191

92+
.. note::
93+
94+
Using the ``BSON::Int64`` and ``BSON::Int32`` types as field types is unsupported.
95+
Saving these types to the database will work as expected, however, querying them
96+
will return the native Ruby ``Integer`` type. Querying fields of type
97+
``BSON::Decimal128`` will return values of type ``BSON::Decimal128`` in
98+
BSON <=4 and values of type ``BigDecimal`` in BSON 5+.
9299

93100
.. _omitting-field-type-definition:
94101

lib/mongoid/fields.rb

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ module Fields
4242
# @api private
4343
IDS = [ :_id, '_id', ].freeze
4444

45+
# BSON classes that are not supported as field types
46+
#
47+
# @api private
48+
INVALID_BSON_CLASSES = [ BSON::Decimal128, BSON::Int32, BSON::Int64 ].freeze
49+
4550
module ClassMethods
4651
# Returns the list of id fields for this model class, as both strings
4752
# and symbols.
@@ -731,8 +736,18 @@ def field_for(name, options)
731736
opts = options.merge(klass: self)
732737
type_mapping = TYPE_MAPPINGS[options[:type]]
733738
opts[:type] = type_mapping || unmapped_type(options)
734-
unless opts[:type].is_a?(Class)
739+
if !opts[:type].is_a?(Class)
735740
raise Errors::InvalidFieldType.new(self, name, options[:type])
741+
else
742+
if INVALID_BSON_CLASSES.include?(opts[:type])
743+
warn_message = "Using #{opts[:type]} as the field type is not supported. "
744+
if opts[:type] == BSON::Decimal128
745+
warn_message += "In BSON <= 4, the BSON::Decimal128 type will work as expected for both storing and querying, but will return a BigDecimal on query in BSON 5+."
746+
else
747+
warn_message += "Saving values of this type to the database will work as expected, however, querying them will return a value of the native Ruby Integer type."
748+
end
749+
Mongoid.logger.warn(warn_message)
750+
end
736751
end
737752
return Fields::Localized.new(name, opts) if options[:localize]
738753
return Fields::ForeignKey.new(name, opts) if options[:identity]

0 commit comments

Comments
 (0)