struct_to_schema.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package schema
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
  4. "reflect"
  5. )
  6. func StructToSchema(instance any) *schema_pb.RecordType {
  7. myType := reflect.TypeOf(instance)
  8. if myType.Kind() != reflect.Struct {
  9. return nil
  10. }
  11. st := reflectTypeToSchemaType(myType)
  12. return st.GetRecordType()
  13. }
  14. func reflectTypeToSchemaType(t reflect.Type) *schema_pb.Type {
  15. switch t.Kind() {
  16. case reflect.Bool:
  17. return TypeBoolean
  18. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
  19. return TypeInt32
  20. case reflect.Int64:
  21. return TypeInt64
  22. case reflect.Float32:
  23. return TypeFloat
  24. case reflect.Float64:
  25. return TypeDouble
  26. case reflect.String:
  27. return TypeString
  28. case reflect.Slice:
  29. switch t.Elem().Kind() {
  30. case reflect.Uint8:
  31. return TypeBytes
  32. default:
  33. if st := reflectTypeToSchemaType(t.Elem()); st != nil {
  34. return &schema_pb.Type{
  35. Kind: &schema_pb.Type_ListType{
  36. ListType: &schema_pb.ListType{
  37. ElementType: st,
  38. },
  39. },
  40. }
  41. }
  42. }
  43. case reflect.Struct:
  44. recordType := &schema_pb.RecordType{}
  45. for i := 0; i < t.NumField(); i++ {
  46. field := t.Field(i)
  47. fieldType := field.Type
  48. fieldName := field.Name
  49. schemaField := reflectTypeToSchemaType(fieldType)
  50. if schemaField == nil {
  51. return nil
  52. }
  53. recordType.Fields = append(recordType.Fields, &schema_pb.Field{
  54. Name: fieldName,
  55. Type: schemaField,
  56. })
  57. }
  58. return &schema_pb.Type{
  59. Kind: &schema_pb.Type_RecordType{
  60. RecordType: recordType,
  61. },
  62. }
  63. }
  64. return nil
  65. }