// AfterSave invokes required actions after persisting. func (u *Repo) AfterSave(db *gorm.DB) (err error) { tags := Tags{} err = db.Model( u, ).Related( &tags, ).Error if err != nil { return err } for _, tag := range tags { err = db.Save( tag, ).Error if err != nil { return err } } return nil }
func (pp *PurchaseProduct) UpdateValue(db *gorm.DB, value float64) error { pps, err := pp.Retreive(db) if err != nil { return err } if len(pps) != 1 { return errors.New("record not found") } *pp = pps[0] if err := VerifyUpdatePurchaseProduct(db, pp); err != nil { return err } err = db.Model(pp).UpdateColumn(PurchaseProduct{Value: value}).Error if err != nil { return err } pp.Value = value return nil }
// AfterSave invokes required actions after persisting. func (u *Registry) AfterSave(db *gorm.DB) (err error) { orgs := Orgs{} err = db.Model( u, ).Related( &orgs, ).Error if err != nil { return err } for _, org := range orgs { err = db.Save( org, ).Error if err != nil { return err } } return nil }
func New(db *gorm.DB) i18n.Backend { db.AutoMigrate(&Translation{}) if err := db.Model(&Translation{}).AddUniqueIndex("idx_translations_key_with_locale", "locale", "key").Error; err != nil { fmt.Printf("Failed to create unique index for translations key & locale, got: %v\n", err.Error()) } return &Backend{DB: db} }
func FacultiesDepartments(db *gorm.DB) ([]json_models.FacultiesDepartments, error) { var result []json_models.FacultiesDepartments err := db.Model(&models.Faculties{}).Select("id as faculty_id, short_name as faculty_name").Scan(&result).Error if err != nil { return nil, err } for i, faculty := range result { var records []models.Departments err := db.Preload("Faculty").Where("faculty_id = ?", faculty.FacultyId).Find(&records).Error if err != nil { return nil, err } if len(records) != 0 { for _, record := range records { val := json_models.Department{Id: record.Id, Name: record.Name} result[i].Departments = append(result[i].Departments, val) } } else { result[i].Departments = []json_models.Department{} } } return result, nil }
func (pp *PurchaseProduct) UpdateQuantity(db *gorm.DB, quantity int) error { pps, err := pp.Retreive(db) if err != nil { return err } if len(pps) != 1 { return errors.New("record not found") } *pp = pps[0] if err := VerifyUpdatePurchaseProduct(db, pp); err != nil { return err } err = db.Model(pp).UpdateColumn(PurchaseProduct{Quantity: quantity}).Error if err != nil { return err } pp.Quantity = quantity return nil }
func (p *SettingDao) Set(db *gorm.DB, key string, val interface{}, enc bool) error { dt, err := web.ToBits(val) if err != nil { db.Rollback() return err } if enc { dt, err = p.Aes.Encode(dt) if err != nil { db.Rollback() return err } } st := Setting{ID: key} var cn int db.Model(st).Count(&cn) if cn == 0 { st.Val = dt db.Create(&st) } else { db.Model(&st).Updates(Setting{Val: dt}) } return nil }
func (p *AuthDao) getRole(db *gorm.DB, name string, resource_type string, resource_id uint) *Role { role := Role{} db.FirstOrCreate(&role, Role{Name: name, ResourceType: resource_type, ResourceID: resource_id}) db.Model(&role).Related(&role.Permissions) return &role }
func UpdateTask(db *gorm.DB, data models.Tasks) error { err := db.Model(data).Updates(data).Error if err != nil { return err } return nil }
// AfterSave invokes required actions after persisting. func (u *Org) AfterSave(db *gorm.DB) (err error) { repos := Repos{} err = db.Model( u, ).Related( &repos, ).Error if err != nil { return err } for _, repo := range repos { err = db.Save( repo, ).Error if err != nil { return err } } return nil }
func FeedForGroupGet(db gorm.DB, params martini.Params, res http.ResponseWriter) (int, string) { podcast := models.Group{} var media = []models.Media{} if err := db.Where(&models.Group{Slug: params["slug"]}).First(&podcast).Error; err != nil { res.Header().Set(ContentType, PlainType) return http.StatusNotFound, "Feed not found" } db.Model(&podcast).Order("created_at desc").Limit(15).Related(&media) tpl, err := template.New("xml_feed").Funcs(template.FuncMap{"short": ShortenString}).Parse(xml_feed_t) if err != nil { res.Header().Set(ContentType, PlainType) return http.StatusInternalServerError, "Generating XML failed" } data := Feed{&podcast, &media} buf := new(bytes.Buffer) err = tpl.Execute(buf, data) log.Println(err) if err != nil { res.Header().Set(ContentType, PlainType) return http.StatusInternalServerError, "Generating XML failed" } res.Header().Set(ContentType, RSSType) return http.StatusOK, buf.String() }
// GetRepo retrieves a specific repo from the database. func (db *data) GetRepo(id string) (*model.Repo, *gorm.DB) { var ( record = &model.Repo{} query *gorm.DB ) if match, _ := regexp.MatchString("^([0-9]+)$", id); match { val, _ := strconv.ParseInt(id, 10, 64) query = db.Where( "id = ?", val, ) } else { query = db.Where( "slug = ?", id, ) } res := query.Model( &record, ).Preload( "Org", ).Preload( "Org.Registry", ).Preload( "Tags", ).First( &record, ) return record, res }
// SaveBinary will efficently save a binary and it's associated parts. // Having to do this for efficency is probably a good sign that I should just // use sqlx or something. func saveBinary(tx *gorm.DB, b *types.Binary) error { var txerr error if tx.NewRecord(b) { parts := b.Parts b.Parts = []types.Part{} txerr = tx.Save(b).Error if txerr != nil { return txerr } pids := make([]int64, len(parts)) for i, p := range parts { pids[i] = p.ID } txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error if txerr != nil { return txerr } } else { pids := make([]int64, len(b.Parts)) for i, p := range b.Parts { pids[i] = p.ID } txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error if txerr != nil { return txerr } } return nil }
func CreateClient(db gorm.DB, options *Options) (id int64) { var c Client db.Where( &Client{ Hostname: options.Hostname, Interface: options.Interface, MacAddr: options.InterfaceData.HardwareAddr.String(), Ip: options.Ip, }, ).First(&c) if c.Id != 0 { db.Model(&c).Update( &Client{ LastSeen: time.Now().Unix(), }, ) } else { c.LastSeen = time.Now().Unix() c.Hostname = options.Hostname c.MacAddr = options.InterfaceData.HardwareAddr.String() c.Interface = options.Interface c.Ip = options.Ip db.Table("clients").Create(&c) } options.Client = &c return c.Id }
// Retreive purchase from database func (purch *Purchase) Retreive(db *gorm.DB) ([]Purchase, error) { var purchs []Purchase err := db.Where(purch).Find(&purchs).Error if err != nil { return nil, err } for i, p := range purchs { order := Order{} order.ID = p.OrderId if err := db.Model(&p).Related(&order, "OrderId").Error; err != nil { return nil, err } pproducts := []PurchaseProduct{} if err := db.Model(order).Related(&pproducts, "Pproducts").Error; err != nil { fmt.Println("[ERROR] ", err.Error()) return nil, err } order.Pproducts = pproducts p.PurschaseOrder = order purchs[i] = p } return purchs, err }
//Migrate db:migrate func (p *Engine) Migrate(db *gorm.DB) { db.AutoMigrate( &Article{}, &Tag{}, &Comment{}, &Attachment{}, ) db.Model(&Tag{}).AddUniqueIndex("idx_cms_tag_name_lang", "name", "lang") }
// Conclude purchase func (purch *Purchase) Conclude(db *gorm.DB) error { rowsAffected := db.Model(purch).Where("confirmed_at != ?", 0).UpdateColumn(Purchase{ConcludedAt: int(time.Now().Unix())}).RowsAffected if rowsAffected != 1 { return errors.New("[ERROR] Purchase must be confirmed before conlcuded") } return nil }
func FacultyGroupsIds(db *gorm.DB, faculty_id int64, year int) []int64 { var groups []int64 err := db.Model(&models.Groups{}).Where(&models.Groups{FacultyId: faculty_id, Year: year}).Pluck("id", &groups).Error if err != nil { panic(err) } return groups }
//Stop the task func (t *Task) Stop(txn *gorm.DB) error { if t.CronID != 0 { entryID := cron.EntryID(t.CronID) MasterCron.Remove(entryID) utils.Log.Infof("The task %s has been stopped", t.ID) return txn.Model(t).UpdateColumn("cron_id", 0).Error } return nil }
func GroupUpdate(db gorm.DB, r render.Render, params martini.Params, updatedGroup models.Group) { var group models.Group if err := db.First(&group, params["id"]).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Group not found"}) return } db.Model(&group).Update(&updatedGroup) r.JSON(http.StatusOK, group) }
func MediaUpdate(db gorm.DB, r render.Render, params martini.Params, updatedMedia models.Media) { var media models.Media if err := db.First(&media, params["id"]).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Media not found"}) return } db.Model(&media).Update(&updatedMedia) r.JSON(http.StatusOK, media) }
// CreateTUFTable creates the DB table for TUFFile func CreateTUFTable(db gorm.DB) error { // TODO: gorm query := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&TUFFile{}) if query.Error != nil { return query.Error } query = db.Model(&TUFFile{}).AddUniqueIndex( "idx_gun", "gun", "role", "version") return query.Error }
func MediaPlay(db gorm.DB, r render.Render, params martini.Params) { media := models.Media{} id, _ := strconv.Atoi(params["id"]) if err := db.First(&media, id).Error; err != nil { r.Error(http.StatusNotFound) return } db.Model(&media).Update(&models.Media{Played: media.Played + 1}) r.Redirect(media.Url) }
func MediaForGroupGet(db gorm.DB, r render.Render, params martini.Params) { podcast := models.Group{} media := []models.Media{} if err := db.Where("slug = ?", params["slug"]).First(&podcast).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Group not found"}) return } db.Model(&podcast).Order("created_at desc").Related(&media) r.JSON(http.StatusOK, media) }
func (u *Media) BeforeCreate(tx *gorm.DB) (err error) { var count int tx.Model(u).Where("name = ?", u.Name).Count(&count) if count > 0 { err = errors.New("Media exists!") return } u.Slug = slug.Slug(u.Name) return }
func (u *Group) BeforeUpdate(tx *gorm.DB) (err error) { var count int tx.Model(u).Where("name = ?", u.Name).Count(&count) if count > 1 { err = errors.New("Conflicting Name!") return } u.Slug = slug.Slug(u.Name) return }
// BeforeDelete invokes required actions before deletion. func (u *Team) BeforeDelete(tx *gorm.DB) error { if err := tx.Model(u).Association("Users").Clear().Error; err != nil { return err } // TODO(tboerger): Prevent delete if team is last owner if err := tx.Model(u).Association("Orgs").Clear().Error; err != nil { return err } return nil }
//Migrate db:migrate func (p *Engine) Migrate(db *gorm.DB) { i18n.Migrate(db) db.AutoMigrate( &Setting{}, &Notice{}, &User{}, &Role{}, &Permission{}, &Log{}, ) db.Model(&User{}).AddUniqueIndex("idx_user_provider_type_id", "provider_type", "provider_id") db.Model(&Role{}).AddUniqueIndex("idx_roles_name_resource_type_id", "name", "resource_type", "resource_id") db.Model(&Permission{}).AddUniqueIndex("idx_permissions_user_role", "user_id", "role_id") }
func (user *User) Validate(db *gorm.DB) { govalidator.CustomTypeTagMap.Set("uniqEmail", govalidator.CustomTypeValidator(func(email interface{}, context interface{}) bool { var count int if db.Model(&User{}).Where("email = ?", email).Count(&count); count == 0 || email == "" { return true } return false })) if user.Name == "invalid" { db.AddError(validations.NewError(user, "Name", "invalid user name")) } }
func (p *LocaleDao) Set(db *gorm.DB, lang, code, message string) { var l Locale if db.Select("id").Where("lang = ? AND code = ?", lang, code).First(&l).RecordNotFound() { db.Create(&Locale{Lang: lang, Code: code, Message: message}) } else { db.Model(Locale{}).Where("id = ?", l.ID).Updates(Locale{Message: message}) } }