code.gitea.io/gitea@v1.21.7/models/db/install/db.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package install
     5  
     6  import (
     7  	"code.gitea.io/gitea/models/db"
     8  	"code.gitea.io/gitea/modules/setting"
     9  
    10  	"xorm.io/xorm"
    11  )
    12  
    13  func getXORMEngine() *xorm.Engine {
    14  	return db.DefaultContext.(*db.Context).Engine().(*xorm.Engine)
    15  }
    16  
    17  // CheckDatabaseConnection checks the database connection
    18  func CheckDatabaseConnection() error {
    19  	e := db.GetEngine(db.DefaultContext)
    20  	_, err := e.Exec("SELECT 1")
    21  	return err
    22  }
    23  
    24  // GetMigrationVersion gets the database migration version
    25  func GetMigrationVersion() (int64, error) {
    26  	var installedDbVersion int64
    27  	x := getXORMEngine()
    28  	exist, err := x.IsTableExist("version")
    29  	if err != nil {
    30  		return 0, err
    31  	}
    32  	if !exist {
    33  		return 0, nil
    34  	}
    35  	_, err = x.Table("version").Cols("version").Get(&installedDbVersion)
    36  	if err != nil {
    37  		return 0, err
    38  	}
    39  	return installedDbVersion, nil
    40  }
    41  
    42  // HasPostInstallationUsers checks whether there are users after installation
    43  func HasPostInstallationUsers() (bool, error) {
    44  	x := getXORMEngine()
    45  	exist, err := x.IsTableExist("user")
    46  	if err != nil {
    47  		return false, err
    48  	}
    49  	if !exist {
    50  		return false, nil
    51  	}
    52  
    53  	// if there are 2 or more users in database, we consider there are users created after installation
    54  	threshold := 2
    55  	if !setting.IsProd {
    56  		// to debug easily, with non-prod RUN_MODE, we only check the count to 1
    57  		threshold = 1
    58  	}
    59  	res, err := x.Table("user").Cols("id").Limit(threshold).Query()
    60  	if err != nil {
    61  		return false, err
    62  	}
    63  	return len(res) >= threshold, nil
    64  }