You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.go 1.5KB

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