volatiletech / randomize

Support library for sqlboiler
BSD 3-Clause "New" or "Revised" License
1 stars 2 forks source link

Nullable types are not supported #1

Open netayg opened 1 year ago

netayg commented 1 year ago

When trying to generate tests for sqlboiler (a module that uses this module) I have encountered this error: Unable to randomize ObjName object: unsupported type: models.NullEnumType

After debugging the issue, the problem seems to be that Null types generated by sqlboiler are not supported by this repo. For example, enum.NullEnumType will not get randomized.

In randomize.go#L143 (link) we see:

    if kind == reflect.Struct {
        if shouldBeNull {
            value = getStructNullValue(s, fieldType, typ)
        } else {
            value = getStructRandValue(s, fieldType, typ)
        }
    } else {
...

Because the type is actually a struct (enum.NullEnumType) we get True and continue. Based on shouldBeNull the relevant function is called. Both functions support only type Date and doesn't "try" to resolve nullable structs (as it probably should, null types are supported by sqlboiler).

func getStructRandValue(s *Seed, fieldType string, typ reflect.Type) interface{} {
    if typ == typeTime {
        return Date(s.NextInt)
    }

    return nil
}

Adding a check for structs of type nullable will solve this issue.

Optional solution: In the getStructRandValue/getStructNullValue add a simple check that verifies if the struct is of type nullable (using isValid or any other identifier). If it is of this type, try to resolve the type of the value member of the struct. In our case, it will be EnumType. Then call the regular function getVariableRandValue/getVariableZeroValue for this member and get a valid random value.

That way, most of the newly created Nullable-EnumTypes will be supported.

florindragos commented 1 year ago

Having the same issue. Looks like there was a problem also for non-nullable types: https://github.com/volatiletech/sqlboiler/issues/487 but nullable still fails with unsupported type when running the generated tests. @aarondl any idea if this could be addressed ?

netayg commented 1 year ago

Hey @florindragos, I have raised the issue also on the Discord channel - I was surprised to hear that unfortunately the support for the tests is soon to end. So even if a solution is found, later down the line more bugs will appear.

My current solution is to filter out any known tests that fail because of this, and check the output of the other tests. Hope this helps. 😄

florindragos commented 1 year ago

@netayg thanks for the update! I guess there is no alternative strategy to generate tests for the models... not really keen on writing everything the old fashioned way :)

netayg commented 1 year ago

You can open a PR to fix the problem, I thought of a couple of ways to fix it, but didn't have the time for it. Good luck :)