db_stats.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package sqlite
  7. type DatabaseStatistics struct {
  8. Name string `json:"name"`
  9. FolderID string `json:"folderID,omitempty"`
  10. Tables []TableStatistics `json:"tables"`
  11. Total TableStatistics `json:"total"`
  12. Children []DatabaseStatistics `json:"children,omitempty"`
  13. }
  14. type TableStatistics struct {
  15. Name string `json:"name,omitempty"`
  16. Size int64 `json:"size"`
  17. Unused int64 `json:"unused"`
  18. }
  19. func (s *DB) Statistics() (*DatabaseStatistics, error) {
  20. ts, total, err := s.tableStats()
  21. if err != nil {
  22. return nil, wrap(err)
  23. }
  24. ds := DatabaseStatistics{
  25. Name: s.baseName,
  26. Tables: ts,
  27. Total: total,
  28. }
  29. err = s.forEachFolder(func(fdb *folderDB) error {
  30. tables, total, err := fdb.tableStats()
  31. if err != nil {
  32. return wrap(err)
  33. }
  34. ds.Children = append(ds.Children, DatabaseStatistics{
  35. Name: fdb.baseName,
  36. FolderID: fdb.folderID,
  37. Tables: tables,
  38. Total: total,
  39. })
  40. return nil
  41. })
  42. if err != nil {
  43. return nil, wrap(err)
  44. }
  45. return &ds, nil
  46. }
  47. func (s *baseDB) tableStats() ([]TableStatistics, TableStatistics, error) {
  48. var stats []TableStatistics
  49. if err := s.stmt(`
  50. SELECT name, pgsize AS size, unused FROM dbstat
  51. WHERE aggregate=true
  52. ORDER BY name
  53. `).Select(&stats); err != nil {
  54. return nil, TableStatistics{}, wrap(err)
  55. }
  56. var total TableStatistics
  57. for _, s := range stats {
  58. total.Size += s.Size
  59. total.Unused += s.Unused
  60. }
  61. return stats, total, nil
  62. }