Browse Source

add MigrateDB func for a single source of truth

Hamidreza Ghavami 1 year ago
parent
commit
26f160fb89
3 changed files with 14 additions and 6 deletions
  1. 3 3
      main.go
  2. 10 1
      web/service/inbound.go
  3. 1 2
      web/service/server.go

+ 3 - 3
main.go

@@ -2,7 +2,6 @@ package main
 
 import (
 	"fmt"
-	"github.com/spf13/cobra"
 	"log"
 	"os"
 	"os/signal"
@@ -16,6 +15,8 @@ import (
 	"x-ui/web/global"
 	"x-ui/web/service"
 
+	"github.com/spf13/cobra"
+
 	"github.com/op/go-logging"
 )
 
@@ -215,8 +216,7 @@ func migrateDb() {
 		log.Fatal(err)
 	}
 	fmt.Println("Start migrating database...")
-	inboundService.MigrationRequirements()
-	inboundService.RemoveOrphanedTraffics()
+	inboundService.MigrateDB()
 	fmt.Println("Migration done!")
 }
 

+ 10 - 1
web/service/inbound.go

@@ -595,6 +595,7 @@ func (s *InboundService) DisableInvalidInbounds() (int64, error) {
 	count := result.RowsAffected
 	return count, err
 }
+
 func (s *InboundService) DisableInvalidClients() (int64, error) {
 	db := database.GetDB()
 	now := time.Now().Unix() * 1000
@@ -605,7 +606,8 @@ func (s *InboundService) DisableInvalidClients() (int64, error) {
 	count := result.RowsAffected
 	return count, err
 }
-func (s *InboundService) RemoveOrphanedTraffics() {
+
+func (s *InboundService) MigrationRemoveOrphanedTraffics() {
 	db := database.GetDB()
 	db.Exec(`
 		DELETE FROM client_traffics
@@ -616,6 +618,7 @@ func (s *InboundService) RemoveOrphanedTraffics() {
 		)
 	`)
 }
+
 func (s *InboundService) AddClientStat(inboundId int, client *model.Client) error {
 	db := database.GetDB()
 
@@ -634,6 +637,7 @@ func (s *InboundService) AddClientStat(inboundId int, client *model.Client) erro
 	}
 	return nil
 }
+
 func (s *InboundService) UpdateClientStat(email string, client *model.Client) error {
 	db := database.GetDB()
 
@@ -1055,3 +1059,8 @@ func (s *InboundService) MigrationRequirements() {
 	// Remove orphaned traffics
 	db.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
 }
+
+func (s *InboundService) MigrateDB() {
+	s.MigrationRequirements()
+	s.MigrationRemoveOrphanedTraffics()
+}

+ 1 - 2
web/service/server.go

@@ -469,8 +469,7 @@ func (s *ServerService) ImportDB(file multipart.File) error {
 		defer os.Rename(fallbackPath, config.GetDBPath())
 		return common.NewErrorf("Error migrating db: %v", err)
 	}
-	s.inboundService.MigrationRequirements()
-	s.inboundService.RemoveOrphanedTraffics()
+	s.inboundService.MigrateDB()
 
 	// remove fallback file
 	defer os.Remove(fallbackPath)