40-counts.sql 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. -- Counts
  7. --
  8. -- Counts and sizes are maintained for each device, folder, type, flag bits
  9. -- combination.
  10. CREATE TABLE IF NOT EXISTS counts (
  11. folder_idx INTEGER NOT NULL,
  12. device_idx INTEGER NOT NULL,
  13. type INTEGER NOT NULL,
  14. local_flags INTEGER NOT NULL,
  15. count INTEGER NOT NULL,
  16. size INTEGER NOT NULL,
  17. deleted INTEGER NOT NULL, -- boolean
  18. PRIMARY KEY(folder_idx, device_idx, type, local_flags, deleted),
  19. FOREIGN KEY(device_idx) REFERENCES devices(idx) ON DELETE CASCADE,
  20. FOREIGN KEY(folder_idx) REFERENCES folders(idx) ON DELETE CASCADE
  21. ) STRICT, WITHOUT ROWID
  22. ;
  23. --- Maintain counts when files are added and removed using triggers
  24. CREATE TRIGGER IF NOT EXISTS counts_insert AFTER INSERT ON files
  25. BEGIN
  26. INSERT INTO counts (folder_idx, device_idx, type, local_flags, count, size, deleted)
  27. VALUES (NEW.folder_idx, NEW.device_idx, NEW.type, NEW.local_flags, 1, NEW.size, NEW.deleted)
  28. ON CONFLICT DO UPDATE SET count = count + 1, size = size + NEW.size;
  29. END
  30. ;
  31. CREATE TRIGGER IF NOT EXISTS counts_delete AFTER DELETE ON files
  32. BEGIN
  33. UPDATE counts SET count = count - 1, size = size - OLD.size
  34. WHERE folder_idx = OLD.folder_idx AND device_idx = OLD.device_idx AND type = OLD.type AND local_flags = OLD.local_flags AND deleted = OLD.deleted;
  35. END
  36. ;
  37. CREATE TRIGGER IF NOT EXISTS counts_update AFTER UPDATE OF local_flags ON files
  38. WHEN NEW.local_flags != OLD.local_flags
  39. BEGIN
  40. INSERT INTO counts (folder_idx, device_idx, type, local_flags, count, size, deleted)
  41. VALUES (NEW.folder_idx, NEW.device_idx, NEW.type, NEW.local_flags, 1, NEW.size, NEW.deleted)
  42. ON CONFLICT DO UPDATE SET count = count + 1, size = size + NEW.size;
  43. UPDATE counts SET count = count - 1, size = size - OLD.size
  44. WHERE folder_idx = OLD.folder_idx AND device_idx = OLD.device_idx AND type = OLD.type AND local_flags = OLD.local_flags AND deleted = OLD.deleted;
  45. END
  46. ;
  47. DROP TRIGGER IF EXISTS counts_update_add -- tmp migration
  48. ;
  49. DROP TRIGGER IF EXISTS counts_update_del -- tmp migration
  50. ;