embeddedpg.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package embeddedpg
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "github.com/cockroachdb/errors"
  8. embpg "github.com/fergusstrange/embedded-postgres"
  9. log "unknwon.dev/clog/v2"
  10. "gogs.io/gogs/internal/conf"
  11. )
  12. // LocalPostgres wraps embedded PostgreSQL server functionality.
  13. type LocalPostgres struct {
  14. srv *embpg.EmbeddedPostgres
  15. baseDir string
  16. tcpPort uint32
  17. database string
  18. user string
  19. pass string
  20. }
  21. // Initialize creates a LocalPostgres with default settings based on workDir.
  22. func Initialize(workDir string) *LocalPostgres {
  23. storageBase := filepath.Join(workDir, "data", "local-postgres")
  24. return &LocalPostgres{
  25. baseDir: storageBase,
  26. tcpPort: 15432,
  27. database: "gogs",
  28. user: "gogs",
  29. pass: "gogs",
  30. }
  31. }
  32. // Launch starts the embedded PostgreSQL server and blocks until ready.
  33. func (pg *LocalPostgres) Launch() error {
  34. log.Info("Launching local PostgreSQL server...")
  35. if err := os.MkdirAll(pg.baseDir, 0o700); err != nil {
  36. return errors.Wrap(err, "mkdir local postgres base")
  37. }
  38. opts := embpg.DefaultConfig().
  39. Username(pg.user).
  40. Password(pg.pass).
  41. Database(pg.database).
  42. Port(pg.tcpPort).
  43. DataPath(pg.baseDir).
  44. RuntimePath(filepath.Join(pg.baseDir, "rt")).
  45. BinariesPath(filepath.Join(pg.baseDir, "bin")).
  46. CachePath(filepath.Join(pg.baseDir, "dl")).
  47. StartTimeout(45 * time.Second).
  48. Logger(os.Stderr)
  49. pg.srv = embpg.NewDatabase(opts)
  50. if err := pg.srv.Start(); err != nil {
  51. return errors.Wrap(err, "launch embedded pg")
  52. }
  53. log.Info("Local PostgreSQL ready on port %d", pg.tcpPort)
  54. return nil
  55. }
  56. // Shutdown stops the embedded PostgreSQL server gracefully.
  57. func (pg *LocalPostgres) Shutdown() error {
  58. if pg.srv == nil {
  59. return nil
  60. }
  61. log.Info("Shutting down local PostgreSQL...")
  62. if err := pg.srv.Stop(); err != nil {
  63. return errors.Wrap(err, "shutdown embedded pg")
  64. }
  65. log.Info("Local PostgreSQL shutdown complete")
  66. return nil
  67. }
  68. // ConfigureGlobalDatabase modifies global conf.Database to point to this instance.
  69. func (pg *LocalPostgres) ConfigureGlobalDatabase() {
  70. conf.Database.Type = "postgres"
  71. conf.Database.Host = fmt.Sprintf("localhost:%d", pg.tcpPort)
  72. conf.Database.Name = pg.database
  73. conf.Database.User = pg.user
  74. conf.Database.Password = pg.pass
  75. conf.Database.SSLMode = "disable"
  76. log.Trace("Global database configured for local PostgreSQL")
  77. }