relation.go 985 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. func (r relation) getNameAs(q bool) string {
  27. return r.getName(q) + " AS " + r.getAlias(q)
  28. }
  29. // relations holds all relation on types
  30. type relations struct {
  31. rmap map[relType][]relation
  32. m *sync.Mutex
  33. }
  34. // addRelation to collection. Requires fields to have equal type
  35. func (r relations) addRelation(rt relType, rel relation) {
  36. r.m.Lock()
  37. defer r.m.Unlock()
  38. if _, ok := r.rmap[rt]; !ok {
  39. r.rmap[rt] = make([]relation, 0)
  40. }
  41. if rel.on.getKind() != rel.key.getKind() {
  42. return
  43. }
  44. r.rmap[rt] = append(r.rmap[rt], rel)
  45. }