Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/MHSanaei/3x-ui.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'database/db.go')
-rw-r--r--database/db.go11
1 files changed, 11 insertions, 0 deletions
diff --git a/database/db.go b/database/db.go
index 8414b118..6de81d79 100644
--- a/database/db.go
+++ b/database/db.go
@@ -1,3 +1,5 @@
+// Package database provides database initialization, migration, and management utilities
+// for the 3x-ui panel using GORM with SQLite.
package database
import (
@@ -45,6 +47,7 @@ func initModels() error {
return nil
}
+// initUser creates a default admin user if the users table is empty.
func initUser() error {
empty, err := isTableEmpty("users")
if err != nil {
@@ -68,6 +71,7 @@ func initUser() error {
return nil
}
+// runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
func runSeeders(isUsersEmpty bool) error {
empty, err := isTableEmpty("history_of_seeders")
if err != nil {
@@ -107,12 +111,14 @@ func runSeeders(isUsersEmpty bool) error {
return nil
}
+// isTableEmpty returns true if the named table contains zero rows.
func isTableEmpty(tableName string) (bool, error) {
var count int64
err := db.Table(tableName).Count(&count).Error
return count == 0, err
}
+// InitDB sets up the database connection, migrates models, and runs seeders.
func InitDB(dbPath string) error {
dir := path.Dir(dbPath)
err := os.MkdirAll(dir, fs.ModePerm)
@@ -151,6 +157,7 @@ func InitDB(dbPath string) error {
return runSeeders(isUsersEmpty)
}
+// CloseDB closes the database connection if it exists.
func CloseDB() error {
if db != nil {
sqlDB, err := db.DB()
@@ -162,14 +169,17 @@ func CloseDB() error {
return nil
}
+// GetDB returns the global GORM database instance.
func GetDB() *gorm.DB {
return db
}
+// IsNotFound checks if the given error is a GORM record not found error.
func IsNotFound(err error) bool {
return err == gorm.ErrRecordNotFound
}
+// IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
func IsSQLiteDB(file io.ReaderAt) (bool, error) {
signature := []byte("SQLite format 3\x00")
buf := make([]byte, len(signature))
@@ -180,6 +190,7 @@ func IsSQLiteDB(file io.ReaderAt) (bool, error) {
return bytes.Equal(buf, signature), nil
}
+// Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
func Checkpoint() error {
// Update WAL
err := db.Exec("PRAGMA wal_checkpoint;").Error