Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GORM Foreign key support #136

Merged
merged 2 commits into from
Feb 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions server/src/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,17 @@ func GetPlayerStatInfo(c *gin.Context) {
func GetUserInfo(c *gin.Context) {
log.Printf("GetUserInfo\n")
userid := c.Params.ByName("userID")
response := APIUserData{}
db.SQLAccess.Gorm.First(&response, userid)
db.SQLAccess.Gorm.Where("user_id = ?", userid).Limit(20).Find(&response.Teams)
db.SQLAccess.Gorm.Where("user_id = ?", userid).Limit(20).Find(&response.Servers)
user := &APIUserData{}
db.SQLAccess.Gorm.First(user, userid)

db.SQLAccess.Gorm.Model(user).Related(&user.Teams, "Teams")
db.SQLAccess.Gorm.Model(user).Related(&user.Servers, "Servers")

matches := []db.MatchData{}
db.SQLAccess.Gorm.Where("user_id = ?", userid).Limit(20).Find(&matches)

var m []APIMatchData
db.SQLAccess.Gorm.Model(user).Related(&matches, "Matches")

var m []*APIMatchData
for i := 0; i < len(matches); i++ {
mapstats := []APIMapStatsData{}
server := APIGameServerData{}
Expand Down Expand Up @@ -220,10 +222,10 @@ func GetUserInfo(c *gin.Context) {
User: user,
Status: status,
}
m = append(m, matchdata)
m = append(m, &matchdata)
}
response.Matches = m
c.JSON(http.StatusOK, response)
user.Matches = m
c.JSON(http.StatusOK, user)
}

func GetServerInfo(c *gin.Context) {
Expand Down Expand Up @@ -254,9 +256,11 @@ func GetMatches(c *gin.Context) {
offset = "0"
}
userID := c.Query("userID")
user := db.UserData{}
response := []db.MatchData{}
if userID != "" {
db.SQLAccess.Gorm.Limit(20).Where("user_id = ?", userID).Order("id DESC").Offset(offset).Find(&response)
db.SQLAccess.Gorm.Limit(20).First(&user, userID)
db.SQLAccess.Gorm.Model(&user).Related(&response, "Matches")
} else {
db.SQLAccess.Gorm.Limit(20).Order("id DESC").Offset(offset).Find(&response)
}
Expand All @@ -267,11 +271,15 @@ func GetTeamInfo(c *gin.Context) {
log.Printf("GetTeamInfo\n")
teamid, err := strconv.Atoi(c.Params.ByName("teamID"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("teamID shoulbe int"))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("teamID should be int"))
return
}
response := APITeamData{}
db.SQLAccess.Gorm.First(&response, teamid)
rec := db.SQLAccess.Gorm.First(&response, teamid)
if rec.RecordNotFound() {
c.AbortWithError(http.StatusNotFound, fmt.Errorf("team not found"))
return
}
var steamids = make([]string, 5)
steamids, err = response.GetPlayers()
if err != nil {
Expand Down
15 changes: 7 additions & 8 deletions server/src/api/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ import (

// UserData Struct for "user" table.
type APIUserData struct {
ID int `gorm:"primary_key;column:id;AUTO_INCREMENT" json:"id"`
SteamID string `gorm:"column:steam_id;unique" json:"steam_id"`
Name string `gorm:"column:name" json:"name"`
Admin bool `gorm:"column:admin" json:"admin"`

Servers []APIGameServerData `gorm:"foreignkey:-" json:"servers"`
Teams []APITeamData `gorm:"foreignkey:-" json:"teams"`
Matches []APIMatchData `gorm:"foreignkey:-" json:"matches"`
ID int `gorm:"primary_key;column:id;AUTO_INCREMENT" json:"id"`
SteamID string `gorm:"column:steam_id;unique" json:"steam_id"`
Name string `gorm:"column:name" json:"name"`
Admin bool `gorm:"column:admin" json:"admin"`
Servers []*APIGameServerData `gorm:"ForeignKey:UserID" json:"servers"`
Teams []*APITeamData `gorm:"ForeignKey:UserID" json:"teams"`
Matches []*APIMatchData `gorm:"ForeignKey:UserID" json:"matches"`
}

// TableName declairation for GORM
Expand Down
5 changes: 4 additions & 1 deletion server/src/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ var (
)

func init() {
c, _ := ini.Load("config.ini")
c, err := ini.Load("config.ini")
if err != nil {
panic(err)
}
Cnf := Config{
SteamAPIKey: c.Section("Steam").Key("APIKey").MustString(""),
DefaultPage: c.Section("GET5").Key("DefaultPage").MustString(""),
Expand Down
55 changes: 26 additions & 29 deletions server/src/db/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ type UserData struct {
Name string `gorm:"column:name"`
Admin bool `gorm:"column:admin"`

Servers []GameServerData `gorm:"foreignkey:user_id"`
Teams []TeamData `gorm:"foreignkey:user_id"`
Matches []MatchData `gorm:"foreignkey:user_id"`
Servers []*GameServerData `gorm:"ForeignKey:UserID"`
Teams []*TeamData `gorm:"ForeignKey:UserID"`
Matches []*MatchData `gorm:"ForeignKey:UserID"`
}

// TableName declairation for GORM
Expand Down Expand Up @@ -112,22 +112,15 @@ func (u *UserData) GetSteamURL() string {
}

// GetRecentMatches Gets match history
func (u *UserData) GetRecentMatches(limit int) []MatchData {
SQLAccess.Gorm.Where("user_id = ?", u.ID).Limit(limit).Find(&u.Matches)
//SQLAccess.Gorm.Model(&u).Related(&u.Matches)
func (u *UserData) GetRecentMatches(limit int) []*MatchData {
SQLAccess.Gorm.Model(u).Related(&u.Matches, "Matches")
return u.Matches
//u.Matches
//return self.matches.filter_by(cancelled=False).limit(limit)
}

// GetTeams Get teams which is owened by user
func (u *UserData) GetTeams(limit int) []*TeamData {
SQLAccess.Gorm.Where("user_id = ?", u.ID).Limit((limit)).Find(&u.Teams)
teampointer := make([]*TeamData, 0, len(u.Teams))
for i := 0; i < len(u.Teams); i++ {
teampointer = append(teampointer, &u.Teams[i])
}
return teampointer
SQLAccess.Gorm.Model(u).Related(&u.Teams, "Teams")
return u.Teams
}

// GameServerData Struct for game_server table.
Expand All @@ -140,8 +133,6 @@ type GameServerData struct {
RconPassword string `gorm:"column:rcon_password;DEFAULT NULL" json:"rcon_password"`
DisplayName string `gorm:"column:display_name;DEFAULT NULL" json:"display_name"`
PublicServer bool `gorm:"column:public_server;DEFAULT NULL" json:"public_server"`

User UserData `gorm:"ASSOCIATION_FOREIGNKEY:user_id"`
}

// TableName declairation for GORM
Expand All @@ -155,7 +146,12 @@ func (g *GameServerData) Create(userid int, displayname string, ipstring string,
return nil, fmt.Errorf("IPaddress or RCON password is empty")
}
var servernum int
SQLAccess.Gorm.Model(&GameServerData{}).Where("user_id = ?", userid).Count(&servernum)
user := UserData{}
err := SQLAccess.Gorm.First(&user, userid).Error
if err != nil {
return nil, err
}
SQLAccess.Gorm.Model(&user).Related(&user.Servers, "Servers").Count(&servernum)
if uint16(servernum) >= MaxResource.Servers {
return nil, fmt.Errorf("Max servers limit exceeded")
}
Expand All @@ -166,7 +162,7 @@ func (g *GameServerData) Create(userid int, displayname string, ipstring string,
g.RconPassword = rconpassword
g.PublicServer = publicserver

_, err := util.CheckServerAvailability(g.IPString, g.Port, g.RconPassword)
_, err = util.CheckServerAvailability(g.IPString, g.Port, g.RconPassword)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -268,9 +264,6 @@ type TeamData struct {
Auths []string `gorm:"-" json:"auths"` // converts pickle []byte to []string
Players []PlayerStatsData `gorm:"-" json:"-"`
PublicTeam bool `gorm:"column:public_team" json:"public_team"`

// User UserData `gorm:"ASSOCIATION_FOREIGNKEY:user_id" json:"-"`
User UserData `gorm:"-" json:"-"`
}

// TableName declairation for GORM
Expand All @@ -284,7 +277,12 @@ func (t *TeamData) Create(userid int, name string, tag string, flag string, logo
return nil, fmt.Errorf("Team name cannot be empty")
}
var teamnum int
SQLAccess.Gorm.Model(&TeamData{}).Where("user_id = ?", userid).Count(&teamnum)
user := UserData{}
err := SQLAccess.Gorm.First(&user, userid).Error
if err != nil {
return nil, err
}
SQLAccess.Gorm.Model(&user).Related(&user.Teams, "Teams").Count(&teamnum)
if uint16(teamnum) >= MaxResource.Teams {
return nil, fmt.Errorf("Max teams limit exceeded")
}
Expand All @@ -294,7 +292,6 @@ func (t *TeamData) Create(userid int, name string, tag string, flag string, logo
t.Flag = flag
t.Logo = logo
t.PublicTeam = publicteam
var err error
for i := 0; i < len(auths); i++ {
auths[i], err = util.AuthToSteamID64(auths[i])
if err != nil {
Expand Down Expand Up @@ -428,14 +425,14 @@ func (t *TeamData) GetPlayers() ([]PlayerStatsData, error) {
*/

// GetRecentMatches Gets team match history.
func (t *TeamData) GetRecentMatches(limit int) []MatchData {
var matches []MatchData
func (t *TeamData) GetRecentMatches(limit int) []*MatchData {
var matches []*MatchData
if t.PublicTeam == true {
SQLAccess.Gorm.Where("team1_id = ?", t.ID).Or("team2_id = ?", t.ID).Not("start_time = null AND cancelled = true").Limit(limit).Find(&matches)
} else {
var owner UserData
SQLAccess.Gorm.First(&owner, t.UserID)
SQLAccess.Gorm.Where("user_id = ?", t.UserID).Find(&owner.Matches).Limit(limit)
SQLAccess.Gorm.Model(&owner).Related(&owner.Matches, "Matches").Limit(limit)
matches = owner.Matches
}
return matches
Expand Down Expand Up @@ -563,10 +560,8 @@ type MatchData struct {
Forfeit bool `gorm:"column:forfeit" json:"forfeit"`
PluginVersion string `gorm:"column:plugin_version" json:"-"`

MapStats []MapStatsData `json:"-"`
MapStats []MapStatsData `gorm:"ForeignKey:MatchID" json:"-"`
Server GameServerData `json:"-"`

User UserData `gorm:"ASSOCIATION_FOREIGNKEY:user_id" json:"-"`
}

// TableName declairation for GORM
Expand Down Expand Up @@ -788,11 +783,13 @@ func (m *MatchData) GetTeam2() (TeamData, error) {
return Team, nil
}

/*
// GetUser Get Match owner as "UserData" struct.
func (m *MatchData) GetUser() UserData {
SQLAccess.Gorm.First(&m.User, m.UserID)
return m.User
}
*/

// GetWinner Get Winner team as "TeamData" struct.
func (m *MatchData) GetWinner() (TeamData, error) {
Expand Down