github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/internal/router/sql/router.go (about) 1 package sqlRouter 2 3 import ( 4 "github.com/ronaksoft/rony/tools" 5 "gorm.io/gorm" 6 "gorm.io/gorm/clause" 7 ) 8 9 type Router struct { 10 db *gorm.DB 11 } 12 13 func New(db *gorm.DB) *Router { 14 r := &Router{ 15 db: db, 16 } 17 18 _ = r.db.AutoMigrate(&Entity{}) 19 20 return r 21 } 22 23 func (r *Router) Set(entityID string, replicaSet uint64, replace bool) error { 24 e := &Entity{ 25 EntityID: entityID, 26 ReplicaSet: replicaSet, 27 CreatedOn: tools.TimeUnix(), 28 EditedOn: tools.TimeUnix(), 29 } 30 31 if replace { 32 return r.db.Clauses(clause.OnConflict{UpdateAll: true}).Create(e).Error 33 } else { 34 return r.db.Create(e).Error 35 } 36 } 37 38 func (r *Router) Get(entityID string) (replicaSet uint64, err error) { 39 var entity = &Entity{} 40 err = r.db.First(entity, "entity_id = ?", entityID).Error 41 42 return entity.ReplicaSet, err 43 }