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,SyncState syncState)104 int32_t DataSyncerRdbStore::UpdateSyncState(int32_t userId, const string &bundleName, SyncState syncState)
105 {
106     LOGI("update syncstate %{public}d", syncState);
107     int updateRows;
108     NativeRdb::ValuesBucket values;
109     values.PutInt(SYNC_STATE, static_cast<int32_t>(syncState));
110     if (syncState == SyncState::SYNC_SUCCEED) {
111         values.PutLong(LAST_SYNC_TIME, UTCTimeMilliSeconds());
112     }
113     string whereClause = USER_ID + " = ? AND " + BUNDLE_NAME + " = ?";
114     vector<string> whereArgs = { to_string(userId), bundleName };
115     if (rdb_ == nullptr) {
116         if (RdbInit() != E_OK) {
117             LOGE("Data Syner init rdb failed");
118             return E_RDB;
119         }
120     }
121     int32_t ret = rdb_->Update(updateRows, DATA_SYNCER_TABLE, values, whereClause, whereArgs);
122     if (ret != E_OK) {
123         LOGE("update sync state failed: %{public}d", ret);
124         return E_OK;
125     }
126     return E_OK;
127 }
128 
GetLong(const string & key,int64_t & val,NativeRdb::ResultSet & resultSet)129 static int32_t GetLong(const string &key, int64_t &val, NativeRdb::ResultSet &resultSet)
130 {
131     int32_t index;
132     int32_t err = resultSet.GetColumnIndex(key, index);
133     if (err != NativeRdb::E_OK) {
134         LOGE("result set get  %{public}s column index err %{public}d", key.c_str(), err);
135         return E_RDB;
136     }
137 
138     err = resultSet.GetLong(index, val);
139     if (err != 0) {
140         LOGE("result set get int err %{public}d", err);
141         return E_RDB;
142     }
143 
144     return E_OK;
145 }
146 
GetLastSyncTime(int32_t userId,const string & bundleName,int64_t & time)147 int32_t DataSyncerRdbStore::GetLastSyncTime(int32_t userId, const string &bundleName, int64_t &time)
148 {
149     LOGI("get sync time uid: %{public}d, name: %{public}s", userId, bundleName.c_str());
150     NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
151     predicates.EqualTo(USER_ID, userId)->EqualTo(BUNDLE_NAME, bundleName);
152     std::shared_ptr<NativeRdb::ResultSet> resultSet = nullptr;
153 
154     auto queryRet = Query(predicates, resultSet);
155     if (queryRet != E_OK) {
156         return queryRet;
157     }
158     if (resultSet->GoToNextRow() != E_OK) {
159         return E_INVAL_ARG;
160     }
161     int32_t ret = GetLong(LAST_SYNC_TIME, time, *resultSet);
162     if (ret != E_OK) {
163         LOGE("get last sync time failed");
164         return ret;
165     }
166     return E_OK;
167 }
168 
QueryDataSyncer(int32_t userId,std::shared_ptr<NativeRdb::ResultSet> & resultSet)169 int32_t DataSyncerRdbStore::QueryDataSyncer(int32_t userId, std::shared_ptr<NativeRdb::ResultSet> &resultSet)
170 {
171     NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE);
172     predicates.EqualTo(USER_ID, userId);
173     return Query(predicates, resultSet);
174 }
175 
Query(NativeRdb::AbsRdbPredicates predicates,std::shared_ptr<NativeRdb::ResultSet> & resultSet)176 int32_t DataSyncerRdbStore::Query(NativeRdb::AbsRdbPredicates predicates,
177     std::shared_ptr<NativeRdb::ResultSet> &resultSet)
178 {
179     if (rdb_ == nullptr) {
180         if (RdbInit() != E_OK) {
181             LOGE("Data Syner init rdb failed");
182             return E_RDB;
183         }
184     }
185     resultSet = rdb_->QueryByStep(predicates, {});
186     if (resultSet == nullptr) {
187         LOGE("DataSyncerRdbStore query failed");
188         return E_RDB;
189     }
190     return E_OK;
191 }
192 
193 
OnCreate(NativeRdb::RdbStore & store)194 int32_t DataSyncerRdbCallBack::OnCreate(NativeRdb::RdbStore &store)
195 {
196     vector<string> executeSqlStrs = {
197         CREATE_DATA_SYNCER_TABLE,
198         CREATE_DATA_SYNCER_UNIQUE_INDEX,
199     };
200 
201     for (const string& sqlStr : executeSqlStrs) {
202         if (store.ExecuteSql(sqlStr) != E_OK) {
203             LOGE("create table failed.");
204             return E_RDB;
205         }
206     }
207     return E_OK;
208 }
209 
VersionAddDataSyncerUniqueIndex(NativeRdb::RdbStore & store)210 static void VersionAddDataSyncerUniqueIndex(NativeRdb::RdbStore &store)
211 {
212     const string addDataSyncerUniqueIdColumn =
213         "ALTER TABLE " + DATA_SYNCER_TABLE + " ADD COLUMN " +
214         DATA_SYNCER_UNIQUE_ID + " TEXT";
215     const string initUniqueIdColumn =
216         "UPDATE " + DATA_SYNCER_TABLE + " SET " +
217         DATA_SYNCER_UNIQUE_ID + " = userId || bundleName";
218     const string addDataSyncerUniqueIndex = CREATE_DATA_SYNCER_UNIQUE_INDEX;
219     const vector<string> addUniqueIndex = { addDataSyncerUniqueIdColumn, initUniqueIdColumn,
220         addDataSyncerUniqueIndex};
221     for (size_t i = 0; i < addUniqueIndex.size(); i++) {
222         if (store.ExecuteSql(addUniqueIndex[i]) != NativeRdb::E_OK) {
223             LOGE("upgrade fail idx:%{public}zu", i);
224         }
225     }
226 }
227 
OnUpgrade(NativeRdb::RdbStore & store,int32_t oldVersion,int32_t newVersion)228 int32_t DataSyncerRdbCallBack::OnUpgrade(NativeRdb::RdbStore &store, int32_t oldVersion, int32_t newVersion)
229 {
230     LOGD("OnUpgrade old:%d, new:%d", oldVersion, newVersion);
231     if (oldVersion < VERSION_ADD_DATA_SYNCER_UNIQUE_INDEX) {
232         VersionAddDataSyncerUniqueIndex(store);
233     }
234     return E_OK;
235 }
236 } // namespace OHOS::FileManagement::CloudSync
237