diff --git a/transformers/json_schema_fields.go b/transformers/json_schema_fields.go new file mode 100644 index 0000000000..223a6bddb0 --- /dev/null +++ b/transformers/json_schema_fields.go @@ -0,0 +1,131 @@ +package transformers + +import ( + "reflect" + "strings" +) + +type jsonSchemaField struct { + field reflect.StructField + depth int + tagged bool + addressable bool +} + +type embeddedJSONStruct struct { + structType reflect.Type + count int + addressable bool +} + +type jsonSchemaFieldsKey struct { + structType reflect.Type + addressable bool +} + +func (t *structTransformer) jsonSchemaFields(structType reflect.Type, addressable bool) map[string]jsonSchemaField { + key := jsonSchemaFieldsKey{structType: structType, addressable: addressable} + if fields, ok := t.jsonSchemaFieldsCache[key]; ok { + return fields + } + if t.jsonSchemaFieldsCache == nil { + t.jsonSchemaFieldsCache = make(map[jsonSchemaFieldsKey]map[string]jsonSchemaField) + } + fields := t.computeJSONSchemaFields(structType, addressable) + t.jsonSchemaFieldsCache[key] = fields + return fields +} + +func (t *structTransformer) computeJSONSchemaFields(structType reflect.Type, addressable bool) map[string]jsonSchemaField { + candidates := make(map[string][]jsonSchemaField) + visited := make(map[reflect.Type]bool) + level := []*embeddedJSONStruct{{structType: structType, count: 1, addressable: addressable}} + for depth := 0; len(level) > 0; depth++ { + for _, embedded := range level { + visited[embedded.structType] = true + } + var next []*embeddedJSONStruct + nextByType := make(map[reflect.Type]*embeddedJSONStruct) + for _, embedded := range level { + for i := 0; i < embedded.structType.NumField(); i++ { + structField := embedded.structType.Field(i) + if isTypeIgnored(structField.Type) { + continue + } + fieldType := structField.Type + if fieldType.Name() == "" && fieldType.Kind() == reflect.Pointer { + fieldType = fieldType.Elem() + } + tagName, _, _ := strings.Cut(structField.Tag.Get("json"), ",") + isEmbeddedStruct := structField.Anonymous && fieldType.Kind() == reflect.Struct + if isEmbeddedStruct && tagName == "" { + if visited[fieldType] { + continue + } + reached, ok := nextByType[fieldType] + if !ok { + reached = &embeddedJSONStruct{ + structType: fieldType, + addressable: embedded.addressable || structField.Type.Kind() == reflect.Pointer, + } + nextByType[fieldType] = reached + next = append(next, reached) + } + reached.count++ + continue + } + if !structField.IsExported() && !isEmbeddedStruct { + continue + } + name, err := t.jsonSchemaNameTransformer(structField) + if err != nil || name == "" { + continue + } + candidate := jsonSchemaField{ + field: structField, + depth: depth, + tagged: tagName != "", + addressable: embedded.addressable, + } + candidates[name] = append(candidates[name], candidate) + if embedded.count > 1 { + candidates[name] = append(candidates[name], candidate) + } + } + } + level = next + } + + fields := make(map[string]jsonSchemaField, len(candidates)) + for name, sameName := range candidates { + if winner, ok := dominantJSONSchemaField(sameName); ok { + fields[name] = winner + } + } + return fields +} + +func dominantJSONSchemaField(sameName []jsonSchemaField) (jsonSchemaField, bool) { + shallowest := sameName[0].depth + for _, f := range sameName { + shallowest = min(shallowest, f.depth) + } + var atShallowest, tagged []jsonSchemaField + for _, f := range sameName { + if f.depth != shallowest { + continue + } + atShallowest = append(atShallowest, f) + if f.tagged { + tagged = append(tagged, f) + } + } + switch { + case len(atShallowest) == 1: + return atShallowest[0], true + case len(tagged) == 1: + return tagged[0], true + default: + return jsonSchemaField{}, false + } +} diff --git a/transformers/json_schema_fields_test.go b/transformers/json_schema_fields_test.go new file mode 100644 index 0000000000..6396fd0f18 --- /dev/null +++ b/transformers/json_schema_fields_test.go @@ -0,0 +1,690 @@ +package transformers + +import ( + "context" + "encoding/json" + "fmt" + "reflect" + "slices" + "testing" + "time" + + "github.com/cloudquery/plugin-sdk/v4/faker" + "github.com/cloudquery/plugin-sdk/v4/scalar" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/stretchr/testify/require" +) + +type SchemaTestSecret struct { + SecretName string `json:"secretName"` +} + +type SchemaTestObjectReference struct { + Name string `json:"name"` +} + +type SchemaTestConfigMapVolumeSource struct { + SchemaTestObjectReference `json:",inline"` //nolint:revive + Optional *bool `json:"optional,omitempty"` +} + +type SchemaTestVolumeSource struct { + Secret *SchemaTestSecret `json:"secret,omitempty"` + ConfigMap *SchemaTestConfigMapVolumeSource `json:"configMap,omitempty"` +} + +type SchemaTestVolume struct { + Name string `json:"name"` + SchemaTestVolumeSource `json:",inline"` //nolint:revive +} + +type SchemaTestQuantity struct { + milli int64 + Format string +} + +func (q SchemaTestQuantity) MarshalJSON() ([]byte, error) { + return json.Marshal(fmt.Sprintf("%dm", q.milli)) +} + +type SchemaTestHTTPGetAction struct { + Path string `json:"path,omitempty"` + Port SchemaTestIntOrString `json:"port"` +} + +type SchemaTestProbeHandler struct { + HTTPGet *SchemaTestHTTPGetAction `json:"httpGet,omitempty"` +} + +type SchemaTestProbe struct { + SchemaTestProbeHandler `json:",inline"` //nolint:revive + PeriodSeconds int32 `json:"periodSeconds,omitempty"` +} + +type SchemaTestResourceRequirements struct { + Limits map[string]SchemaTestQuantity `json:"limits,omitempty"` +} + +type SchemaTestContainer struct { + Name string `json:"name"` + LivenessProbe *SchemaTestProbe `json:"livenessProbe,omitempty"` + Resources SchemaTestResourceRequirements `json:"resources,omitempty"` +} + +type SchemaTestPodSpec struct { + Volumes []SchemaTestVolume `json:"volumes,omitempty"` + Containers []SchemaTestContainer `json:"containers"` +} + +type SchemaTestNamed struct { + Name string `json:"name"` + ID string `json:"id"` +} + +type SchemaTestUntaggedName struct { + Name string +} + +type SchemaTestTaggedName struct { + Name int `json:"Name"` +} + +type SchemaTestLeft struct { + SchemaTestObjectReference +} + +type SchemaTestRight struct { + SchemaTestObjectReference +} + +type SchemaTestIntOrString struct { + Type int + IntVal int32 + StrVal string +} + +func (v SchemaTestIntOrString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.IntVal) +} + +type SchemaTestPointerMarshaler struct { + Value string +} + +func (v *SchemaTestPointerMarshaler) MarshalJSON() ([]byte, error) { + return json.Marshal(v.Value) +} + +type SchemaTestText struct { + Raw string +} + +func (v SchemaTestText) MarshalText() ([]byte, error) { + return []byte(v.Raw), nil +} + +type SchemaTestMarshalerList []SchemaTestSecret + +func (v SchemaTestMarshalerList) MarshalJSON() ([]byte, error) { + return json.Marshal(len(v)) +} + +type SchemaTestDeep struct { + Value SchemaTestPointerMarshaler `json:"value"` +} + +type SchemaTestMid struct { + SchemaTestDeep +} + +type SchemaTestValuePath struct { + SchemaTestMid +} + +type SchemaTestPointerPath struct { + *SchemaTestMid +} + +type SchemaTestMapKey struct { + ID string +} + +func (k SchemaTestMapKey) MarshalText() ([]byte, error) { + return []byte(k.ID), nil +} + +func (k SchemaTestMapKey) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]string{"id": k.ID}) +} + +type SchemaTestNumericKey int + +func (k SchemaTestNumericKey) MarshalText() ([]byte, error) { + return []byte(fmt.Sprintf("key-%d", int(k))), nil +} + +type schemaTestUnexportedEmbed struct { + Exported string `json:"exported"` +} + +type SchemaTestGeneratedClient struct { + ID string `json:"id"` + Name *string `json:"name,omitempty"` + ForceSendFields []string `json:"-"` + AdditionalProperties map[string]any +} + +func (v SchemaTestGeneratedClient) MarshalJSON() ([]byte, error) { + object := map[string]any{"id": v.ID} + if v.Name != nil { + object["name"] = *v.Name + } + for key, value := range v.AdditionalProperties { + object[key] = value + } + return json.Marshal(object) +} + +type SchemaTestServerResponse struct { + StatusCode int `json:"statusCode"` +} + +type SchemaTestGeneratedResponse struct { + SchemaTestServerResponse `json:"-"` + ID string `json:"id"` + explicitFields *SchemaTestSecret //nolint:unused +} + +func (v SchemaTestGeneratedResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]string{"id": v.ID}) +} + +type SchemaTestPaymentSource struct { + ID string `json:"id"` + Object string `json:"object"` + Card *SchemaTestSecret `json:"-"` +} + +func (v SchemaTestPaymentSource) MarshalJSON() ([]byte, error) { + if v.Card != nil { + return json.Marshal(v.Card) + } + return json.Marshal(v.ID) +} + +func TestJSONTypeSchemaMatchesEncoder(t *testing.T) { + tests := []struct { + name string + testStruct any + want string + }{ + { + name: "flattens inline embedded structs at every level", + testStruct: struct { + Volume SchemaTestVolume `json:"volume"` + }{}, + want: `{"configMap":{"name":"utf8","optional":"bool"},"name":"utf8","secret":{"secretName":"utf8"}}`, + }, + { + name: "flattens an embedded struct without a json tag", + testStruct: struct { + Ref struct { + SchemaTestObjectReference + } `json:"ref"` + }{}, + want: `{"name":"utf8"}`, + }, + { + name: "flattens an embedded struct pointer", + testStruct: struct { + Ref struct { + *SchemaTestObjectReference + } `json:"ref"` + }{}, + want: `{"name":"utf8"}`, + }, + { + name: "flattens the exported fields of an unexported embedded struct", + testStruct: struct { + Item struct { + schemaTestUnexportedEmbed + } `json:"item"` + }{}, + want: `{"exported":"utf8"}`, + }, + { + name: "keeps an embedded struct with a json name as a key", + testStruct: struct { + Ref struct { + SchemaTestObjectReference `json:"reference"` + } `json:"ref"` + }{}, + want: `{"reference":{"name":"utf8"}}`, + }, + { + name: "prefers the shallower field when names collide", + testStruct: struct { + Item struct { + Name string `json:"name"` + SchemaTestObjectReference + } `json:"item"` + }{}, + want: `{"name":"utf8"}`, + }, + { + name: "drops tagged fields that collide at the same depth", + testStruct: struct { + Item struct { + SchemaTestNamed + SchemaTestObjectReference //nolint:govet + } `json:"item"` + }{}, + want: `{"id":"utf8"}`, + }, + { + name: "prefers the tagged field when names collide at the same depth", + testStruct: struct { + Item struct { + SchemaTestUntaggedName + SchemaTestTaggedName + } `json:"item"` + }{}, + want: `{"Name":"int64"}`, + }, + { + name: "drops fields of the same embedded type reached twice at the same depth", + testStruct: struct { + Item struct { + SchemaTestLeft + SchemaTestRight //nolint:govet + ID string `json:"id"` + } `json:"item"` + }{}, + want: `{"id":"utf8"}`, + }, + { + name: "uses json for a type with MarshalJSON", + testStruct: struct { + Item struct { + Port SchemaTestIntOrString `json:"port"` + } `json:"item"` + }{}, + want: `{"port":"json"}`, + }, + { + name: "keeps the tagged fields of a type with MarshalJSON", + testStruct: struct { + Item struct { + Client SchemaTestGeneratedClient `json:"client"` + } `json:"item"` + }{}, + want: `{"client":{"id":"utf8","name":"utf8"}}`, + }, + { + name: "keeps the tagged fields of a type with MarshalJSON and hidden metadata", + testStruct: struct { + Item struct { + Response SchemaTestGeneratedResponse `json:"response"` + } `json:"item"` + }{}, + want: `{"response":{"id":"utf8"}}`, + }, + { + name: "uses json for a type with MarshalJSON that hides a struct variant", + testStruct: struct { + Item struct { + Source SchemaTestPaymentSource `json:"source"` + } `json:"item"` + }{}, + want: `{"source":"json"}`, + }, + { + name: "uses json for a type with a pointer MarshalJSON", + testStruct: struct { + Item struct { + Value *SchemaTestPointerMarshaler `json:"value"` + } `json:"item"` + }{}, + want: `{"value":"json"}`, + }, + { + name: "uses pointer MarshalJSON only where the encoder can take the address", + testStruct: struct { + Item struct { + Value SchemaTestPointerMarshaler `json:"value"` + List []SchemaTestPointerMarshaler `json:"list"` + Map map[string]SchemaTestPointerMarshaler `json:"map"` + } `json:"item"` + }{}, + want: `{"list":["json"],"map":{"utf8":{"Value":"utf8"}},"value":{"Value":"utf8"}}`, + }, + { + name: "uses pointer MarshalJSON for a value field inside a pointer", + testStruct: struct { + Item *struct { + Value SchemaTestPointerMarshaler `json:"value"` + } `json:"item"` + }{}, + want: `{"value":"json"}`, + }, + { + name: "takes addressability from the first path to a shared embedded type when it is a value", + testStruct: struct { + Item struct { + SchemaTestValuePath + SchemaTestPointerPath + } `json:"item"` + }{}, + want: `{"value":{"Value":"utf8"}}`, + }, + { + name: "takes addressability from the first path to a shared embedded type when it is a pointer", + testStruct: struct { + Item struct { + SchemaTestPointerPath + SchemaTestValuePath + } `json:"item"` + }{}, + want: `{"value":"json"}`, + }, + { + name: "uses utf8 for map keys that the encoder writes as text", + testStruct: struct { + Item struct { + ByStruct map[SchemaTestMapKey]string `json:"by_struct"` + ByNumber map[SchemaTestNumericKey]string `json:"by_number"` + ByPointer map[*SchemaTestMapKey]string `json:"by_pointer"` + } `json:"item"` + }{}, + want: `{"by_number":{"utf8":"utf8"},"by_pointer":{"utf8":"utf8"},"by_struct":{"utf8":"utf8"}}`, + }, + { + name: "keeps the int64 key type for a plain integer map key", + testStruct: struct { + Item struct { + ByInt map[int]string `json:"by_int"` + } `json:"item"` + }{}, + want: `{"by_int":{"int64":"utf8"}}`, + }, + { + name: "ignores pointer MarshalJSON for a value column", + testStruct: struct { + Value SchemaTestPointerMarshaler `json:"value"` + }{}, + want: `{"Value":"utf8"}`, + }, + { + name: "uses json for a column type with MarshalJSON", + testStruct: struct { + Port SchemaTestIntOrString `json:"port"` + }{}, + want: `"json"`, + }, + { + name: "uses json for a slice type with MarshalJSON", + testStruct: struct { + Item struct { + Secrets SchemaTestMarshalerList `json:"secrets"` + } `json:"item"` + }{}, + want: `{"secrets":"json"}`, + }, + { + name: "uses utf8 for a type with MarshalText", + testStruct: struct { + Item struct { + Text SchemaTestText `json:"text"` + } `json:"item"` + }{}, + want: `{"text":"utf8"}`, + }, + { + name: "keeps the timestamp type for time.Time", + testStruct: struct { + Item struct { + CreatedAt time.Time `json:"created_at"` + } `json:"item"` + }{}, + want: `{"created_at":"timestamp[us, tz=UTC]"}`, + }, + { + name: "skips a field tagged with a dash", + testStruct: struct { + Item struct { + Name string `json:"name"` + Secret string `json:"-"` + } `json:"item"` + }{}, + want: `{"name":"utf8"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + table := schema.Table{Name: "test"} + require.NoError(t, TransformWithStruct(tt.testStruct)(&table)) + require.Len(t, table.Columns, 1) + require.Equal(t, tt.want, table.Columns[0].TypeSchema) + }) + } +} + +func TestJSONTypeSchemaKeysMatchMarshalledValue(t *testing.T) { + tests := []struct { + name string + column func() any + }{ + { + name: "kubernetes-shaped volume", + column: func() any { return &struct{ Volume SchemaTestVolume }{} }, + }, + { + name: "kubernetes-shaped pod spec", + column: func() any { return &struct{ Spec SchemaTestPodSpec }{} }, + }, + { + name: "colliding embedded structs", + column: func() any { + return &struct { + Item struct { + SchemaTestNamed + SchemaTestObjectReference //nolint:govet + SchemaTestUntaggedName + SchemaTestTaggedName + SchemaTestLeft + SchemaTestRight //nolint:govet + } + }{} + }, + }, + { + name: "types with their own marshallers", + column: func() any { + return &struct { + Item struct { + Port SchemaTestIntOrString + Value *SchemaTestPointerMarshaler + Text SchemaTestText + Secrets SchemaTestMarshalerList + } + }{} + }, + }, + { + name: "types with MarshalJSON and json tags", + column: func() any { + return &struct { + Item struct { + Client SchemaTestGeneratedClient + Response SchemaTestGeneratedResponse + } + }{} + }, + }, + { + name: "diamond of embedded structs", + column: func() any { return schemaTestDiamondColumn(8) }, + }, + { + name: "shared embedded type reached by a value path first", + column: func() any { + return &struct { + Item struct { + SchemaTestValuePath + SchemaTestPointerPath + } + }{} + }, + }, + { + name: "shared embedded type reached by a pointer path first", + column: func() any { + return &struct { + Item struct { + SchemaTestPointerPath + SchemaTestValuePath + } + }{} + }, + }, + { + name: "map keys with their own marshallers", + column: func() any { + return &struct { + Item struct { + ByStruct map[SchemaTestMapKey]SchemaTestSecret + ByNumber map[SchemaTestNumericKey]SchemaTestSecret + } + }{} + }, + }, + { + name: "pointer-only marshallers in a value column", + column: func() any { + return &struct { + Item struct { + Value SchemaTestPointerMarshaler + List []SchemaTestPointerMarshaler + Map map[string]SchemaTestPointerMarshaler + } + }{} + }, + }, + { + name: "pointer-only marshallers in a pointer column", + column: func() any { + return &struct { + Item *struct { + Value SchemaTestPointerMarshaler + List []SchemaTestPointerMarshaler + Map map[string]SchemaTestPointerMarshaler + } + }{} + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + column := tt.column() + require.NoError(t, faker.FakeObject(column, faker.WithMaxDepth(30))) + + table := schema.Table{Name: "test"} + require.NoError(t, TransformWithStruct(column)(&table)) + require.Len(t, table.Columns, 1) + + var typeSchema any + require.NoError(t, json.Unmarshal([]byte(table.Columns[0].TypeSchema), &typeSchema)) + + resource := schema.NewResourceData(&table, nil, column) + require.NoError(t, table.Columns[0].Resolver(context.Background(), nil, resource, table.Columns[0])) + stored, ok := resource.Get(table.Columns[0].Name).(*scalar.JSON) + require.True(t, ok) + var value any + require.NoError(t, json.Unmarshal(stored.Value, &value)) + + var mismatches []string + compareJSONKeys(typeSchema, value, "$", &mismatches) + slices.Sort(mismatches) + require.Empty(t, mismatches, "type schema: %s\nvalue: %s", table.Columns[0].TypeSchema, stored.Value) + }) + } +} + +func schemaTestDiamondColumn(levels int) any { + level := reflect.TypeFor[SchemaTestObjectReference]() + for range levels { + left := reflect.StructOf([]reflect.StructField{ + {Name: "Shared", Type: level, Anonymous: true}, + }) + right := reflect.StructOf([]reflect.StructField{ + {Name: "Shared", Type: level, Anonymous: true}, + {Name: "Ignored", Type: reflect.TypeFor[bool](), Tag: `json:"-"`}, + }) + level = reflect.StructOf([]reflect.StructField{ + {Name: "Left", Type: left, Anonymous: true}, + {Name: "Right", Type: right, Anonymous: true}, + {Name: "ID", Type: reflect.TypeFor[string](), Tag: `json:"id"`}, + }) + } + return reflect.New(reflect.StructOf([]reflect.StructField{ + {Name: "Item", Type: level, Tag: `json:"item"`}, + })).Interface() +} + +func TestJSONTypeSchemaDropsFieldsOfADiamondOfEmbeddedStructs(t *testing.T) { + table := schema.Table{Name: "test"} + require.NoError(t, TransformWithStruct(schemaTestDiamondColumn(8))(&table)) + require.Equal(t, `{"id":"utf8"}`, table.Column("item").TypeSchema) +} + +func compareJSONKeys(typeSchema, value any, path string, mismatches *[]string) { + if value == nil { + return + } + switch s := typeSchema.(type) { + case string: + if s == "json" || s == "any" { + return + } + switch value.(type) { + case map[string]any, []any: + *mismatches = append(*mismatches, fmt.Sprintf("%s: schema has %s, value is %T", path, s, value)) + } + case []any: + values, ok := value.([]any) + if !ok { + *mismatches = append(*mismatches, fmt.Sprintf("%s: schema has a list, value is %T", path, value)) + return + } + for _, v := range values { + compareJSONKeys(s[0], v, path+"[]", mismatches) + } + case map[string]any: + object, ok := value.(map[string]any) + if !ok { + *mismatches = append(*mismatches, fmt.Sprintf("%s: schema has an object, value is %T", path, value)) + return + } + if mapValueSchema, isMap := s["utf8"]; isMap && len(s) == 1 { + for _, v := range object { + compareJSONKeys(mapValueSchema, v, path+".*", mismatches) + } + return + } + for key, keySchema := range s { + v, ok := object[key] + if !ok { + *mismatches = append(*mismatches, fmt.Sprintf("%s.%s: in schema, not in value", path, key)) + continue + } + compareJSONKeys(keySchema, v, path+"."+key, mismatches) + } + for key := range object { + if _, ok := s[key]; !ok { + *mismatches = append(*mismatches, fmt.Sprintf("%s.%s: in value, not in schema", path, key)) + } + } + } +} diff --git a/transformers/struct.go b/transformers/struct.go index 9cfc2cef76..f6c7f5fe9a 100644 --- a/transformers/struct.go +++ b/transformers/struct.go @@ -2,6 +2,7 @@ package transformers import ( "bytes" + "encoding" "encoding/json" "fmt" "reflect" @@ -35,6 +36,7 @@ type structTransformer struct { jsonSchemaNameTransformer NameTransformer maxJSONTypeSchemaDepth int + jsonSchemaFieldsCache map[jsonSchemaFieldsKey]map[string]jsonSchemaField } func isFieldStruct(reflectType reflect.Type) bool { @@ -169,7 +171,7 @@ func (t *structTransformer) addColumnFromField(field reflect.StructField, parent // Enrich JSON column with detailed schema if columnType == types.ExtensionTypes.JSON { - column.TypeSchema = structSchemaToJSON(t.fieldToJSONSchema(field, 0)) + column.TypeSchema = structSchemaToJSON(t.fieldToJSONSchema(field, 0, false)) } for _, pk := range t.pkFields { @@ -291,21 +293,97 @@ func normalizePointer(field reflect.StructField) reflect.Value { return reflect.New(field.Type) } -func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth int) any { +var ( + jsonMarshalerType = reflect.TypeFor[json.Marshaler]() + textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]() +) + +func implementsInterface(t reflect.Type, iface reflect.Type, addressable bool) bool { + return t.Implements(iface) || (addressable && reflect.PointerTo(t).Implements(iface)) +} + +func jsonTagName(field reflect.StructField) string { + name, _, _ := strings.Cut(field.Tag.Get("json"), ",") + return name +} + +func hasJSONTaggedField(t reflect.Type) bool { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if name := jsonTagName(field); field.IsExported() && name != "" && name != "-" { + return true + } + } + return false +} + +func hasHiddenStructField(t reflect.Type) bool { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + fieldType := field.Type + if fieldType.Kind() == reflect.Pointer { + fieldType = fieldType.Elem() + } + if field.IsExported() && !field.Anonymous && jsonTagName(field) == "-" && fieldType.Kind() == reflect.Struct { + return true + } + } + return false +} + +func ownMarshalerSchema(t reflect.Type, addressable bool) (string, bool) { + switch t.Kind() { + case reflect.Struct, reflect.Map, reflect.Slice: + default: + return "", false + } + switch { + case implementsInterface(t, jsonMarshalerType, addressable): + if t.Kind() == reflect.Struct && hasJSONTaggedField(t) && !hasHiddenStructField(t) { + return "", false + } + return types.ExtensionTypes.JSON.String(), true + case implementsInterface(t, textMarshalerType, addressable): + return arrow.BinaryTypes.String.String(), true + default: + return "", false + } +} + +func (t *structTransformer) mapKeyJSONSchema(keyType reflect.Type, depth int) string { + switch keyType.Kind() { + case reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + if keyType.Kind() != reflect.String && keyType.Implements(textMarshalerType) { + return arrow.BinaryTypes.String.String() + } + keySchema, _ := t.fieldToJSONSchema(reflect.StructField{Type: keyType}, depth+1, false).(string) + return keySchema + default: + if keyType.Implements(textMarshalerType) { + return arrow.BinaryTypes.String.String() + } + return "" + } +} + +func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth int, addressable bool) any { normalizedField := normalizePointer(field) + addressable = addressable || field.Type.Kind() == reflect.Pointer + if marshalerSchema, ok := ownMarshalerSchema(normalizedField.Elem().Type(), addressable); ok { + return marshalerSchema + } switch normalizedField.Elem().Kind() { case reflect.Struct: fieldsMap := make(map[string]any) - fieldType := normalizedField.Elem().Type() - for i := 0; i < fieldType.NumField(); i++ { - structField := fieldType.Field(i) - if !structField.IsExported() || isTypeIgnored(structField.Type) { - continue - } - name, err := t.jsonSchemaNameTransformer(structField) - if err != nil { + structType := normalizedField.Elem().Type() + taggedOnly := implementsInterface(structType, jsonMarshalerType, addressable) + for name, schemaField := range t.jsonSchemaFields(structType, addressable) { + if taggedOnly && !schemaField.tagged { continue } + structField := schemaField.field columnType, err := t.getColumnType(structField) if err != nil { continue @@ -316,7 +394,7 @@ func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth i } // Avoid infinite recursion if columnType == types.ExtensionTypes.JSON && depth < t.maxJSONTypeSchemaDepth { - fieldsMap[name] = t.fieldToJSONSchema(structField, depth+1) + fieldsMap[name] = t.fieldToJSONSchema(structField, depth+1, schemaField.addressable) continue } asList, ok := columnType.(*arrow.ListType) @@ -328,15 +406,13 @@ func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth i } return fieldsMap case reflect.Map: - keySchema, ok := t.fieldToJSONSchema(reflect.StructField{ - Type: normalizedField.Elem().Type().Key(), - }, depth+1).(string) - if keySchema == "" || !ok { + keySchema := t.mapKeyJSONSchema(normalizedField.Elem().Type().Key(), depth) + if keySchema == "" { return "" } valueSchema := t.fieldToJSONSchema(reflect.StructField{ Type: normalizedField.Elem().Type().Elem(), - }, depth+1) + }, depth+1, false) if valueSchema == "" { return "" } @@ -346,7 +422,7 @@ func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth i case reflect.Slice: valueSchema := t.fieldToJSONSchema(reflect.StructField{ Type: normalizedField.Elem().Type().Elem(), - }, depth+1) + }, depth+1, true) if valueSchema == "" { return "" }