1 /*
2 * Copyright (c) 2023 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 #include "data_syncer_rdb_store.h"
17
18 #include "data_syncer_rdb_col.h"
19 #include "dfs_error.h"
20 #include "rdb_helper.h"
21 #include "rdb_sql_utils.h"
22 #include "rdb_store_config.h"
23 #include "result_set.h"
24 #include "utils_log.h"
25
26 namespace OHOS::FileManagement::CloudSync {
27 using namespace std;
28
GetInstance()29 DataSyncerRdbStore &DataSyncerRdbStore::GetInstance()
30 {
31 static DataSyncerRdbStore instance;
32 return instance;
33 }
34
RdbInit()35 int32_t DataSyncerRdbStore::RdbInit()
36 {
37 LOGI("Init rdb store");
38 int32_t errCode = 0;
39 string databasePath = NativeRdb::RdbSqlUtils::GetDefaultDatabasePath(EL1_CLOUDFILE_DIR, DATA_SYNCER_DB, errCode);
40
41 if (errCode != E_OK) {
42 LOGE("Create Default Database Path is failed, errCode = %{public}d", errCode);
43 return E_RDB;
44 }
45 NativeRdb::RdbStoreConfig config{""};
46 config.SetName(move(DATA_SYNCER_DB));
47 config.SetPath(move(databasePath));
48 errCode = E_OK;
49 DataSyncerRdbCallBack rdbDataCallBack;
50 rdb_ = NativeRdb::RdbHelper::GetRdbStore(config, CLOUD_DISK_RDB_VERSION, rdbDataCallBack, errCode);
51 if (rdb_ == nullptr) {
52 LOGE("GetRdbStore is failed, errCode = %{public}d", errCode);
53 return E_RDB;
54 }
55
56 return E_OK;
57 }
58
Insert(int32_t userId,const std::string & bundleName)59 int32_t DataSyncerRdbStore::Insert(int32_t userId, const std::string &bundleName)
60 {
61 LOGI("datasyncer insert userId %d, bundleName %s", userId, bundleName.c_str());
62 string uniqueId = to_string(userId) + bundleName;
63 NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
64 predicates.EqualTo(DATA_SYNCER_UNIQUE_ID, uniqueId);
65 std::shared_ptr<NativeRdb::ResultSet> resultSet = nullptr;
66 auto queryRet = Query(predicates, resultSet);
67 if (queryRet != E_OK) {
68 return queryRet;
69 }
70 if (resultSet->GoToNextRow() == E_OK) {
71 return E_OK;
72 }
73 NativeRdb::ValuesBucket values;
74 values.PutInt(USER_ID, userId);
75 values.PutString(BUNDLE_NAME, bundleName);
76 values.PutString(DATA_SYNCER_UNIQUE_ID, uniqueId);
77 int32_t ret = 0;
78 {
79 std::lock_guard<std::mutex> lck(rdbMutex_);
80 int64_t rowId;
81 if (rdb_ == nullptr) {
82 if (RdbInit() != E_OK) {
83 LOGE("Data Syner init rdb failed");
84 return E_RDB;
85 }
86 }
87 ret = rdb_->Insert(rowId, DATA_SYNCER_TABLE, values);
88 }
89 if (ret != E_OK) {
90 LOGE("fail to insert userId %d bundleName %s, ret %{public}d", userId, bundleName.c_str(), ret);
91 return E_RDB;
92 }
93
94 return E_OK;
95 }
96
UTCTimeMilliSeconds()97 static int64_t UTCTimeMilliSeconds()
98 {
99 struct timespec t;
100 clock_gettime(CLOCK_REALTIME, &t);
101 return t.tv_sec * SECOND_TO_MILLISECOND + t.tv_nsec / MILLISECOND_TO_NANOSECOND;
102 }
103
UpdateSyncState(int32_t userId,const string & bundleName,CloudSyncState cloudSyncState,ErrorType errorType)104 int32_t DataSyncerRdbStore::UpdateSyncState(int32_t userId, const string &bundleName,
105 CloudSyncState cloudSyncState, ErrorType errorType)
106 {
107 int updateRows;
108 NativeRdb::ValuesBucket values;
109 values.PutInt(SYNC_STATE, static_cast<int32_t>(cloudSyncState));
110 if (cloudSyncState == CloudSyncState::COMPLETED && errorType == ErrorType::NO_ERROR) {
111 values.PutLong(LAST_SYNC_TIME, UTCTimeMilliSeconds());
112 }
113 values.PutInt(SYNC_ERROR_TYPE, static_cast<int32_t>(errorType));
114 string whereClause = USER_ID + " = ? AND " + BUNDLE_NAME + " = ?";
115 vector<string> whereArgs = { to_string(userId), bundleName };
116 if (rdb_ == nullptr) {
117 if (RdbInit() != E_OK) {
118 LOGE("Data Syner init rdb failed");
119 return E_RDB;
120 }
121 }
122 int32_t ret = rdb_->Update(updateRows, DATA_SYNCER_TABLE, values, whereClause, whereArgs);
123 if (ret != E_OK) {
124 LOGE("update sync state failed: %{public}d", ret);
125 return E_RDB;
126 }
127 if (updateRows <= 0) {
128 LOGE("update sync state with no lines changed");
129 return E_RDB;
130 }
131 return E_OK;
132 }
133
GetLong(const string & key,int64_t & val,NativeRdb::ResultSet & resultSet)134 static int32_t GetLong(const string &key, int64_t &val, NativeRdb::ResultSet &resultSet)
135 {
136 int32_t index;
137 int32_t err = resultSet.GetColumnIndex(key, index);
138 if (err != NativeRdb::E_OK) {
139 LOGE("result set get %{public}s column index err %{public}d", key.c_str(), err);
140 return E_RDB;
141 }
142
143 err = resultSet.GetLong(index, val);
144 if (err != NativeRdb::E_OK) {
145 LOGE("result set get long err %{public}d", err);
146 return E_RDB;
147 }
148
149 return E_OK;
150 }
151
GetLastSyncTime(int32_t userId,const string & bundleName,int64_t & time)152 int32_t DataSyncerRdbStore::GetLastSyncTime(int32_t userId, const string &bundleName, int64_t &time)
153 {
154 LOGI("get sync time uid: %{public}d, name: %{public}s", userId, bundleName.c_str());
155 NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
156 predicates.EqualTo(USER_ID, userId)->EqualTo(BUNDLE_NAME, bundleName);
157 std::shared_ptr<NativeRdb::ResultSet> resultSet = nullptr;
158
159 auto queryRet = Query(predicates, resultSet);
160 if (queryRet != E_OK) {
161 return queryRet;
162 }
163 if (resultSet->GoToNextRow() != E_OK) {
164 return E_INVAL_ARG;
165 }
166 int32_t ret = GetLong(LAST_SYNC_TIME, time, *resultSet);
167 if (ret != E_OK) {
168 LOGE("get last sync time failed");
169 return ret;
170 }
171 return E_OK;
172 }
173
GetInt(const string & key,int32_t & val,NativeRdb::ResultSet & resultSet)174 static int32_t GetInt(const string &key, int32_t &val, NativeRdb::ResultSet &resultSet)
175 {
176 int32_t index;
177 int32_t err = resultSet.GetColumnIndex(key, index);
178 if (err != NativeRdb::E_OK) {
179 LOGE("result set get %{public}s column index err %{public}d", key.c_str(), err);
180 return E_RDB;
181 }
182
183 err = resultSet.GetInt(index, val);
184 if (err != NativeRdb::E_OK) {
185 LOGE("result set get int err %{public}d", err);
186 return E_RDB;
187 }
188
189 return E_OK;
190 }
191
GetSyncStateAndErrorType(int32_t userId,const std::string & bundleName,CloudSyncState & cloudSyncState,ErrorType & errorType)192 int32_t DataSyncerRdbStore::GetSyncStateAndErrorType(int32_t userId, const std::string &bundleName,
193 CloudSyncState &cloudSyncState, ErrorType &errorType)
194 {
195 NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
196 predicates.EqualTo(USER_ID, userId)->EqualTo(BUNDLE_NAME, bundleName);
197 std::shared_ptr<NativeRdb::ResultSet> resultSet = nullptr;
198
199 auto queryRet = Query(predicates, resultSet);
200 if (queryRet != E_OK) {
201 LOGE("get sync state query failed");
202 return queryRet;
203 }
204 if (resultSet->GoToNextRow() != E_OK) {
205 LOGE("get sync state no more rows");
206 return E_INVAL_ARG;
207 }
208
209 int32_t syncState = static_cast<int32_t>(CloudSyncState::COMPLETED);
210 int32_t ret = GetInt(SYNC_STATE, syncState, *resultSet);
211 if (ret != E_OK) {
212 LOGE("get sync state failed");
213 return ret;
214 } else {
215 cloudSyncState = static_cast<CloudSyncState>(syncState);
216 }
217
218 int32_t err = static_cast<int32_t>(ErrorType::NO_ERROR);
219 ret = GetInt(SYNC_ERROR_TYPE, err, *resultSet);
220 if (ret != E_OK) {
221 LOGE("get error type failed");
222 return ret;
223 } else {
224 errorType = static_cast<ErrorType>(err);
225 }
226 return E_OK;
227 }
228
QueryDataSyncer(int32_t userId,std::shared_ptr<NativeRdb::ResultSet> & resultSet)229 int32_t DataSyncerRdbStore::QueryDataSyncer(int32_t userId, std::shared_ptr<NativeRdb::ResultSet> &resultSet)
230 {
231 NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
232 predicates.EqualTo(USER_ID, userId);
233 return Query(predicates, resultSet);
234 }
235
QueryCloudSync(int32_t userId,const std::string & bundleName,std::shared_ptr<NativeRdb::ResultSet> & resultSet)236 int32_t DataSyncerRdbStore::QueryCloudSync(int32_t userId,
237 const std::string &bundleName,
238 std::shared_ptr<NativeRdb::ResultSet> &resultSet)
239 {
240 NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
241 predicates.EqualTo(USER_ID, userId);
242 predicates.EqualTo(BUNDLE_NAME, bundleName);
243 return Query(predicates, resultSet);
244 }
245
Query(NativeRdb::AbsRdbPredicates predicates,std::shared_ptr<NativeRdb::ResultSet> & resultSet)246 int32_t DataSyncerRdbStore::Query(NativeRdb::AbsRdbPredicates predicates,
247 std::shared_ptr<NativeRdb::ResultSet> &resultSet)
248 {
249 if (rdb_ == nullptr) {
250 if (RdbInit() != E_OK) {
251 LOGE("Data Syner init rdb failed");
252 return E_RDB;
253 }
254 }
255 resultSet = rdb_->QueryByStep(predicates, {});
256 if (resultSet == nullptr) {
257 LOGE("DataSyncerRdbStore query failed");
258 return E_RDB;
259 }
260 return E_OK;
261 }
262
263
OnCreate(NativeRdb::RdbStore & store)264 int32_t DataSyncerRdbCallBack::OnCreate(NativeRdb::RdbStore &store)
265 {
266 vector<string> executeSqlStrs = {
267 CREATE_DATA_SYNCER_TABLE,
268 CREATE_DATA_SYNCER_UNIQUE_INDEX,
269 };
270
271 for (const string& sqlStr : executeSqlStrs) {
272 if (store.ExecuteSql(sqlStr) != E_OK) {
273 LOGE("create table failed.");
274 return E_RDB;
275 }
276 }
277 return E_OK;
278 }
279
VersionAddDataSyncerUniqueIndex(NativeRdb::RdbStore & store)280 static void VersionAddDataSyncerUniqueIndex(NativeRdb::RdbStore &store)
281 {
282 const string addDataSyncerUniqueIdColumn =
283 "ALTER TABLE " + DATA_SYNCER_TABLE + " ADD COLUMN " +
284 DATA_SYNCER_UNIQUE_ID + " TEXT";
285 const string initUniqueIdColumn =
286 "UPDATE " + DATA_SYNCER_TABLE + " SET " +
287 DATA_SYNCER_UNIQUE_ID + " = userId || bundleName";
288 const string addDataSyncerUniqueIndex = CREATE_DATA_SYNCER_UNIQUE_INDEX;
289 const vector<string> addUniqueIndex = { addDataSyncerUniqueIdColumn, initUniqueIdColumn,
290 addDataSyncerUniqueIndex};
291 for (size_t i = 0; i < addUniqueIndex.size(); i++) {
292 if (store.ExecuteSql(addUniqueIndex[i]) != NativeRdb::E_OK) {
293 LOGE("upgrade fail idx:%{public}zu", i);
294 }
295 }
296 }
297
VersionAddDataSyncerErrorType(NativeRdb::RdbStore & store)298 static void VersionAddDataSyncerErrorType(NativeRdb::RdbStore &store)
299 {
300 const string addDataSyncerErrorType = CREATE_DATA_SYNCER_ERROR_TYPE;
301 if (store.ExecuteSql(addDataSyncerErrorType) != NativeRdb::E_OK) {
302 LOGE("upgrade fail add errorType");
303 }
304 const string updateCloudSyncState = UPDATE_CLOUD_SYNC_STATE;
305 if (store.ExecuteSql(updateCloudSyncState) != NativeRdb::E_OK) {
306 LOGE("upgrade fail sync state -> cloud sync state");
307 }
308 }
309
OnUpgrade(NativeRdb::RdbStore & store,int32_t oldVersion,int32_t newVersion)310 int32_t DataSyncerRdbCallBack::OnUpgrade(NativeRdb::RdbStore &store, int32_t oldVersion, int32_t newVersion)
311 {
312 LOGD("OnUpgrade old:%d, new:%d", oldVersion, newVersion);
313 if (oldVersion < VERSION_ADD_DATA_SYNCER_UNIQUE_INDEX) {
314 VersionAddDataSyncerUniqueIndex(store);
315 }
316 if (oldVersion < VERSION_ADD_ERROR_TYPE) {
317 VersionAddDataSyncerErrorType(store);
318 }
319 return E_OK;
320 }
321 } // namespace OHOS::FileManagement::CloudSync
322