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.6KB

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