mergeBook inserts or updates the given book in the local database. If a book with a duplicate label exists locally, it renames the duplicate by appending a number.
(tx *database.DB, b client.SyncFragBook, mode int)
| 269 | // mergeBook inserts or updates the given book in the local database. |
| 270 | // If a book with a duplicate label exists locally, it renames the duplicate by appending a number. |
| 271 | func mergeBook(tx *database.DB, b client.SyncFragBook, mode int) error { |
| 272 | var count int |
| 273 | if err := tx.QueryRow("SELECT count(*) FROM books WHERE label = ?", b.Label).Scan(&count); err != nil { |
| 274 | return errors.Wrapf(err, "checking for books with a duplicate label %s", b.Label) |
| 275 | } |
| 276 | |
| 277 | // if duplicate exists locally, rename it and mark it dirty |
| 278 | if count > 0 { |
| 279 | newLabel, err := resolveLabel(tx, b.Label) |
| 280 | if err != nil { |
| 281 | return errors.Wrap(err, "getting a new book label for conflict resolution") |
| 282 | } |
| 283 | |
| 284 | if _, err := tx.Exec("UPDATE books SET label = ?, dirty = ? WHERE label = ? AND uuid != ?", newLabel, true, b.Label, b.UUID); err != nil { |
| 285 | return errors.Wrap(err, "resolving duplicate book label") |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | if mode == modeInsert { |
| 290 | book := database.NewBook(b.UUID, b.Label, b.USN, false, false) |
| 291 | if err := book.Insert(tx); err != nil { |
| 292 | return errors.Wrapf(err, "inserting note with uuid %s", b.UUID) |
| 293 | } |
| 294 | } else if mode == modeUpdate { |
| 295 | // The state from the server overwrites the local state. In other words, the server change always wins. |
| 296 | if _, err := tx.Exec("UPDATE books SET usn = ?, uuid = ?, label = ?, deleted = ? WHERE uuid = ?", |
| 297 | b.USN, b.UUID, b.Label, b.Deleted, b.UUID); err != nil { |
| 298 | return errors.Wrapf(err, "updating local book %s", b.UUID) |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | return nil |
| 303 | } |
| 304 | |
| 305 | func stepSyncBook(tx *database.DB, b client.SyncFragBook) error { |
| 306 | var localUSN int |