当前位置: 首页>>代码示例>>Golang>>正文


Golang gorm.DB类代码示例

本文整理汇总了Golang中github.com/jinzhu/gorm.DB的典型用法代码示例。如果您正苦于以下问题:Golang DB类的具体用法?Golang DB怎么用?Golang DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: PostLike

func PostLike(db gorm.DB, router *gin.Engine) {
	// POST /like
	// POST new like to database
	router.POST("/like", func(c *gin.Context) {
		var likeData model.LikeData
		if err := c.BindJSON(&likeData); err == nil {
			like := &model.Like{
				LikeData: likeData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				like.Trace.CreatedBy = x_user
				like.Trace.UpdatedBy = x_user
				if err := checkDataLike(like.LikeData); err {
					if err := db.Create(&like).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, like)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:35,代码来源:like.go

示例2: PostActivity

func PostActivity(db gorm.DB, router *gin.Engine) {
	// POST /activity
	// POST new activity to database
	router.POST("/activity", func(c *gin.Context) {
		var activityData model.ActivityData
		if err := c.BindJSON(&activityData); err == nil {
			activity := &model.Activity{
				ActivityData: activityData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				activity.Trace.CreatedBy = x_user
				activity.Trace.UpdatedBy = x_user
				if err := checkDataActivity(activity.ActivityData); err {
					if err := db.Create(&activity).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, activity)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:35,代码来源:activity.go

示例3: releasesCreate

// releasesCreate creates a new Release and inserts it into the database.
func releasesCreate(db *gorm.DB, release *Release) (*Release, error) {
	t := db.Begin()

	// Get the last release version for this app.
	v, err := releasesLastVersion(t, release.App.ID)
	if err != nil {
		t.Rollback()
		return release, err
	}

	// Increment the release version.
	release.Version = v + 1

	if err := t.Create(release).Error; err != nil {
		t.Rollback()
		return release, err
	}

	if err := t.Commit().Error; err != nil {
		t.Rollback()
		return release, err
	}

	return release, nil
}
开发者ID:yourchanges,项目名称:empire,代码行数:26,代码来源:releases.go

示例4: isAuthorized

func isAuthorized(db *gorm.DB, nameOfTable, header string) (*authPair, bool) {
	// blank login and password with ":" separator return, in base64, a size of 10 char
	if len(header) <= 10 {
		return nil, false
	}

	var i int
	var u authPair
	var cred string

	// get credentials from header
	if value, err := base64.StdEncoding.DecodeString(header[6:]); err != nil {
		return nil, false
	} else {
		cred = string(value)
	}

	// check ":" separator
	i = strings.Index(cred, ":")

	// check present in database
	db.Table(nameOfTable).Select(
		"identifiant, mot_de_passe").Where(
		"identifiant=? and mot_de_passe=?", cred[:i], cred[i+1:]).Find(&u)

	if reflect.DeepEqual(u, authPair{}) {
		return nil, false
	}

	// success
	return &u, true
}
开发者ID:Chipsterjulien,项目名称:basicAuthWithDBForGin,代码行数:32,代码来源:auth.go

示例5: MediaCreate

func MediaCreate(db gorm.DB, r render.Render, media models.Media) {
	if err := db.Save(&media).Error; err != nil {
		r.JSON(http.StatusConflict, map[string]interface{}{"error": "Media conflict"})
		return
	}
	r.JSON(http.StatusCreated, media)
}
开发者ID:RadioTerminal,项目名称:podcaster,代码行数:7,代码来源:media.go

示例6: AddUserFile

func AddUserFile(db *gorm.DB, udt *UserFileInfo, content []byte) error {

	lastId, err := getLastFileIdByUserId(db, udt.UserId)
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}
	nextId := lastId + 1
	// revel.INFO.Println("Next DS id: ", nextId)
	udt.FileId = nextId

	err = db.Save(udt).Error
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}

	ds := &UserFile{
		UserId:  udt.UserId,
		FileId:  udt.FileId,
		Content: content,
	}

	err = db.Save(ds).Error
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}

	return err
}
开发者ID:slnaing07,项目名称:revel-modz,代码行数:31,代码来源:userfiles.go

示例7: AddTables

func AddTables(db *gorm.DB) error {
	err := db.AutoMigrate(UserFileInfo{}).Error
	if err != nil {
		return err
	}
	return db.AutoMigrate(UserFile{}).Error
}
开发者ID:slnaing07,项目名称:revel-modz,代码行数:7,代码来源:userfiles.go

示例8: PutGroupAdmin

func PutGroupAdmin(db gorm.DB, router *gin.Engine) {
	// PUT /group_admin
	// Update group_admin data by id
	router.PUT("/group_admin/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var group_adminData model.GroupAdminData
			if err := c.BindJSON(&group_adminData); err == nil {
				group_admin := &model.GroupAdmin{
					GroupAdminData: group_adminData,
					GroupAdminId:   model.GroupAdminId{Id: id},
				}
				if err := checkDataGroupAdmin(group_admin.GroupAdminData); err {
					checkGroupAdmin := &model.GroupAdmin{
						GroupAdminData: group_adminData,
						GroupAdminId:   model.GroupAdminId{Id: id},
					}
					if err := db.First(checkGroupAdmin).Error; err == nil {
						db.Save(&group_admin)
						c.JSON(http.StatusOK, group_admin)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:group_admin.go

示例9: PostGroupAdmin

func PostGroupAdmin(db gorm.DB, router *gin.Engine) {
	// POST /group_admin
	// POST new group_admin to database
	router.POST("/group_admin", func(c *gin.Context) {
		var group_adminData model.GroupAdminData
		if err := c.BindJSON(&group_adminData); err == nil {
			group_admin := &model.GroupAdmin{
				GroupAdminData: group_adminData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				group_admin.Trace.CreatedBy = x_user
				group_admin.Trace.UpdatedBy = x_user
				if err := checkDataGroupAdmin(group_admin.GroupAdminData); err {
					if err := db.Create(&group_admin).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, group_admin)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:35,代码来源:group_admin.go

示例10: AllDistinctDates

func AllDistinctDates(db gorm.DB) []Date {
	var results []Date
	scope := db.Table("media").Select("date_part('day', taken_at) as day, date_part('month', taken_at) as month, date_part('year', taken_at) as year")
	scope = scope.Group("day, month, year").Order("year, month, day")
	scope.Scan(&results)
	return results
}
开发者ID:jaischeema,项目名称:panorma,代码行数:7,代码来源:models.go

示例11: compositeIndex

func compositeIndex(table *gorm.DB, kind string, primary_key string, dst interface{}, parents []string) {

	index_name := "idx_" + kind + "_" + primary_key
	indexes := []string{primary_key}

	if len(parents) == 0 {
		parents = []string{}
		st := reflect.TypeOf(dst).Elem()
		for i := 0; i < st.NumField(); i++ {
			field := st.Field(i)
			pacific_parent := field.Tag.Get("pacific_parent")
			if pacific_parent != "" {
				parents = append(parents, pacific_parent)
			}
		}
	}

	for _, parent := range parents {
		if parent != "" {
			index_name = index_name + "_" + parent
			indexes = append(indexes, parent)
		}
	}

	if len(indexes) > 0 {
		table.AddUniqueIndex(index_name, indexes...) //TODO: if not exists?
	}
}
开发者ID:likestripes,项目名称:pacific,代码行数:28,代码来源:postgres.go

示例12: isAuthorized

func isAuthorized(db *gorm.DB, nameOfTable, header string) (*authPair, bool) {

	var i int
	var u authPair
	var cred string

	// get credentials from header
	if value, err := base64.StdEncoding.DecodeString(header); err != nil {
		return nil, false
	} else {
		cred = string(value)
	}

	// check format
	if i = strings.Index(cred, ":"); len(cred) < 8 || i < 8 {
		return nil, false
	}

	// check present in database
	db.Table(nameOfTable).Select(
		"identifiant, mot_de_passe").Where(
		"identifiant=? and mot_de_passe=?", cred[6:i], cred[i:]).Find(&u)
	if reflect.DeepEqual(u, authPair{}) {
		return nil, false
	}

	// success
	return &u, true
}
开发者ID:WnP,项目名称:basicAuthWithDBForGin,代码行数:29,代码来源:auth.go

示例13: storeFact

func storeFact(Fact *models.Fact, db *gorm.DB) (*models.Fact, error) {
	var err error

	if Fact == nil {
		return nil, errors.New("save: fact is nil")
	}

	if Fact.ID == 0 {
		err := db.Create(Fact).Error
		if err != nil {
			return nil, err
		}
	}

	var f models.Fact

	if err := db.Where(&models.Fact{ID: Fact.ID}).First(&f).Error; err != nil {
		return nil, err
	}
	if err := db.Where(f.ActionID).First(&f.Action).Error; err != nil {
		return nil, err
	}
	err = db.Where(f.ContactID).First(&f.Contact).Error
	if err != nil { //&& err != gorm.RecordNotFound
		return nil, err
	}

	if err == nil {
		if err := db.Where(f.Contact.AddressID).First(&f.Contact.Address).Error; err != nil { //&& err != gorm.RecordNotFound
			return nil, err
		}
	}

	return &f, nil
}
开发者ID:quorumsco,项目名称:indexor,代码行数:35,代码来源:main.go

示例14: PutActivity

func PutActivity(db gorm.DB, router *gin.Engine) {
	// PUT /activity
	// Update activity data by id
	router.PUT("/activity/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var activityData model.ActivityData
			if err := c.BindJSON(&activityData); err == nil {
				activity := &model.Activity{
					ActivityData: activityData,
					ActivityId:   model.ActivityId{Id: id},
				}
				if err := checkDataActivity(activity.ActivityData); err {
					checkActivity := &model.Activity{
						ActivityData: activityData,
						ActivityId:   model.ActivityId{Id: id},
					}
					if err := db.First(checkActivity).Error; err == nil {
						db.Save(&activity)
						c.JSON(http.StatusOK, activity)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:activity.go

示例15: getPlayerWeapons

func getPlayerWeapons(db *gorm.DB, player uint) []WeaponStat {

	// have some initial capacity
	ws := make([]WeaponStat, 0, 10)

	rows, err := db.Table("weapon_stats").
		Select("type, sum(weapon_stats.shots) as shots, sum(weapon_stats.hits) as hits, sum(weapon_stats.kills) as kills").
		Joins("join player_match_stats on weapon_stats.player_match_stat_id = player_match_stats.id").
		Joins("join aliases on player_match_stats.alias_id = aliases.id").
		Where("aliases.player_id = ?", player).
		Group("weapon_stats.type").
		Rows()

	if err != nil {
		log.Printf("query failed: %s", err)
		return ws
	}

	for rows.Next() {
		var t string     // type
		var k, s, h uint // kills, shots, hits
		if err := rows.Scan(&t, &s, &h, &k); err != nil {
			log.Printf("failed to scan row: %s", err)
		}
		log.Printf("stats: %s %v %v %v", t, s, h, k)
		ws = append(ws, WeaponStat{
			Shots: s,
			Kills: k,
			Hits:  h,
			Type:  t,
		})
	}

	return ws
}
开发者ID:bboozzoo,项目名称:q3stats,代码行数:35,代码来源:playerglobal.go


注:本文中的github.com/jinzhu/gorm.DB类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。