field.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package orm
  2. import (
  3. "reflect"
  4. "strings"
  5. )
  6. // fieldType is the type we expect
  7. type fieldType reflect.Kind
  8. // Relation or Column defines type of mapping
  9. const (
  10. Relation 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. }
  19. // getFieldName returns the field name within the struct,
  20. // e.g struct { fieldName fieldType }{}
  21. func (f *field) getFieldName() string {
  22. return f.sf.Name
  23. }
  24. // getFieldType returns the field type within the struct,
  25. // e.g struct { fieldName fieldType }{}
  26. func (f *field) getFieldType() string {
  27. return f.t.Name()
  28. }
  29. // getType returns the type; Relation or Column
  30. func (f *field) getType() fieldType {
  31. return (fieldType)(f.t.Kind())
  32. }
  33. // getKind returns the actual reflect.Kind
  34. func (f *field) getKind() reflect.Kind {
  35. return f.t.Kind()
  36. }
  37. // getTag returns tags on this field, can be
  38. // db:"siglevalue" (bool type?) or db:"key:value"
  39. func (f *field) getTag(key string) (string, bool) {
  40. if tag := f.sf.Tag.Get(Prefix); len(tag) != 0 {
  41. tags := strings.Split(tag, ";")
  42. for _, tag := range tags {
  43. kv := strings.Split(tag, ":")
  44. kv[0] = strings.Trim(kv[0], " ")
  45. if len(kv) == 1 && kv[0] == key {
  46. return kv[0], true
  47. }
  48. if len(kv) == 2 && kv[0] == key {
  49. kv[1] = strings.Trim(kv[1], " ")
  50. return kv[1], true
  51. }
  52. }
  53. }
  54. return "", false
  55. }
  56. // hasTags checks if it has all keys
  57. func (f *field) hasTags(keys ...string) bool {
  58. match := 0
  59. for _, key := range keys {
  60. if f.hasTag(key) {
  61. match += 1
  62. }
  63. }
  64. return len(keys) == match
  65. }
  66. // hasTags checks if it has key
  67. func (f *field) hasTag(key string) bool {
  68. if _, ok := f.getTag(key); ok {
  69. return true
  70. }
  71. return false
  72. }