4
0

storage.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/v2/internal/storage"
  4. import (
  5. "context"
  6. "database/sql"
  7. "time"
  8. )
  9. // Storage handles all operations related to the database.
  10. type Storage struct {
  11. db *sql.DB
  12. }
  13. // NewStorage returns a new Storage.
  14. func NewStorage(db *sql.DB) *Storage {
  15. return &Storage{db}
  16. }
  17. // DatabaseVersion returns the version of the database which is in use.
  18. func (s *Storage) DatabaseVersion() string {
  19. var dbVersion string
  20. err := s.db.QueryRow(`SELECT current_setting('server_version')`).Scan(&dbVersion)
  21. if err != nil {
  22. return err.Error()
  23. }
  24. return dbVersion
  25. }
  26. // Ping checks if the database connection works.
  27. func (s *Storage) Ping() error {
  28. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  29. defer cancel()
  30. return s.db.PingContext(ctx)
  31. }
  32. // DBStats returns database statistics.
  33. func (s *Storage) DBStats() sql.DBStats {
  34. return s.db.Stats()
  35. }
  36. // DBSize returns how much size the database is using in a pretty way.
  37. func (s *Storage) DBSize() (string, error) {
  38. var size string
  39. err := s.db.QueryRow("SELECT pg_size_pretty(pg_database_size(current_database()))").Scan(&size)
  40. if err != nil {
  41. return "", err
  42. }
  43. return size, nil
  44. }