Improved database model migration and added indexing (#2655)

This commit is contained in:
Zahar Izmailov 2025-02-03 15:36:03 +03:00 committed by GitHub
parent 8a7cffd63f
commit b922d986d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 28 additions and 13 deletions

View File

@ -26,20 +26,35 @@ const (
)
func initModels() error {
models := []interface{}{
// Order matters: first create tables without dependencies
baseModels := []interface{}{
&model.User{},
&model.Inbound{},
&model.OutboundTraffics{},
&model.Setting{},
&model.InboundClientIps{},
&xray.ClientTraffic{},
}
for _, model := range models {
// Migrate base models
for _, model := range baseModels {
if err := db.AutoMigrate(model); err != nil {
log.Printf("Error auto migrating model: %v", err)
log.Printf("Error auto migrating base model: %v", err)
return err
}
}
// Then migrate models with dependencies
dependentModels := []interface{}{
&model.Inbound{},
&model.OutboundTraffics{},
&model.InboundClientIps{},
&xray.ClientTraffic{},
}
for _, model := range dependentModels {
if err := db.AutoMigrate(model); err != nil {
log.Printf("Error auto migrating dependent model: %v", err)
return err
}
}
return nil
}

View File

@ -29,14 +29,14 @@ type User struct {
type Inbound struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
UserId int `json:"-"`
UserId int `json:"-" gorm:"index"`
Up int64 `json:"up" form:"up"`
Down int64 `json:"down" form:"down"`
Total int64 `json:"total" form:"total"`
Remark string `json:"remark" form:"remark"`
Enable bool `json:"enable" form:"enable"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`
ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"`
ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id;constraint:OnDelete:CASCADE" json:"clientStats"`
// config part
Listen string `json:"listen" form:"listen"`

View File

@ -283,4 +283,4 @@ install_x-ui() {
echo -e "${green}Running...${plain}"
install_base
install_x-ui $1
install_x-ui $1

View File

@ -1912,4 +1912,4 @@ if [[ $# > 0 ]]; then
esac
else
show_menu
fi
fi

View File

@ -2,9 +2,9 @@ package xray
type ClientTraffic struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
InboundId int `json:"inboundId" form:"inboundId"`
InboundId int `json:"inboundId" form:"inboundId" gorm:"index;not null"`
Enable bool `json:"enable" form:"enable"`
Email string `json:"email" form:"email" gorm:"unique"`
Email string `json:"email" form:"email" gorm:"uniqueIndex"`
Up int64 `json:"up" form:"up"`
Down int64 `json:"down" form:"down"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`