Is there a way (or is it even a good idea) to convert a nil field value into a boolean false when loading data from a database? I tried using Ecto.Type to create a custom type to be used on the schema field that would handle the conversion and quickly discovered that the load function on the Type behavior is not called when a nil is returned from the database. Should converting a nil to false be handled when loading data or should it be handled after the data has been loaded into the schema by passing the struct to a function that will check for nil and reset the value accordingly?
Isn’t a nil already treated as false except for pure-boolean operations?
If there is a nullable Boolean field in the database then null has probably different semantics than false. If they were the same, then the field were defaulting to false. So no, it’s probably not safe to treat null the same as false in this case.
But if that’s the case then why wouldn’t they want it to remain nil in the schema so they can differentiate?
The application semantics only deal with true or false so the contextual meaning of nil is the same as false. I didn’t consider that Elixir might treat them the same but I just checked and they are not considered equal.
iex(1)> nil == false
No, not considered equal, but both are considered false.
if nil, do: :truthy, else: :falsy #=> :falsy
You could set the field to
default: false and it should treat empty fields as
But then you won’t know anymore if a user has actually answered the question with “no” or not provided an answer yet. (or whatever the difference between NULL and false might be in the fields context!)
Granted it’s some kind of question this might be true, but it could also be a feature toggle, where the semantic difference between “not yet filled” and “consciously disabled” is not relevant for the code using the value.
Yupp, and thats what I am telling right from the start, it depends on the semantics of NULL in the context. If it had no semantic meaning the DB designer would have given it a default value.
Thank you for your input, gentlemen. The app in this context is a service that consumes data inserted by a UI. In the UI there is a semantic difference between null and false. Nil meaning that an option has not been chosen versus false which indicates a negative option choice. However, the service consuming that data does not distinguish between nil and false and treats them the same way and really only cares if the option has been set to true. I think the best think would be to simply pass the schema struct to a function that would check the field value for nil and return false.
@LostKobrakai I tried setting
default: false in the schema but that had no effect when reading a null column value.