1 /*
2  * Copyright (c) 2021 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 SQLITE_SINGLE_VER_STORAGE_ENGINE_H
17 #define SQLITE_SINGLE_VER_STORAGE_ENGINE_H
18 
19 #include "macro_utils.h"
20 #include "sqlite_storage_engine.h"
21 #include "sqlite_single_ver_storage_executor.h"
22 
23 namespace DistributedDB {
24 enum class SQLiteGeneralNSNotificationEventType {
25     SQLITE_GENERAL_NS_PUT_EVENT = 0x01,
26     SQLITE_GENERAL_NS_SYNC_EVENT = 0x02,
27     SQLITE_GENERAL_NS_LOCAL_PUT_EVENT = 0x04,
28     SQLITE_GENERAL_CONFLICT_EVENT = 0x08, // Conflict event
29     SQLITE_GENERAL_FINISH_MIGRATE_EVENT = 0x10, // Only trigger sync event
30 };
31 enum class SQLiteGeneralNSConflictType {
32     SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY = 0x01, // sync conflict for same origin dev
33     SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG = 0x02, // sync conflict for different origin dev
34     SQLITE_GENERAL_NS_NATIVE_ALL = 0x0c, // native conflict.
35 };
36 class SQLiteSingleVerStorageEngine : public SQLiteStorageEngine {
37 public:
38     SQLiteSingleVerStorageEngine();
39     ~SQLiteSingleVerStorageEngine() override;
40 
41     // Delete the copy and assign constructors
42     DISABLE_COPY_ASSIGN_MOVE(SQLiteSingleVerStorageEngine);
43 
44     void IncreaseCacheRecordVersion() override;
45     uint64_t GetCacheRecordVersion() const override;
46     uint64_t GetAndIncreaseCacheRecordVersion() override;
47 
48     int ExecuteMigrate() override;
49     bool IsEngineCorrupted() const override;
50 
GetSecurityOption()51     const SecurityOption &GetSecurityOption() const
52     {
53         return option_.securityOpt;
54     }
55 
SetNeedUpdateSecOption(bool flag)56     void SetNeedUpdateSecOption(bool flag)
57     {
58         isNeedUpdateSecOpt_ = flag;
59     }
60 
61     void CacheSubscribe(const std::string &subscribeId, const QueryObject &query);
62 
63     int UpgradeLocalMetaData();
64 
65 protected:
66     virtual StorageExecutor *NewSQLiteStorageExecutor(sqlite3 *dbHandle, bool isWrite, bool isMemDb) override;
67 
68     int Upgrade(sqlite3 *db) override;
69 
70     int CreateNewExecutor(bool isWrite, StorageExecutor *&handle) override;
71 
72     ExecutorState executorState_;
73 
74 private:
75     // For executor.
76     int PreCreateExecutor(bool isWrite, SecurityOption &existedSecOpt);
77     int EndCreateExecutor(sqlite3 *db, bool isWrite, bool isDetachMeta);
78     int ReInit() override;
79     int ReleaseExecutor(SQLiteSingleVerStorageExecutor *&handle);
80     int ReleaseHandleTransiently(SQLiteSingleVerStorageExecutor *&handle, uint64_t idleTime,
81         NotifyMigrateSyncData &syncData);
82 
83     // For migrate.
84     int MigrateLocalData(SQLiteSingleVerStorageExecutor *handle) const;
85     int MigrateSyncDataByVersion(SQLiteSingleVerStorageExecutor *&handle,
86         NotifyMigrateSyncData &syncData, uint64_t &curMigrateVer);
87     int MigrateSyncData(SQLiteSingleVerStorageExecutor *&handle, bool &isNeedTriggerSync);
88     int FinishMigrateData(SQLiteSingleVerStorageExecutor *&handle, EngineState stateBeforeMigrate);
89     int InitExecuteMigrate(SQLiteSingleVerStorageExecutor *handle, EngineState preMigrateState);
90     void EndMigrate(SQLiteSingleVerStorageExecutor *&handle, EngineState stateBeforeMigrate, int errCode,
91         bool isNeedTriggerSync);
92     void ResetCacheRecordVersion();
93     int EraseDeviceWaterMark(SQLiteSingleVerStorageExecutor *&handle, const std::vector<DataItem> &dataItems);
94     int EraseDeviceWaterMark(const std::set<std::string> &removeDevices, bool isNeedHash);
95     int GetRemoveDataDevices(SQLiteSingleVerStorageExecutor *handle, const DataItem &item,
96         std::set<std::string> &removeDevices, bool &isNeedHash) const;
97 
98     // For db.
99     int TryToOpenMainDatabase(bool isWrite, sqlite3 *&db);
100     int GetCacheDbHandle(sqlite3 *&db);
101     int GetDbHandle(bool isWrite, const SecurityOption &secOpt, sqlite3 *&dbHandle);
102     int AttachMetaDatabase(sqlite3 *dbHandle, const OpenDbProperties &option) const;
103     int AttachMainDbAndCacheDb(SQLiteSingleVerStorageExecutor *handle, EngineState stateBeforeMigrate);
104     int AttachMainDbAndCacheDb(sqlite3 *dbHandle, EngineState stateBeforeMigrate) const;
105     void RegisterFunctionIfNeed(sqlite3 *dbHandle) const;
106     int TryAttachMetaDb(const SecurityOption &existedSecOpt, sqlite3 *&dbHandle, bool &isAttachMeta,
107         bool &isNeedDetachMeta);
108 
109     // For secOpt.
110     int CreateNewDirsAndSetSecOpt() const;
111     void CheckDatabaseSecOpt(const SecurityOption &secOption) const;
112     int GetExistedSecOption(SecurityOption &secOption) const;
113 
114     void ClearCorruptedFlag() override;
115 
116     // For commit notify.
117     void CommitAndReleaseNotifyData(SingleVerNaturalStoreCommitNotifyData *&committedData, int eventType) const;
118     void InitConflictNotifiedFlag(SingleVerNaturalStoreCommitNotifyData *&committedData) const;
119     void CommitNotifyForMigrateCache(NotifyMigrateSyncData &syncData) const;
120 
121     // For subscribe
122     int AddSubscribeToMainDBInMigrate();
123 
124     bool IsUseExistedSecOption(const SecurityOption &existedSecOpt, const SecurityOption &openSecOpt);
125 
126     mutable std::mutex migrateLock_;
127     std::atomic<uint64_t> cacheRecordVersion_;
128     bool isCorrupted_;
129     bool isNeedUpdateSecOpt_; // update the option_
130 
131     std::mutex subscribeMutex_;
132     std::map<std::string, QueryObject> subscribeQuery_;
133 };
134 } // namespace DistributedDB
135 
136 #endif // SQLITE_SINGLE_VER_STORAGE_ENGINE_H
137