40-counts.sql 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. device_idx INTEGER NOT NULL,
  12. type INTEGER NOT NULL,
  13. local_flags INTEGER NOT NULL,
  14. deleted INTEGER NOT NULL, -- boolean
  15. count INTEGER NOT NULL,
  16. size INTEGER NOT NULL,
  17. PRIMARY KEY(device_idx, type, local_flags, deleted),
  18. FOREIGN KEY(device_idx) REFERENCES devices(idx) ON DELETE CASCADE
  19. ) STRICT, WITHOUT ROWID
  20. ;
  21. --- Maintain counts when files are added and removed using triggers
  22. CREATE TRIGGER IF NOT EXISTS counts_insert AFTER INSERT ON files
  23. BEGIN
  24. INSERT INTO counts (device_idx, type, local_flags, deleted, count, size)
  25. VALUES (NEW.device_idx, NEW.type, NEW.local_flags, NEW.deleted, 1, NEW.size)
  26. ON CONFLICT DO UPDATE SET count = count + 1, size = size + NEW.size;
  27. END
  28. ;
  29. CREATE TRIGGER IF NOT EXISTS counts_delete AFTER DELETE ON files
  30. BEGIN
  31. UPDATE counts SET count = count - 1, size = size - OLD.size
  32. WHERE device_idx = OLD.device_idx AND type = OLD.type AND local_flags = OLD.local_flags AND deleted = OLD.deleted;
  33. END
  34. ;
  35. CREATE TRIGGER IF NOT EXISTS counts_update AFTER UPDATE OF local_flags ON files
  36. WHEN NEW.local_flags != OLD.local_flags
  37. BEGIN
  38. INSERT INTO counts (device_idx, type, local_flags, deleted, count, size)
  39. VALUES (NEW.device_idx, NEW.type, NEW.local_flags, NEW.deleted, 1, NEW.size)
  40. ON CONFLICT DO UPDATE SET count = count + 1, size = size + NEW.size;
  41. UPDATE counts SET count = count - 1, size = size - OLD.size
  42. WHERE device_idx = OLD.device_idx AND type = OLD.type AND local_flags = OLD.local_flags AND deleted = OLD.deleted;
  43. END
  44. ;