gitea源码

db.go 1.4KB

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