relation.go 891 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package orm
  2. import (
  3. "sync"
  4. )
  5. // relType describes relation type
  6. type relType int8
  7. // Of these three
  8. const (
  9. hasOne relType = iota << 1
  10. hasMany relType = iota << 1
  11. belongsTo relType = iota << 1
  12. )
  13. // relation describes how tables are related
  14. type relation struct {
  15. *table
  16. f field
  17. on column
  18. key column
  19. }
  20. func (r relation) getAlias(q bool) string {
  21. if q {
  22. return SqlFlavor.Quote(r.getAlias(false))
  23. }
  24. return r.f.getFieldName()
  25. }
  26. // relations holds all relation on types
  27. type relations struct {
  28. rmap map[relType][]relation
  29. m *sync.Mutex
  30. }
  31. // addRelation to collection. Requires fields to have equal type
  32. func (r relations) addRelation(rt relType, rel relation) {
  33. r.m.Lock()
  34. defer r.m.Unlock()
  35. if _, ok := r.rmap[rt]; !ok {
  36. r.rmap[rt] = make([]relation, 0)
  37. }
  38. if rel.on.getKind() != rel.key.getKind() {
  39. return
  40. }
  41. r.rmap[rt] = append(r.rmap[rt], rel)
  42. }