db_update.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. "cmp"
  9. "context"
  10. "fmt"
  11. "runtime"
  12. "slices"
  13. "strings"
  14. "github.com/jmoiron/sqlx"
  15. "github.com/syncthing/syncthing/internal/gen/dbproto"
  16. "github.com/syncthing/syncthing/internal/itererr"
  17. "github.com/syncthing/syncthing/lib/osutil"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/sliceutil"
  20. "google.golang.org/protobuf/proto"
  21. )
  22. func (s *DB) Update(folder string, device protocol.DeviceID, fs []protocol.FileInfo) error {
  23. s.updateLock.Lock()
  24. defer s.updateLock.Unlock()
  25. folderIdx, err := s.folderIdxLocked(folder)
  26. if err != nil {
  27. return wrap(err)
  28. }
  29. deviceIdx, err := s.deviceIdxLocked(device)
  30. if err != nil {
  31. return wrap(err)
  32. }
  33. tx, err := s.sql.BeginTxx(context.Background(), nil)
  34. if err != nil {
  35. return wrap(err)
  36. }
  37. defer tx.Rollback() //nolint:errcheck
  38. txp := &txPreparedStmts{Tx: tx}
  39. //nolint:sqlclosecheck
  40. insertFileStmt, err := txp.Preparex(`
  41. INSERT OR REPLACE INTO files (folder_idx, device_idx, remote_sequence, name, type, modified, size, version, deleted, invalid, local_flags, blocklist_hash)
  42. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  43. RETURNING sequence
  44. `)
  45. if err != nil {
  46. return wrap(err, "prepare insert file")
  47. }
  48. //nolint:sqlclosecheck
  49. insertFileInfoStmt, err := txp.Preparex(`
  50. INSERT INTO fileinfos (sequence, fiprotobuf)
  51. VALUES (?, ?)
  52. `)
  53. if err != nil {
  54. return wrap(err, "prepare insert fileinfo")
  55. }
  56. //nolint:sqlclosecheck
  57. insertBlockListStmt, err := txp.Preparex(`
  58. INSERT OR IGNORE INTO blocklists (blocklist_hash, blprotobuf)
  59. VALUES (?, ?)
  60. `)
  61. if err != nil {
  62. return wrap(err, "prepare insert blocklist")
  63. }
  64. var prevRemoteSeq int64
  65. for i, f := range fs {
  66. f.Name = osutil.NormalizedFilename(f.Name)
  67. var blockshash *[]byte
  68. if len(f.Blocks) > 0 {
  69. f.BlocksHash = protocol.BlocksHash(f.Blocks)
  70. blockshash = &f.BlocksHash
  71. } else {
  72. f.BlocksHash = nil
  73. }
  74. if f.Type == protocol.FileInfoTypeDirectory {
  75. f.Size = 128 // synthetic directory size
  76. }
  77. // Insert the file.
  78. //
  79. // If it is a remote file, set remote_sequence otherwise leave it at
  80. // null. Returns the new local sequence.
  81. var remoteSeq *int64
  82. if device != protocol.LocalDeviceID {
  83. if i > 0 && f.Sequence == prevRemoteSeq {
  84. return fmt.Errorf("duplicate remote sequence number %d", prevRemoteSeq)
  85. }
  86. prevRemoteSeq = f.Sequence
  87. remoteSeq = &f.Sequence
  88. }
  89. var localSeq int64
  90. if err := insertFileStmt.Get(&localSeq, folderIdx, deviceIdx, remoteSeq, f.Name, f.Type, f.ModTime().UnixNano(), f.Size, f.Version.String(), f.IsDeleted(), f.IsInvalid(), f.LocalFlags, blockshash); err != nil {
  91. return wrap(err, "insert file")
  92. }
  93. if len(f.Blocks) > 0 {
  94. // Indirect the block list
  95. blocks := sliceutil.Map(f.Blocks, protocol.BlockInfo.ToWire)
  96. bs, err := proto.Marshal(&dbproto.BlockList{Blocks: blocks})
  97. if err != nil {
  98. return wrap(err, "marshal blocklist")
  99. }
  100. if _, err := insertBlockListStmt.Exec(f.BlocksHash, bs); err != nil {
  101. return wrap(err, "insert blocklist")
  102. }
  103. if device == protocol.LocalDeviceID {
  104. // Insert all blocks
  105. if err := s.insertBlocksLocked(txp, f.BlocksHash, f.Blocks); err != nil {
  106. return wrap(err, "insert blocks")
  107. }
  108. }
  109. f.Blocks = nil
  110. }
  111. // Insert the fileinfo
  112. if device == protocol.LocalDeviceID {
  113. f.Sequence = localSeq
  114. }
  115. bs, err := proto.Marshal(f.ToWire(true))
  116. if err != nil {
  117. return wrap(err, "marshal fileinfo")
  118. }
  119. if _, err := insertFileInfoStmt.Exec(localSeq, bs); err != nil {
  120. return wrap(err, "insert fileinfo")
  121. }
  122. // Update global and need
  123. if err := s.recalcGlobalForFile(txp, folderIdx, f.Name); err != nil {
  124. return wrap(err)
  125. }
  126. }
  127. return wrap(tx.Commit())
  128. }
  129. func (s *DB) DropFolder(folder string) error {
  130. s.updateLock.Lock()
  131. defer s.updateLock.Unlock()
  132. _, err := s.stmt(`
  133. DELETE FROM folders
  134. WHERE folder_id = ?
  135. `).Exec(folder)
  136. return wrap(err)
  137. }
  138. func (s *DB) DropDevice(device protocol.DeviceID) error {
  139. if device == protocol.LocalDeviceID {
  140. panic("bug: cannot drop local device")
  141. }
  142. s.updateLock.Lock()
  143. defer s.updateLock.Unlock()
  144. deviceIdx, err := s.deviceIdxLocked(device)
  145. if err != nil {
  146. return wrap(err)
  147. }
  148. tx, err := s.sql.BeginTxx(context.Background(), nil)
  149. if err != nil {
  150. return wrap(err)
  151. }
  152. defer tx.Rollback() //nolint:errcheck
  153. txp := &txPreparedStmts{Tx: tx}
  154. // Find all folders where the device is involved
  155. var folderIdxs []int64
  156. if err := tx.Select(&folderIdxs, `
  157. SELECT folder_idx
  158. FROM counts
  159. WHERE device_idx = ? AND count > 0
  160. GROUP BY folder_idx
  161. `, deviceIdx); err != nil {
  162. return wrap(err)
  163. }
  164. // Drop the device, which cascades to delete all files etc for it
  165. if _, err := tx.Exec(`DELETE FROM devices WHERE device_id = ?`, device.String()); err != nil {
  166. return wrap(err)
  167. }
  168. // Recalc the globals for all affected folders
  169. for _, idx := range folderIdxs {
  170. if err := s.recalcGlobalForFolder(txp, idx); err != nil {
  171. return wrap(err)
  172. }
  173. }
  174. return wrap(tx.Commit())
  175. }
  176. func (s *DB) DropAllFiles(folder string, device protocol.DeviceID) error {
  177. s.updateLock.Lock()
  178. defer s.updateLock.Unlock()
  179. // This is a two part operation, first dropping all the files and then
  180. // recalculating the global state for the entire folder.
  181. folderIdx, err := s.folderIdxLocked(folder)
  182. if err != nil {
  183. return wrap(err)
  184. }
  185. deviceIdx, err := s.deviceIdxLocked(device)
  186. if err != nil {
  187. return wrap(err)
  188. }
  189. tx, err := s.sql.BeginTxx(context.Background(), nil)
  190. if err != nil {
  191. return wrap(err)
  192. }
  193. defer tx.Rollback() //nolint:errcheck
  194. txp := &txPreparedStmts{Tx: tx}
  195. // Drop all the file entries
  196. result, err := tx.Exec(`
  197. DELETE FROM files
  198. WHERE folder_idx = ? AND device_idx = ?
  199. `, folderIdx, deviceIdx)
  200. if err != nil {
  201. return wrap(err)
  202. }
  203. if n, err := result.RowsAffected(); err == nil && n == 0 {
  204. // The delete affected no rows, so we don't need to redo the entire
  205. // global/need calculation.
  206. return wrap(tx.Commit())
  207. }
  208. // Recalc global for the entire folder
  209. if err := s.recalcGlobalForFolder(txp, folderIdx); err != nil {
  210. return wrap(err)
  211. }
  212. return wrap(tx.Commit())
  213. }
  214. func (s *DB) DropFilesNamed(folder string, device protocol.DeviceID, names []string) error {
  215. for i := range names {
  216. names[i] = osutil.NormalizedFilename(names[i])
  217. }
  218. s.updateLock.Lock()
  219. defer s.updateLock.Unlock()
  220. folderIdx, err := s.folderIdxLocked(folder)
  221. if err != nil {
  222. return wrap(err)
  223. }
  224. deviceIdx, err := s.deviceIdxLocked(device)
  225. if err != nil {
  226. return wrap(err)
  227. }
  228. tx, err := s.sql.BeginTxx(context.Background(), nil)
  229. if err != nil {
  230. return wrap(err)
  231. }
  232. defer tx.Rollback() //nolint:errcheck
  233. txp := &txPreparedStmts{Tx: tx}
  234. // Drop the named files
  235. query, args, err := sqlx.In(`
  236. DELETE FROM files
  237. WHERE folder_idx = ? AND device_idx = ? AND name IN (?)
  238. `, folderIdx, deviceIdx, names)
  239. if err != nil {
  240. return wrap(err)
  241. }
  242. if _, err := tx.Exec(query, args...); err != nil {
  243. return wrap(err)
  244. }
  245. // Recalc globals for the named files
  246. for _, name := range names {
  247. if err := s.recalcGlobalForFile(txp, folderIdx, name); err != nil {
  248. return wrap(err)
  249. }
  250. }
  251. return wrap(tx.Commit())
  252. }
  253. func (*DB) insertBlocksLocked(tx *txPreparedStmts, blocklistHash []byte, blocks []protocol.BlockInfo) error {
  254. if len(blocks) == 0 {
  255. return nil
  256. }
  257. bs := make([]map[string]any, len(blocks))
  258. for i, b := range blocks {
  259. bs[i] = map[string]any{
  260. "hash": b.Hash,
  261. "blocklist_hash": blocklistHash,
  262. "idx": i,
  263. "offset": b.Offset,
  264. "size": b.Size,
  265. }
  266. }
  267. _, err := tx.NamedExec(`
  268. INSERT OR IGNORE INTO blocks (hash, blocklist_hash, idx, offset, size)
  269. VALUES (:hash, :blocklist_hash, :idx, :offset, :size)
  270. `, bs)
  271. return wrap(err)
  272. }
  273. func (s *DB) recalcGlobalForFolder(txp *txPreparedStmts, folderIdx int64) error {
  274. // Select files where there is no global, those are the ones we need to
  275. // recalculate.
  276. //nolint:sqlclosecheck
  277. namesStmt, err := txp.Preparex(`
  278. SELECT f.name FROM files f
  279. WHERE f.folder_idx = ? AND NOT EXISTS (
  280. SELECT 1 FROM files g
  281. WHERE g.folder_idx = ? AND g.name = f.name AND g.local_flags & ? != 0
  282. )
  283. GROUP BY name
  284. `)
  285. if err != nil {
  286. return wrap(err)
  287. }
  288. rows, err := namesStmt.Queryx(folderIdx, folderIdx, protocol.FlagLocalGlobal)
  289. if err != nil {
  290. return wrap(err)
  291. }
  292. defer rows.Close()
  293. for rows.Next() {
  294. var name string
  295. if err := rows.Scan(&name); err != nil {
  296. return wrap(err)
  297. }
  298. if err := s.recalcGlobalForFile(txp, folderIdx, name); err != nil {
  299. return wrap(err)
  300. }
  301. }
  302. return wrap(rows.Err())
  303. }
  304. func (s *DB) recalcGlobalForFile(txp *txPreparedStmts, folderIdx int64, file string) error {
  305. //nolint:sqlclosecheck
  306. selStmt, err := txp.Preparex(`
  307. SELECT name, folder_idx, device_idx, sequence, modified, version, deleted, invalid, local_flags FROM files
  308. WHERE folder_idx = ? AND name = ?
  309. `)
  310. if err != nil {
  311. return wrap(err)
  312. }
  313. es, err := itererr.Collect(iterStructs[fileRow](selStmt.Queryx(folderIdx, file)))
  314. if err != nil {
  315. return wrap(err)
  316. }
  317. if len(es) == 0 {
  318. // shouldn't happen
  319. return nil
  320. }
  321. // Sort the entries; the global entry is at the head of the list
  322. slices.SortFunc(es, fileRow.Compare)
  323. // The global version is the first one in the list that is not invalid,
  324. // or just the first one in the list if all are invalid.
  325. var global fileRow
  326. globIdx := slices.IndexFunc(es, func(e fileRow) bool { return !e.Invalid })
  327. if globIdx < 0 {
  328. globIdx = 0
  329. }
  330. global = es[globIdx]
  331. // We "have" the file if the position in the list of versions is at the
  332. // global version or better, or if the version is the same as the global
  333. // file (we might be further down the list due to invalid flags), or if
  334. // the global is deleted and we don't have it at all...
  335. localIdx := slices.IndexFunc(es, func(e fileRow) bool { return e.DeviceIdx == s.localDeviceIdx })
  336. hasLocal := localIdx >= 0 && localIdx <= globIdx || // have a better or equal version
  337. localIdx >= 0 && es[localIdx].Version.Equal(global.Version.Vector) || // have an equal version but invalid/ignored
  338. localIdx < 0 && global.Deleted // missing it, but the global is also deleted
  339. // Set the global flag on the global entry. Set the need flag if the
  340. // local device needs this file, unless it's invalid.
  341. global.LocalFlags |= protocol.FlagLocalGlobal
  342. if hasLocal || global.Invalid {
  343. global.LocalFlags &= ^protocol.FlagLocalNeeded
  344. } else {
  345. global.LocalFlags |= protocol.FlagLocalNeeded
  346. }
  347. //nolint:sqlclosecheck
  348. upStmt, err := txp.Prepare(`
  349. UPDATE files SET local_flags = ?
  350. WHERE folder_idx = ? AND device_idx = ? AND sequence = ?
  351. `)
  352. if err != nil {
  353. return wrap(err)
  354. }
  355. if _, err := upStmt.Exec(global.LocalFlags, global.FolderIdx, global.DeviceIdx, global.Sequence); err != nil {
  356. return wrap(err)
  357. }
  358. // Clear the need and global flags on all other entries
  359. //nolint:sqlclosecheck
  360. upStmt, err = txp.Prepare(`
  361. UPDATE files SET local_flags = local_flags & ?
  362. WHERE folder_idx = ? AND name = ? AND sequence != ? AND local_flags & ? != 0
  363. `)
  364. if err != nil {
  365. return wrap(err)
  366. }
  367. if _, err := upStmt.Exec(^(protocol.FlagLocalNeeded | protocol.FlagLocalGlobal), folderIdx, global.Name, global.Sequence, protocol.FlagLocalNeeded|protocol.FlagLocalGlobal); err != nil {
  368. return wrap(err)
  369. }
  370. return nil
  371. }
  372. func (s *DB) folderIdxLocked(folderID string) (int64, error) {
  373. if _, err := s.stmt(`
  374. INSERT OR IGNORE INTO folders(folder_id)
  375. VALUES (?)
  376. `).Exec(folderID); err != nil {
  377. return 0, wrap(err)
  378. }
  379. var idx int64
  380. if err := s.stmt(`
  381. SELECT idx FROM folders
  382. WHERE folder_id = ?
  383. `).Get(&idx, folderID); err != nil {
  384. return 0, wrap(err)
  385. }
  386. return idx, nil
  387. }
  388. func (s *DB) deviceIdxLocked(deviceID protocol.DeviceID) (int64, error) {
  389. devStr := deviceID.String()
  390. if _, err := s.stmt(`
  391. INSERT OR IGNORE INTO devices(device_id)
  392. VALUES (?)
  393. `).Exec(devStr); err != nil {
  394. return 0, wrap(err)
  395. }
  396. var idx int64
  397. if err := s.stmt(`
  398. SELECT idx FROM devices
  399. WHERE device_id = ?
  400. `).Get(&idx, devStr); err != nil {
  401. return 0, wrap(err)
  402. }
  403. return idx, nil
  404. }
  405. // wrap returns the error wrapped with the calling function name and
  406. // optional extra context strings as prefix. A nil error wraps to nil.
  407. func wrap(err error, context ...string) error {
  408. if err == nil {
  409. return nil
  410. }
  411. prefix := "error"
  412. pc, _, _, ok := runtime.Caller(1)
  413. details := runtime.FuncForPC(pc)
  414. if ok && details != nil {
  415. prefix = strings.ToLower(details.Name())
  416. if dotIdx := strings.LastIndex(prefix, "."); dotIdx > 0 {
  417. prefix = prefix[dotIdx+1:]
  418. }
  419. }
  420. if len(context) > 0 {
  421. for i := range context {
  422. context[i] = strings.TrimSpace(context[i])
  423. }
  424. extra := strings.Join(context, ", ")
  425. return fmt.Errorf("%s (%s): %w", prefix, extra, err)
  426. }
  427. return fmt.Errorf("%s: %w", prefix, err)
  428. }
  429. type fileRow struct {
  430. Name string
  431. Version dbVector
  432. FolderIdx int64 `db:"folder_idx"`
  433. DeviceIdx int64 `db:"device_idx"`
  434. Sequence int64
  435. Modified int64
  436. Size int64
  437. LocalFlags int64 `db:"local_flags"`
  438. Deleted bool
  439. Invalid bool
  440. }
  441. func (e fileRow) Compare(other fileRow) int {
  442. // From FileInfo.WinsConflict
  443. vc := e.Version.Vector.Compare(other.Version.Vector)
  444. switch vc {
  445. case protocol.Equal:
  446. if e.Invalid != other.Invalid {
  447. if e.Invalid {
  448. return 1
  449. }
  450. return -1
  451. }
  452. // Compare the device ID index, lower is better. This is only
  453. // deterministic to the extent that LocalDeviceID will always be the
  454. // lowest one, order between remote devices is random (and
  455. // irrelevant).
  456. return cmp.Compare(e.DeviceIdx, other.DeviceIdx)
  457. case protocol.Greater: // we are newer
  458. return -1
  459. case protocol.Lesser: // we are older
  460. return 1
  461. case protocol.ConcurrentGreater, protocol.ConcurrentLesser: // there is a conflict
  462. if e.Invalid != other.Invalid {
  463. if e.Invalid { // we are invalid, we lose
  464. return 1
  465. }
  466. return -1 // they are invalid, we win
  467. }
  468. if e.Deleted != other.Deleted {
  469. if e.Deleted { // we are deleted, we lose
  470. return 1
  471. }
  472. return -1 // they are deleted, we win
  473. }
  474. if d := cmp.Compare(e.Modified, other.Modified); d != 0 {
  475. return -d // positive d means we were newer, so we win (negative return)
  476. }
  477. if vc == protocol.ConcurrentGreater {
  478. return -1 // we have a better device ID, we win
  479. }
  480. return 1 // they win
  481. default:
  482. return 0
  483. }
  484. }