You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.5 KiB

8 months ago
8 months ago
  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. }