field.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package orm
  2. import (
  3. "reflect"
  4. "strings"
  5. )
  6. // fieldType is the type we expect
  7. type fieldType uint8
  8. // Relation or Column defines type of mapping
  9. const (
  10. Relation fieldType = iota << 1 // fieldType = (fieldType)(reflect.Struct)
  11. Column
  12. )
  13. // field holds necessary data on specific field
  14. type field struct {
  15. sf reflect.StructField
  16. t reflect.Type
  17. v reflect.Value
  18. ft fieldType
  19. }
  20. func (f *field) Make() reflect.Value {
  21. o := reflect.New(f.MakeType()).Elem()
  22. switch f.MakeType().Kind() {
  23. case reflect.Map:
  24. o.Set(reflect.MakeMap(o.Type()))
  25. }
  26. return o
  27. }
  28. func (f *field) MakeType() reflect.Type {
  29. return f.sf.Type
  30. }
  31. // getFieldName returns the field name within the struct,
  32. // e.g struct { fieldName fieldType }{}
  33. func (f *field) getFieldName() string {
  34. return f.sf.Name
  35. }
  36. // getFieldType returns the field type within the struct,
  37. // e.g struct { fieldName fieldType }{}
  38. func (f *field) getFieldType() string {
  39. return f.t.Name()
  40. }
  41. // getType returns the type; Relation or Column
  42. func (f *field) getType() fieldType {
  43. return f.ft //(fieldType)(f.t.Kind())
  44. }
  45. // getKind returns the actual reflect.Kind
  46. func (f *field) getKind() reflect.Kind {
  47. return f.t.Kind()
  48. }
  49. // getTag returns tags on this field, can be
  50. // db:"siglevalue" (bool type?) or db:"key:value"
  51. func (f *field) getTag(key string) (string, bool) {
  52. if tag := f.sf.Tag.Get(Prefix); len(tag) != 0 {
  53. tags := strings.Split(tag, ";")
  54. for _, tag := range tags {
  55. kv := strings.Split(tag, ":")
  56. kv[0] = strings.Trim(kv[0], " ")
  57. if len(kv) == 1 && kv[0] == key {
  58. return kv[0], true
  59. }
  60. if len(kv) == 2 && kv[0] == key {
  61. kv[1] = strings.Trim(kv[1], " ")
  62. return kv[1], true
  63. }
  64. }
  65. }
  66. return "", false
  67. }
  68. // hasTags checks if it has all keys
  69. func (f *field) hasTags(keys ...string) bool {
  70. match := 0
  71. for _, key := range keys {
  72. if f.hasTag(key) {
  73. match += 1
  74. }
  75. }
  76. return len(keys) == match
  77. }
  78. // hasTags checks if it has key
  79. func (f *field) hasTag(key string) bool {
  80. if _, ok := f.getTag(key); ok {
  81. return true
  82. }
  83. return false
  84. }