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 RINGTONE_RDB_TRANSACTION_H
17 #define RINGTONE_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::Media {
27 #define EXPORT __attribute__ ((visibility ("default")))
28 static constexpr int32_t SQLITE3_DATABASE_LOCKER = -5;
29 /**
30  * This class is used for database transaction creation, commit, and rollback
31  * The usage of class is as follows:
32  *   1. initialize RingtoneRdbTransaction object with a rdb instance
33  *          (for example: TranscationOperations opt(rdb))
34  *   2. After init opt, you need call Start() function to start transaction
35  *          int32_t err = opt.Start();
36  *          if err != E_OK, transaction init failed
37  *   3. If you need to commit transaction, then use
38  *          int32_t err = opt.Finish();
39  *          if err != E_OK, transaction commit failed and auto rollback
40  *   4. If RingtoneRdbTransaction is destructed without successfully finish, it will be auto rollback
41  */
42 class RingtoneRdbTransaction {
43 public:
44     EXPORT RingtoneRdbTransaction(const std::shared_ptr<OHOS::NativeRdb::RdbStore> &rdbStore);
45     EXPORT ~RingtoneRdbTransaction();
46     EXPORT int32_t Start();
47     EXPORT void Finish();
48 
49 private:
50     int32_t BeginTransaction();
51     int32_t TransactionCommit();
52     int32_t TransactionRollback();
53 
54     std::shared_ptr<OHOS::NativeRdb::RdbStore> rdbStore_;
55     bool isStart = false;
56     bool isFinish = false;
57 
58     static std::mutex transactionMutex_;
59     static std::condition_variable transactionCV_;
60     static std::atomic<bool> isInTransaction_;
61 };
62 } // namespace OHOS::Media
63 
64 #endif // RINGTONE_RDB_TRANSACTION_H
65