package model import ( "encoding/json" "strings" "time" ) const sentinelYear = 1 func SentinelBirthday() time.Time { return time.Date(sentinelYear, 1, 1, 0, 0, 0, 0, time.UTC) } type Sex uint8 const ( SexUnknown Sex = 0 SexMale Sex = 1 SexFemale Sex = 2 ) func (s *Sex) UnmarshalJSON(b []byte) error { var raw string if err := json.Unmarshal(b, &raw); err == nil { switch strings.ToLower(strings.TrimSpace(raw)) { case "male": *s = SexMale return nil case "female": *s = SexFemale return nil case "", "unknown", "null": *s = SexUnknown return nil } } // also accept numbers in JSON var n int if err := json.Unmarshal(b, &n); err == nil { *s = Sex(n) return nil } *s = SexUnknown return nil } type User struct { ID uint64 `gorm:"primaryKey"` Nick string `gorm:"not null;uniqueIndex:uniq_user_nick"` Name string Surname string Fathersname string Sex Sex `gorm:"type:smallint;check:sex IN (0,1,2)"` Birthday time.Time Cards []Card `gorm:"foreignKey:UserID"` // just for compatibility Flights []Flight `gorm:"many2many:user_flights;joinForeignKey:UserID;joinReferences:FlightID"` } func (User) TableName() string { return "users" } type Card struct { ID uint64 `gorm:"primaryKey"` Prefix string `gorm:"not null;uniqueIndex:uniq_card_identity"` Number uint64 `gorm:"not null;uniqueIndex:uniq_card_identity"` Bonusprogramm string `gorm:"not null;uniqueIndex:uniq_card_identity"` // User has multiple cards -> each card has registered flights to it Flights []Flight `gorm:"many2many:card_flights;joinForeignKey:CardID;joinReferences:FlightID"` UserID uint64 User User `gorm:"foreignKey:UserID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` } func (Card) TableName() string { return "cards" } type Flight struct { ID uint64 `gorm:"primaryKey"` Number string `gorm:"not null;uniqueIndex:uniq_flight_identity"` From string `gorm:"not null;uniqueIndex:uniq_flight_identity"` FromCity string `gorm:"not null;uniqueIndex:uniq_flight_identity"` FromCountry string `gorm:"not null;uniqueIndex:uniq_flight_identity"` To string `gorm:"not null;uniqueIndex:uniq_flight_identity"` ToCity string `gorm:"not null;uniqueIndex:uniq_flight_identity"` ToCountry string `gorm:"not null;uniqueIndex:uniq_flight_identity"` Date time.Time `gorm:"not null;uniqueIndex:uniq_flight_identity"` Users []User `gorm:"many2many:user_flights;joinForeignKey:FlightID;joinReferences:UserID"` Cards []Card `gorm:"many2many:card_flights;joinForeignKey:FlightID;joinReferences:CardID"` } func (Flight) TableName() string { return "flights" }