silverstripe-framework: Allow `null` values for `DBInt` (and possibly other fields that currently don't allow it)
nullifyEmpty is an option on DBString that lets you set whether an empty value is stored as "" or null.
Right now, on numeric fields such a DBInt, empty values are always stored as 0. This creates a problem if you want to apply a unique index for a sparsely populated int field. Unique indexes allow for more than one occurrence of null, but only one occurence of 0.
Furthermore, sometimes you will have a need for storing 0 as well as null.
To solve this, we should add two properties to DBInt and DBFloat:
- nullifyEmpty
- allowNull
The allowed values of such fields would be as follows:
- 0, 1, 2, … (allowNull = false)
- null, 1, 2, … (allowNull = true, nullifyEmpty = true)
- null, 0, 1, 2, … (allowNull = true, nullifyEmpty = false)
We’d need to consider the coersion rules. I would probably go for:
- If allowNull is true: then coerce falsey values other than an
0and"0"to null. Coerce0and"0"to (int)0 or (float)0 as appropriate. - If allowNull is false: then coerce falsey values to (int)0 or (float)0 as appropriate.
In the unit tests for this feature ensure that this coercion is tested.
The default should be allowNull = false, which should let us introduce this in a minor release.
About this issue
- Original URL
- State: open
- Created 8 years ago
- Reactions: 1
- Comments: 16 (14 by maintainers)
Commits related to this issue
- FIX: Correct type coercion of MySQL — committed to silverstripe/silverstripe-framework by deleted user 8 years ago
Note that there was argument on #3473 for allowing “0” as a real value in some cases. So you might end up wanting to allow both. Although I would probably allow for configuration to specify any of the 3 cases if we went down that road, for example:
My vote is to add it to
DBInt, but retain the existing default behaviour until 5.x. I don’t think we need a separate class for the behaviour