db_update.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. import (
  8. "fmt"
  9. "os"
  10. "runtime"
  11. "strings"
  12. )
  13. func (s *DB) DropFolder(folder string) error {
  14. s.folderDBsMut.Lock()
  15. defer s.folderDBsMut.Unlock()
  16. s.updateLock.Lock()
  17. defer s.updateLock.Unlock()
  18. _, err := s.stmt(`
  19. DELETE FROM folders
  20. WHERE folder_id = ?
  21. `).Exec(folder)
  22. if fdb, ok := s.folderDBs[folder]; ok {
  23. fdb.Close()
  24. _ = os.Remove(fdb.path)
  25. _ = os.Remove(fdb.path + "-wal")
  26. _ = os.Remove(fdb.path + "-shm")
  27. delete(s.folderDBs, folder)
  28. }
  29. return wrap(err)
  30. }
  31. func (s *DB) ListFolders() ([]string, error) {
  32. var res []string
  33. err := s.stmt(`
  34. SELECT folder_id FROM folders
  35. ORDER BY folder_id
  36. `).Select(&res)
  37. return res, wrap(err)
  38. }
  39. // wrap returns the error wrapped with the calling function name and
  40. // optional extra context strings as prefix. A nil error wraps to nil.
  41. func wrap(err error, context ...string) error {
  42. if err == nil {
  43. return nil
  44. }
  45. prefix := "error"
  46. pc, _, _, ok := runtime.Caller(1)
  47. details := runtime.FuncForPC(pc)
  48. if ok && details != nil {
  49. prefix = strings.ToLower(details.Name())
  50. if dotIdx := strings.LastIndex(prefix, "."); dotIdx > 0 {
  51. prefix = prefix[dotIdx+1:]
  52. }
  53. }
  54. if len(context) > 0 {
  55. for i := range context {
  56. context[i] = strings.TrimSpace(context[i])
  57. }
  58. extra := strings.Join(context, ", ")
  59. return fmt.Errorf("%s (%s): %w", prefix, extra, err)
  60. }
  61. return fmt.Errorf("%s: %w", prefix, err)
  62. }