schema/field: allow using JSON fields with type 'any' (#3380)

Fixed https://github.com/ent/ent/issues/3104
This commit is contained in:
Ariel Mashraki
2023-03-10 10:20:51 +02:00
committed by GitHub
parent 4a60f52cf4
commit 81eb431081
11 changed files with 190 additions and 2 deletions

View File

@@ -108,6 +108,26 @@ func Floats(name string) *jsonBuilder {
return JSON(name, []float64{})
}
// Any returns a new JSON Field with type any. Although this field type can be
// useful for fields with dynamic data layout, it is strongly recommended to use
// JSON with json.RawMessage instead and implement custom marshaling.
func Any(name string) *jsonBuilder {
const t = "any"
return &jsonBuilder{&Descriptor{
Name: name,
Info: &TypeInfo{
Type: TypeJSON,
Ident: t,
Nillable: true,
RType: &RType{
Name: t,
Ident: t,
Kind: reflect.Interface,
},
},
}}
}
// Enum returns a new Field with type enum. An example for defining enum is as follows:
//
// field.Enum("state").

View File

@@ -512,6 +512,13 @@ func TestJSON(t *testing.T) {
Descriptor()
assert.Error(t, fd.Err)
fd = field.Any("unknown").
Descriptor()
assert.NoError(t, fd.Err)
assert.Equal(t, field.TypeJSON, fd.Info.Type)
assert.Equal(t, "unknown", fd.Name)
assert.Equal(t, "any", fd.Info.String())
fd = field.JSON("values", &url.Values{}).Descriptor()
assert.Equal(t, "net/url", fd.Info.PkgPath)
assert.Equal(t, "url", fd.Info.PkgName)