migration_delegate.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/leveldb_proto/internal/migration_delegate.h"
  5. #include <memory>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/task/sequenced_task_runner.h"
  9. #include "base/threading/sequenced_task_runner_handle.h"
  10. namespace leveldb_proto {
  11. MigrationDelegate::MigrationDelegate() {}
  12. MigrationDelegate::~MigrationDelegate() = default;
  13. void MigrationDelegate::DoMigration(UniqueProtoDatabase* from,
  14. UniqueProtoDatabase* to,
  15. MigrationCallback callback) {
  16. from->LoadKeysAndEntries(base::BindOnce(
  17. &MigrationDelegate::OnLoadKeysAndEntries, weak_ptr_factory_.GetWeakPtr(),
  18. std::move(callback), base::Unretained(to)));
  19. }
  20. void MigrationDelegate::OnLoadKeysAndEntries(
  21. MigrationCallback callback,
  22. UniqueProtoDatabase* to,
  23. bool success,
  24. std::unique_ptr<KeyValueMap> keys_entries) {
  25. if (!success) {
  26. DCHECK(base::SequencedTaskRunnerHandle::IsSet());
  27. auto current_task_runner = base::SequencedTaskRunnerHandle::Get();
  28. current_task_runner->PostTask(FROM_HERE,
  29. base::BindOnce(std::move(callback), false));
  30. return;
  31. }
  32. // Convert the std::map we got back into a vector of std::pairs to be used
  33. // with UpdateEntries.
  34. auto kev = std::make_unique<KeyValueVector>();
  35. for (auto const& key_entry : *keys_entries)
  36. kev->push_back(key_entry);
  37. // Save the entries in |to|.
  38. to->UpdateEntries(
  39. std::move(kev), std::make_unique<KeyVector>(),
  40. base::BindOnce(&MigrationDelegate::OnUpdateEntries,
  41. weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  42. }
  43. void MigrationDelegate::OnUpdateEntries(MigrationCallback callback,
  44. bool success) {
  45. DCHECK(base::SequencedTaskRunnerHandle::IsSet());
  46. auto current_task_runner = base::SequencedTaskRunnerHandle::Get();
  47. current_task_runner->PostTask(FROM_HERE,
  48. base::BindOnce(std::move(callback), success));
  49. // TODO (thildebr): For additional insurance, verify the entries match,
  50. // although they should if we got a success from UpdateEntries.
  51. }
  52. } // namespace leveldb_proto