1 /*
2 * Copyright (c) 2025 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 #include "rdb_general_ut.h"
16 #include "rdb_data_generator.h"
17 #include "runtime_config.h"
18 #include "sqlite_relational_utils.h"
19 #include "virtual_cloud_data_translate.h"
20
21 using namespace DistributedDBUnitTest;
22
23 namespace DistributedDB {
24 const std::string CIPHER_CONFIG_SQL = "PRAGMA codec_cipher='aes-256-gcm';";
25 const std::string KDF_ITER_CONFIG_SQL = "PRAGMA codec_kdf_iter=5000;";
26 const std::string SHA256_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA256;";
27
28 const Field intField = {"id", TYPE_INDEX<int64_t>, true, false};
29 const Field stringField = {"name", TYPE_INDEX<std::string>, false, false};
30 const Field boolField = {"gender", TYPE_INDEX<bool>, false, true};
31 const Field doubleField = {"height", TYPE_INDEX<double>, false, true};
32 const Field bytesField = {"photo", TYPE_INDEX<Bytes>, false, true};
33 const Field assetField = {"assert", TYPE_INDEX<Asset>, false, true};
34 const Field assetsField = {"asserts", TYPE_INDEX<Assets>, false, true};
35
36 const std::vector<UtFieldInfo> g_defaultFiledInfo = {
37 {intField, true}, {stringField, false}, {boolField, false},
38 {doubleField, false}, {bytesField, false}, {assetField, false}, {assetsField, false},
39 };
40
41 UtDateBaseSchemaInfo g_defaultSchemaInfo = {
42 .tablesInfo = {
43 {.name = g_defaultTable1, .sharedTableName = g_defaultTable1 + "_shared", .fieldInfo = g_defaultFiledInfo},
44 {.name = g_defaultTable2, .fieldInfo = g_defaultFiledInfo}
45 }
46 };
47
InitDelegate(const StoreInfo & info)48 int RDBGeneralUt::InitDelegate(const StoreInfo &info)
49 {
50 InitDatabase(info);
51 {
52 std::lock_guard<std::mutex> autoLock(storeMutex_);
53 if (stores_.find(info) != stores_.end()) {
54 return E_OK;
55 }
56 }
57 auto [errCode, delegate] = OpenRDBStore(info);
58 if ((errCode != E_OK )|| (delegate == nullptr)) {
59 LOGE("[RDBGeneralUt] Open store failed %d", errCode);
60 return errCode;
61 }
62 {
63 std::lock_guard<std::mutex> autoLock(storeMutex_);
64 stores_[info] = delegate;
65 }
66 LOGI("[RDBGeneralUt] Init delegate app %s store %s user %s success", info.appId.c_str(),
67 info.storeId.c_str(), info.userId.c_str());
68 return E_OK;
69 }
70
OpenRDBStore(const StoreInfo & info)71 std::pair<int, RelationalStoreDelegate *> RDBGeneralUt::OpenRDBStore(const StoreInfo &info)
72 {
73 std::pair<int, RelationalStoreDelegate *> res;
74 auto &[errCode, delegate] = res;
75 delegate = nullptr;
76 std::string storePath = GetTestDir() + "/" + info.storeId + ".db";
77 RelationalStoreManager mgr(info.appId, info.userId);
78 RelationalStoreDelegate::Option option = GetOption();
79 errCode = mgr.OpenStore(storePath, info.storeId, option, delegate);
80 return res;
81 }
82
SetOption(const RelationalStoreDelegate::Option & option)83 void RDBGeneralUt::SetOption(const RelationalStoreDelegate::Option& option)
84 {
85 std::lock_guard<std::mutex> autoLock(storeMutex_);
86 option_ = option;
87 }
88
GetOption() const89 RelationalStoreDelegate::Option RDBGeneralUt::GetOption() const
90 {
91 std::lock_guard<std::mutex> autoLock(storeMutex_);
92 return option_;
93 }
94
SetSchemaInfo(const StoreInfo & info,const DistributedDBUnitTest::UtDateBaseSchemaInfo & schemaInfo)95 void RDBGeneralUt::SetSchemaInfo(const StoreInfo &info, const DistributedDBUnitTest::UtDateBaseSchemaInfo &schemaInfo)
96 {
97 std::lock_guard<std::mutex> autoLock(storeMutex_);
98 schemaInfoMap_[info] = schemaInfo;
99 }
100
GetTableSchemaInfo(const StoreInfo & info) const101 UtDateBaseSchemaInfo RDBGeneralUt::GetTableSchemaInfo(const StoreInfo &info) const
102 {
103 std::lock_guard<std::mutex> autoLock(storeMutex_);
104 auto iter = schemaInfoMap_.find(info);
105 if (iter != schemaInfoMap_.end()) {
106 return iter->second;
107 }
108 return g_defaultSchemaInfo;
109 }
110
GetSchema(const StoreInfo & info) const111 DataBaseSchema RDBGeneralUt::GetSchema(const StoreInfo &info) const
112 {
113 UtDateBaseSchemaInfo schemaInfo = GetTableSchemaInfo(info);
114 DataBaseSchema schema;
115 for (auto &item : schemaInfo.tablesInfo) {
116 TableSchema tableSchema;
117 tableSchema.name = item.name;
118 tableSchema.sharedTableName = item.sharedTableName;
119 for (auto &fieldInfo : item.fieldInfo) {
120 tableSchema.fields.push_back(fieldInfo.field);
121 }
122 schema.tables.push_back(tableSchema);
123 }
124 return schema;
125 }
126
GetTableSchema(const StoreInfo & info,const std::string & tableName) const127 TableSchema RDBGeneralUt::GetTableSchema(const StoreInfo &info, const std::string &tableName) const
128 {
129 UtDateBaseSchemaInfo schemaInfo = GetTableSchemaInfo(info);
130 for (auto &item : schemaInfo.tablesInfo) {
131 if (item.name != tableName) {
132 continue;
133 }
134 TableSchema tableSchema;
135 tableSchema.name = item.name;
136 tableSchema.sharedTableName = item.sharedTableName;
137 for (auto &fieldInfo : item.fieldInfo) {
138 tableSchema.fields.push_back(fieldInfo.field);
139 }
140 return tableSchema;
141 }
142 LOGD("[RDBGeneralUt] Table %s not found", tableName.c_str());
143 return {"", "", {}};
144 }
145
GetAllTrackerSchema(const StoreInfo & info,const std::vector<std::string> & tables) const146 std::vector<TrackerSchema> RDBGeneralUt::GetAllTrackerSchema(const StoreInfo &info,
147 const std::vector<std::string> &tables) const
148 {
149 UtDateBaseSchemaInfo schemaInfo = GetTableSchemaInfo(info);
150 std::vector<TrackerSchema> res;
151 std::set<std::string> trackerTables(tables.begin(), tables.end());
152 for (const auto &item : schemaInfo.tablesInfo) {
153 if (trackerTables.find(item.name) == trackerTables.end()) {
154 continue;
155 }
156 TrackerSchema trackerSchema;
157 trackerSchema.tableName = item.name;
158 for (const auto &field : item.fieldInfo) {
159 trackerSchema.trackerColNames.insert(field.field.colName);
160 trackerSchema.extendColNames.insert(field.field.colName);
161 }
162 res.push_back(std::move(trackerSchema));
163 }
164 return res;
165 }
166
CloseDelegate(const StoreInfo & info)167 int RDBGeneralUt::CloseDelegate(const StoreInfo &info)
168 {
169 std::lock_guard<std::mutex> autoLock(storeMutex_);
170 auto storeIter = stores_.find(info);
171 if (storeIter != stores_.end()) {
172 RelationalStoreManager mgr(info.appId, info.userId);
173 EXPECT_EQ(mgr.CloseStore(storeIter->second), OK);
174 storeIter->second = nullptr;
175 stores_.erase(storeIter);
176 }
177 auto dbIter = sqliteDb_.find(info);
178 if (dbIter != sqliteDb_.end()) {
179 sqlite3_close_v2(dbIter->second);
180 dbIter->second = nullptr;
181 sqliteDb_.erase(dbIter);
182 }
183 auto schemaIter = schemaInfoMap_.find(info);
184 if (schemaIter != schemaInfoMap_.end()) {
185 schemaInfoMap_.erase(schemaIter);
186 }
187 LOGI("[RDBGeneralUt] Close delegate app %s store %s user %s success", info.appId.c_str(),
188 info.storeId.c_str(), info.userId.c_str());
189 return E_OK;
190 }
191
CloseAllDelegate()192 void RDBGeneralUt::CloseAllDelegate()
193 {
194 std::lock_guard<std::mutex> autoLock(storeMutex_);
195 for (auto &iter : sqliteDb_) {
196 sqlite3_close_v2(iter.second);
197 iter.second = nullptr;
198 }
199 sqliteDb_.clear();
200 for (auto &iter : stores_) {
201 RelationalStoreManager mgr(iter.first.appId, iter.first.userId);
202 EXPECT_EQ(mgr.CloseStore(iter.second), OK);
203 iter.second = nullptr;
204 }
205 stores_.clear();
206 schemaInfoMap_.clear();
207 isDbEncrypted_ = false;
208 LOGI("[RDBGeneralUt] Close all delegate success");
209 }
210
SetUp()211 void RDBGeneralUt::SetUp()
212 {
213 BasicUnitTest::SetUp();
214 RuntimeConfig::SetCloudTranslate(std::make_shared<VirtualCloudDataTranslate>());
215 {
216 std::lock_guard<std::mutex> autoLock(storeMutex_);
217 virtualCloudDb_ = std::make_shared<VirtualCloudDb>();
218 virtualAssetLoader_ = std::make_shared<VirtualAssetLoader>();
219 }
220 }
221
TearDown()222 void RDBGeneralUt::TearDown()
223 {
224 CloseAllDelegate();
225 {
226 std::lock_guard<std::mutex> autoLock(storeMutex_);
227 virtualCloudDb_ = nullptr;
228 virtualAssetLoader_ = nullptr;
229 }
230 BasicUnitTest::TearDown();
231 }
232
InitDatabase(const StoreInfo & info)233 int RDBGeneralUt::InitDatabase(const StoreInfo &info)
234 {
235 std::string storePath = GetTestDir() + "/" + info.storeId + ".db";
236 sqlite3 *db = RelationalTestUtils::CreateDataBase(storePath);
237 if (db == nullptr) {
238 LOGE("[RDBGeneralUt] Create database failed %s", storePath.c_str());
239 return -E_INVALID_DB;
240 }
241 int errCode = E_OK;
242 if (GetIsDbEncrypted()) {
243 errCode = EncryptedDb(db);
244 if (errCode != E_OK) {
245 return errCode;
246 }
247 }
248 UtDateBaseSchemaInfo schemaInfo = GetTableSchemaInfo(info);
249 errCode = RDBDataGenerator::InitDatabaseWithSchemaInfo(schemaInfo, *db);
250 if (errCode != SQLITE_OK) {
251 LOGE("[RDBGeneralUt] Init database failed %d", errCode);
252 return errCode;
253 }
254 {
255 std::lock_guard<std::mutex> autoLock(storeMutex_);
256 if (sqliteDb_.find(info) != sqliteDb_.end()) {
257 sqlite3_close_v2(db);
258 return E_OK;
259 }
260 sqliteDb_[info] = db;
261 }
262 return E_OK;
263 }
264
GetSqliteHandle(const StoreInfo & info) const265 sqlite3 *RDBGeneralUt::GetSqliteHandle(const StoreInfo &info) const
266 {
267 std::lock_guard<std::mutex> autoLock(storeMutex_);
268 auto db = sqliteDb_.find(info);
269 if (db == sqliteDb_.end()) {
270 LOGE("[RDBGeneralUt] Not exist sqlite db app %s store %s user %s", info.appId.c_str(),
271 info.storeId.c_str(), info.userId.c_str());
272 return nullptr;
273 }
274 return db->second;
275 }
276
InsertLocalDBData(int64_t begin,int64_t count,const StoreInfo & info)277 int RDBGeneralUt::InsertLocalDBData(int64_t begin, int64_t count, const StoreInfo &info)
278 {
279 auto schema = GetSchema(info);
280 auto db = GetSqliteHandle(info);
281 if (db == nullptr) {
282 LOGE("[RDBGeneralUt] Get null sqlite when insert data");
283 return -E_INVALID_DB;
284 }
285 auto errCode = RDBDataGenerator::InsertLocalDBData(begin, begin + count, db, schema);
286 if (errCode != E_OK) {
287 LOGE("[RDBGeneralUt] Insert data failed %d app %s store %s user %s", errCode, info.appId.c_str(),
288 info.storeId.c_str(), info.userId.c_str());
289 } else {
290 LOGI("[RDBGeneralUt] Insert data success begin %" PRId64 " count %" PRId64 " app %s store %s user %s",
291 begin, count, info.appId.c_str(), info.storeId.c_str(), info.userId.c_str());
292 }
293 return errCode;
294 }
295
ExecuteSQL(const std::string & sql,const StoreInfo & info)296 int RDBGeneralUt::ExecuteSQL(const std::string &sql, const StoreInfo &info)
297 {
298 auto db = GetSqliteHandle(info);
299 if (db == nullptr) {
300 LOGE("[RDBGeneralUt] Get null sqlite when insert data");
301 return -E_INVALID_DB;
302 }
303 return SQLiteUtils::ExecuteRawSQL(db, sql);
304 }
305
CreateDistributedTable(const StoreInfo & info,const std::string & table,TableSyncType type)306 int RDBGeneralUt::CreateDistributedTable(const StoreInfo &info, const std::string &table, TableSyncType type)
307 {
308 auto store = GetDelegate(info);
309 if (store == nullptr) {
310 LOGE("[RDBGeneralUt] Get null delegate when create distributed table %s", table.c_str());
311 return -E_INVALID_DB;
312 }
313 auto errCode = store->CreateDistributedTable(table, type);
314 if (errCode != E_OK) {
315 LOGE("[RDBGeneralUt] Create distributed table failed %d app %s store %s user %s", errCode, info.appId.c_str(),
316 info.storeId.c_str(), info.userId.c_str());
317 }
318 LOGI("[RDBGeneralUt] Create distributed table success, app %s store %s user %s", info.appId.c_str(),
319 info.storeId.c_str(), info.userId.c_str());
320 return errCode;
321 }
322
SetDistributedTables(const StoreInfo & info,const std::vector<std::string> & tables,TableSyncType type)323 int RDBGeneralUt::SetDistributedTables(const StoreInfo &info, const std::vector<std::string> &tables,
324 TableSyncType type)
325 {
326 int errCode = E_OK;
327 for (const auto &table : tables) {
328 errCode = CreateDistributedTable(info, table, type);
329 if (errCode != E_OK) {
330 return errCode;
331 }
332 }
333 RelationalStoreDelegate::Option option = GetOption();
334 if (option.tableMode != DistributedTableMode::COLLABORATION) {
335 return E_OK;
336 }
337 auto store = GetDelegate(info);
338 if (store == nullptr) {
339 LOGE("[RDBGeneralUt] Get null delegate when set distributed tables");
340 return -E_INVALID_DB;
341 }
342 auto schema = GetSchema(info);
343 errCode = store->SetDistributedSchema(RDBDataGenerator::ParseSchema(schema));
344 if (errCode != E_OK) {
345 LOGE("[RDBGeneralUt] Set distributed schema failed %d app %s store %s user %s", errCode, info.appId.c_str(),
346 info.storeId.c_str(), info.userId.c_str());
347 }
348 LOGI("[RDBGeneralUt] Set distributed table success, app %s store %s user %s", info.appId.c_str(),
349 info.storeId.c_str(), info.userId.c_str());
350 return errCode;
351 }
352
GetDelegate(const StoreInfo & info) const353 RelationalStoreDelegate *RDBGeneralUt::GetDelegate(const StoreInfo &info) const
354 {
355 std::lock_guard<std::mutex> autoLock(storeMutex_);
356 auto db = stores_.find(info);
357 if (db == stores_.end()) {
358 LOGE("[RDBGeneralUt] Not exist delegate app %s store %s user %s", info.appId.c_str(),
359 info.storeId.c_str(), info.userId.c_str());
360 return nullptr;
361 }
362 return db->second;
363 }
364
BlockPush(const StoreInfo & from,const StoreInfo & to,const std::string & table,DBStatus expectRet)365 void RDBGeneralUt::BlockPush(const StoreInfo &from, const StoreInfo &to, const std::string &table, DBStatus expectRet)
366 {
367 ASSERT_NO_FATAL_FAILURE(BlockSync(from, to, table, SYNC_MODE_PUSH_ONLY, expectRet));
368 }
369
BlockPull(const StoreInfo & from,const StoreInfo & to,const std::string & table,DBStatus expectRet)370 void RDBGeneralUt::BlockPull(const StoreInfo &from, const StoreInfo &to, const std::string &table, DBStatus expectRet)
371 {
372 ASSERT_NO_FATAL_FAILURE(BlockSync(from, to, table, SYNC_MODE_PULL_ONLY, expectRet));
373 }
374
BlockSync(const StoreInfo & from,const StoreInfo & to,const std::string & table,SyncMode mode,DBStatus expectRet)375 void RDBGeneralUt::BlockSync(const StoreInfo &from, const StoreInfo &to, const std::string &table, SyncMode mode,
376 DBStatus expectRet)
377 {
378 auto store = GetDelegate(from);
379 ASSERT_NE(store, nullptr);
380 auto toDevice = GetDevice(to);
381 ASSERT_FALSE(toDevice.empty());
382 Query query = Query::Select(table);
383 ASSERT_NO_FATAL_FAILURE(DistributedDBToolsUnitTest::BlockSync(*store, query, mode, expectRet, {toDevice}));
384 }
385
CountTableData(const StoreInfo & info,const std::string & table,const std::string & condition)386 int RDBGeneralUt::CountTableData(const StoreInfo &info, const std::string &table, const std::string &condition)
387 {
388 return CountTableDataByDev(info, table, "", condition);
389 }
390
CountTableDataByDev(const StoreInfo & info,const std::string & table,const std::string & dev,const std::string & condition)391 int RDBGeneralUt::CountTableDataByDev(const StoreInfo &info, const std::string &table, const std::string &dev,
392 const std::string &condition)
393 {
394 auto db = GetSqliteHandle(info);
395 if (db == nullptr) {
396 LOGE("[RDBGeneralUt] Get null sqlite when count table %s", table.c_str());
397 return 0;
398 }
399 bool isCreated = false;
400 int errCode = SQLiteUtils::CheckTableExists(db, table, isCreated);
401 if (errCode != E_OK) {
402 LOGE("[RDBGeneralUt] Check table exist failed %d when count table %s", errCode, table.c_str());
403 return 0;
404 }
405 if (!isCreated) {
406 LOGW("[RDBGeneralUt] Check table %s not exist", table.c_str());
407 return 0;
408 }
409
410 std::string cntSql = "SELECT count(*) FROM '" + table + "'";
411 if (!condition.empty() || !dev.empty()) {
412 cntSql.append(" WHERE ");
413 }
414 if (!condition.empty()) {
415 cntSql.append(condition);
416 if (!dev.empty()) {
417 cntSql.append(" AND ");
418 }
419 }
420 if (!dev.empty()) {
421 auto hex = DBCommon::TransferStringToHex(DBCommon::TransferHashString(dev));
422 cntSql.append("device='").append(hex).append("'");
423 }
424 sqlite3_stmt *stmt = nullptr;
425 errCode = SQLiteUtils::GetStatement(db, cntSql, stmt);
426 if (errCode != E_OK) {
427 LOGE("[RDBGeneralUt] Check table %s failed by get stmt %d", table.c_str(), errCode);
428 return 0;
429 }
430 int count = 0;
431 errCode = SQLiteUtils::StepWithRetry(stmt, false);
432 if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
433 count = sqlite3_column_int(stmt, 0);
434 LOGI("[RDBGeneralUt] Count table %s success exist %d data dev %s", table.c_str(), count, dev.c_str());
435 } else {
436 LOGE("[RDBGeneralUt] Count table %s failed by %d dev %s", table.c_str(), errCode, dev.c_str());
437 }
438
439 int ret = E_OK;
440 SQLiteUtils::ResetStatement(stmt, true, ret);
441 return count;
442 }
443
SetTrackerTables(const StoreInfo & info,const std::vector<std::string> & tables,bool isForce)444 int RDBGeneralUt::SetTrackerTables(const StoreInfo &info, const std::vector<std::string> &tables, bool isForce)
445 {
446 auto store = GetDelegate(info);
447 if (store == nullptr) {
448 LOGE("[RDBGeneralUt] Get null delegate when set tracker tables");
449 return -E_INVALID_DB;
450 }
451 auto trackerSchema = GetAllTrackerSchema(info, tables);
452 for (const auto &trackerTable : trackerSchema) {
453 auto temp = trackerTable;
454 temp.isForceUpgrade = isForce;
455 auto errCode = store->SetTrackerTable(temp);
456 if (errCode != E_OK) {
457 LOGE("[RDBGeneralUt] Set tracker table %s failed %d app %s store %s user %s",
458 trackerTable.tableName.c_str(), errCode,
459 info.appId.c_str(), info.storeId.c_str(), info.userId.c_str());
460 return errCode;
461 }
462 }
463 LOGI("[RDBGeneralUt] Set tracker %zu table success app %s store %s user %s",
464 trackerSchema.size(), info.appId.c_str(), info.storeId.c_str(), info.userId.c_str());
465 return E_OK;
466 }
467
GetVirtualCloudDb() const468 std::shared_ptr<VirtualCloudDb> RDBGeneralUt::GetVirtualCloudDb() const
469 {
470 std::lock_guard<std::mutex> autoLock(storeMutex_);
471 return virtualCloudDb_;
472 }
473
GetVirtualAssetLoader() const474 std::shared_ptr<VirtualAssetLoader> RDBGeneralUt::GetVirtualAssetLoader() const
475 {
476 std::lock_guard<std::mutex> autoLock(storeMutex_);
477 return virtualAssetLoader_;
478 }
479
SetCloudDbConfig(const StoreInfo & info) const480 void RDBGeneralUt::SetCloudDbConfig(const StoreInfo &info) const
481 {
482 auto delegate = GetDelegate(info);
483 ASSERT_NE(delegate, nullptr);
484 std::shared_ptr<VirtualCloudDb> virtualCloudDb = GetVirtualCloudDb();
485 std::shared_ptr<VirtualAssetLoader> virtualAssetLoader = GetVirtualAssetLoader();
486 ASSERT_NE(virtualCloudDb, nullptr);
487 ASSERT_NE(virtualAssetLoader, nullptr);
488 ASSERT_EQ(delegate->SetCloudDB(virtualCloudDb), DBStatus::OK);
489 ASSERT_EQ(delegate->SetIAssetLoader(virtualAssetLoader), DBStatus::OK);
490 ASSERT_EQ(delegate->SetCloudDbSchema(GetSchema(info)), DBStatus::OK);
491 LOGI("[RDBGeneralUt] Set cloud db config success, app %s store %s user %s", info.appId.c_str(),
492 info.storeId.c_str(), info.userId.c_str());
493 }
494
CloudBlockSync(const StoreInfo & info,const Query & query,DBStatus exceptStatus,DBStatus callbackExpect)495 void RDBGeneralUt::CloudBlockSync(const StoreInfo &info, const Query &query, DBStatus exceptStatus,
496 DBStatus callbackExpect)
497 {
498 LOGI("[RDBGeneralUt] Begin cloud sync, app %s store %s user %s", info.appId.c_str(),
499 info.storeId.c_str(), info.userId.c_str());
500 auto delegate = GetDelegate(info);
501 ASSERT_NE(delegate, nullptr);
502 RelationalTestUtils::CloudBlockSync(query, delegate, exceptStatus, callbackExpect);
503 }
504
GetCloudDataCount(const std::string & tableName) const505 int RDBGeneralUt::GetCloudDataCount(const std::string &tableName) const
506 {
507 VBucket extend;
508 extend[CloudDbConstant::CURSOR_FIELD] = std::to_string(0);
509 int realCount = 0;
510 std::vector<VBucket> data;
511 std::shared_ptr<VirtualCloudDb> virtualCloudDb = GetVirtualCloudDb();
512 if (virtualCloudDb == nullptr) {
513 LOGE("[RDBGeneralUt] virtual cloud db is nullptr");
514 return -1;
515 }
516 virtualCloudDb->Query(tableName, extend, data);
517 for (size_t j = 0; j < data.size(); ++j) {
518 auto entry = data[j].find(CloudDbConstant::DELETE_FIELD);
519 if (entry != data[j].end() && std::get<bool>(entry->second)) {
520 continue;
521 }
522 realCount++;
523 }
524 LOGI("[RDBGeneralUt] Count cloud table %s success, count %d", tableName.c_str(), realCount);
525 return realCount;
526 }
527
SetIsDbEncrypted(bool isdbEncrypted)528 void RDBGeneralUt::SetIsDbEncrypted(bool isdbEncrypted)
529 {
530 isDbEncrypted_ = isdbEncrypted;
531 }
532
GetIsDbEncrypted() const533 bool RDBGeneralUt::GetIsDbEncrypted() const
534 {
535 return isDbEncrypted_;
536 }
537
EncryptedDb(sqlite3 * db)538 int RDBGeneralUt::EncryptedDb(sqlite3 *db)
539 {
540 std::string passwd(PASSWD_VECTOR.begin(), PASSWD_VECTOR.end());
541 int rc = sqlite3_key(db, passwd.c_str(), passwd.size());
542 if (rc != SQLITE_OK) {
543 sqlite3_close(db);
544 LOGE("sqlite3_key failed, %d, passwd is %s.", rc, passwd.c_str());
545 return -E_INVALID_DB;
546 }
547 char *errMsg = nullptr;
548 int errCode = sqlite3_exec(db, CIPHER_CONFIG_SQL.c_str(), nullptr, nullptr, &errMsg);
549 if (errCode != SQLITE_OK || errMsg != nullptr) {
550 LOGE("set cipher failed: %d, cipher is %s.", errCode, CIPHER_CONFIG_SQL.c_str());
551 sqlite3_close(db);
552 sqlite3_free(errMsg);
553 return -E_INVALID_DB;
554 }
555 errMsg = nullptr;
556 errCode = sqlite3_exec(db, KDF_ITER_CONFIG_SQL.c_str(), nullptr, nullptr, &errMsg);
557 if (errCode != SQLITE_OK || errMsg != nullptr) {
558 LOGE("set iterTimes failed: %d, iterTimes is %s.", errCode, KDF_ITER_CONFIG_SQL.c_str());
559 sqlite3_close(db);
560 sqlite3_free(errMsg);
561 return -E_INVALID_DB;
562 }
563 errCode = sqlite3_exec(db, SHA256_ALGO_SQL.c_str(), nullptr, nullptr, &errMsg);
564 if (errCode != SQLITE_OK || errMsg != nullptr) {
565 LOGE("set codec_hmac_algo failed: %d, codec_hmac_algo is %s.", errCode, SHA256_ALGO_SQL.c_str());
566 sqlite3_close(db);
567 sqlite3_free(errMsg);
568 return -E_INVALID_DB;
569 }
570 return E_OK;
571 }
572
RemoteQuery(const StoreInfo & from,const StoreInfo & to,const std::string & sql,DBStatus expectRet)573 void RDBGeneralUt::RemoteQuery(const StoreInfo &from, const StoreInfo &to, const std::string &sql, DBStatus expectRet)
574 {
575 auto store = GetDelegate(from);
576 ASSERT_NE(store, nullptr);
577 auto toDevice = GetDevice(to);
578 ASSERT_FALSE(toDevice.empty());
579 RemoteCondition condition;
580 condition.sql = sql;
581 std::shared_ptr<ResultSet> resultSet = nullptr;
582 EXPECT_EQ(store->RemoteQuery(toDevice, condition, DBConstant::MAX_TIMEOUT, resultSet), expectRet);
583 EXPECT_NE(resultSet, nullptr);
584 }
585
PutMetaData(const StoreInfo & store,const Key & key,const Value & value)586 int RDBGeneralUt::PutMetaData(const StoreInfo &store, const Key &key, const Value &value)
587 {
588 auto db = GetSqliteHandle(store);
589 if (db == nullptr) {
590 LOGE("[RDBGeneralUt] Get null sqlite when put meta data userId[%s] appId[%s] storeId[%s]",
591 store.userId.c_str(), store.appId.c_str(), store.storeId.c_str());
592 return -E_INTERNAL_ERROR;
593 }
594 return SQLiteRelationalUtils::PutKvData(db, false, key, value);
595 }
596 }