1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_CLOUDISK_RDB_TRANSACTION_H 17 #define OHOS_CLOUDISK_RDB_TRANSACTION_H 18 19 #include <atomic> 20 #include <condition_variable> 21 #include <cstdint> 22 #include <mutex> 23 24 #include "rdb_store.h" 25 26 namespace OHOS { 27 namespace FileManagement { 28 namespace CloudDisk { 29 enum TRANS_DB_IDX { 30 PHOTO_RDB_IDX = 0, 31 CLOUDDISK_RDB_IDX = 1, 32 }; 33 static constexpr uint32_t RDB_NUM = 2; 34 /** 35 * This class is used for database transaction creation, commit, and rollback 36 * The usage of class is as follows: 37 * 1. initialize TransactionOperations object with a rdb instance 38 * (for example: TranscationOperations opt(rdb)) 39 * 2. After init opt, you need call Start() function to start transaction 40 * int32_t err = opt.Start(); 41 * if err != E_OK, transaction init failed 42 * 3. If you need to commit transaction, then use 43 * int32_t err = opt.Finish(); 44 * if err != E_OK, transaction commit failed and auto rollback 45 * 4. If TransactionOperations is destructed without successfully finish, it will be auto rollback 46 */ 47 class TransactionOperations { 48 public: 49 TransactionOperations(const std::shared_ptr<OHOS::NativeRdb::RdbStore> &rdbStore); 50 ~TransactionOperations(); 51 std::pair<int32_t, std::shared_ptr<NativeRdb::Transaction>> Start( 52 NativeRdb::Transaction::TransactionType type = NativeRdb::Transaction::EXCLUSIVE); 53 void Finish(); 54 55 private: 56 int32_t BeginTransaction(NativeRdb::Transaction::TransactionType type); 57 int32_t TransactionCommit(); 58 int32_t TransactionRollback(); 59 60 std::shared_ptr<OHOS::NativeRdb::RdbStore> rdbStore_; 61 std::shared_ptr<OHOS::NativeRdb::Transaction> transaction_; 62 63 bool isStart = false; 64 bool isFinish = false; 65 }; 66 } // namespace CloudDisk 67 } // namespace FileManagement 68 } // namespace OHOS 69 #endif // OHOS_CLOUDDISK_RDB_TRANSACTION_H 70