• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef RELATIONAL_STORE
16 #include <gtest/gtest.h>
17 
18 #include "db_common.h"
19 #include "db_constant.h"
20 #include "distributeddb_data_generate_unit_test.h"
21 #include "distributeddb_tools_unit_test.h"
22 #include "isyncer.h"
23 #include "kv_virtual_device.h"
24 #include "mock_sync_task_context.h"
25 #include "platform_specific.h"
26 #include "process_system_api_adapter_impl.h"
27 #include "relational_schema_object.h"
28 #include "relational_store_manager.h"
29 #include "relational_virtual_device.h"
30 #include "runtime_config.h"
31 #include "single_ver_sync_target.h"
32 #include "virtual_relational_ver_sync_db_interface.h"
33 
34 using namespace testing::ext;
35 using namespace DistributedDB;
36 using namespace DistributedDBUnitTest;
37 namespace {
38     const std::string DEVICE_A = "real_device";
39     const std::string DEVICE_B = "deviceB";
40     const std::string DEVICE_C = "deviceC";
41     const std::string DEVICE_D = "deviceD";
42     const std::string g_tableName = "TEST_TABLE";
43 
44     const int ONE_HUNDERED = 100;
45     const char DEFAULT_CHAR = 'D';
46     const std::string DEFAULT_TEXT = "This is a text";
47     const std::vector<uint8_t> DEFAULT_BLOB(ONE_HUNDERED, DEFAULT_CHAR);
48     const std::string SHA1_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA1";
49     const std::string SHA256_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA256";
50     const std::string SHA256_ALGO_REKEY_SQL = "PRAGMA codec_rekey_hmac_algo=SHA256";
51 
52 #ifndef OMIT_ENCRYPT
53     bool g_isAfterRekey = false;
54     const string CORRECT_KEY = "a correct key";
55     CipherPassword g_correctPasswd;
56     const string REKEY_KEY = "a key after rekey";
57     CipherPassword g_rekeyPasswd;
58     const string INCORRECT_KEY = "a incorrect key";
59     CipherPassword g_incorrectPasswd;
60     const int DEFAULT_ITER = 5000;
61 #endif
62     RelationalStoreManager g_mgr(APP_ID, USER_ID);
63     std::string g_testDir;
64     std::string g_dbDir;
65     std::string g_id;
66     std::vector<StorageType> g_storageType = {
67         StorageType::STORAGE_TYPE_INTEGER, StorageType::STORAGE_TYPE_REAL,
68         StorageType::STORAGE_TYPE_TEXT, StorageType::STORAGE_TYPE_BLOB
69     };
70     DistributedDBToolsUnitTest g_tool;
71     RelationalStoreDelegate* g_rdbDelegatePtr = nullptr;
72     VirtualCommunicatorAggregator* g_communicatorAggregator = nullptr;
73     RelationalVirtualDevice *g_deviceB = nullptr;
74     RelationalVirtualDevice *g_deviceC = nullptr;
75     KvVirtualDevice *g_deviceD = nullptr;
76     std::vector<FieldInfo> g_fieldInfoList;
77     RelationalStoreObserverUnitTest *g_observer = nullptr;
GetDeviceTableName(const std::string & tableName)78     std::string GetDeviceTableName(const std::string &tableName)
79     {
80         return "naturalbase_rdb_aux_" +
81             tableName + "_" + DBCommon::TransferStringToHex(DBCommon::TransferHashString(DEVICE_B));
82     }
83 
OpenStore()84     void OpenStore()
85     {
86         if (g_observer == nullptr) {
87             g_observer = new (std::nothrow) RelationalStoreObserverUnitTest();
88         }
89         RelationalStoreDelegate::Option option;
90         option.observer = g_observer;
91 #ifndef OMIT_ENCRYPT
92         option.isEncryptedDb = true;
93         option.iterateTimes = DEFAULT_ITER;
94         option.passwd = g_isAfterRekey ? g_rekeyPasswd : g_correctPasswd;
95         option.cipher = CipherType::DEFAULT;
96 #endif
97         g_mgr.OpenStore(g_dbDir, STORE_ID_1, option, g_rdbDelegatePtr);
98         ASSERT_TRUE(g_rdbDelegatePtr != nullptr);
99     }
100 
GetDB(sqlite3 * & db,bool isSha256Algo=true)101     int GetDB(sqlite3 *&db, bool isSha256Algo = true)
102     {
103         int flag = SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
104         const auto &dbPath = g_dbDir;
105         int rc = sqlite3_open_v2(dbPath.c_str(), &db, flag, nullptr);
106         if (rc != SQLITE_OK) {
107             return rc;
108         }
109 #ifndef OMIT_ENCRYPT
110         string sql =
111             "PRAGMA key='" + (g_isAfterRekey ? REKEY_KEY : CORRECT_KEY) + "';"
112             "PRAGMA codec_kdf_iter=" + std::to_string(DEFAULT_ITER) + ";";
113         EXPECT_EQ(sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr), SQLITE_OK);
114         if (isSha256Algo) {
115             EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_SQL), E_OK);
116         } else {
117             EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA1_ALGO_SQL), E_OK);
118         }
119         EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_REKEY_SQL), E_OK);
120 #endif
121         EXPECT_EQ(SQLiteUtils::RegisterCalcHash(db), E_OK);
122         EXPECT_EQ(SQLiteUtils::RegisterGetSysTime(db), E_OK);
123         EXPECT_EQ(sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr), SQLITE_OK);
124         return rc;
125     }
126 
GetType(StorageType type)127     std::string GetType(StorageType type)
128     {
129         static std::map<StorageType, std::string> typeMap = {
130             {StorageType::STORAGE_TYPE_INTEGER, "INT"},
131             {StorageType::STORAGE_TYPE_REAL, "DOUBLE"},
132             {StorageType::STORAGE_TYPE_TEXT, "TEXT"},
133             {StorageType::STORAGE_TYPE_BLOB, "BLOB"}
134         };
135         if (typeMap.find(type) == typeMap.end()) {
136             type = StorageType::STORAGE_TYPE_INTEGER;
137         }
138         return typeMap[type];
139     }
140 
DropTable(sqlite3 * db,const std::string & tableName)141     int DropTable(sqlite3 *db, const std::string &tableName)
142     {
143         std::string sql = "DROP TABLE " + tableName + ";";
144         return sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr);
145     }
146 
CreateTable(sqlite3 * db,const std::vector<FieldInfo> & fieldInfoList,const std::string & tableName)147     int CreateTable(sqlite3 *db, const std::vector<FieldInfo> &fieldInfoList, const std::string &tableName)
148     {
149         std::string sql = "CREATE TABLE " + tableName + "(";
150         int index = 0;
151         for (const auto &field : fieldInfoList) {
152             if (index != 0) {
153                 sql += ",";
154             }
155             sql += field.GetFieldName() + " ";
156             std::string type = GetType(field.GetStorageType());
157             sql += type + " ";
158             if (index == 0) {
159                 sql += "PRIMARY KEY NOT NULL ";
160             }
161             index++;
162         }
163         sql += ");";
164         int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr);
165         return rc;
166     }
167 
PrepareInsert(sqlite3 * db,sqlite3_stmt * & statement,std::vector<FieldInfo> fieldInfoList,const std::string & tableName)168     int PrepareInsert(sqlite3 *db, sqlite3_stmt *&statement,
169         std::vector<FieldInfo> fieldInfoList, const std::string &tableName)
170     {
171         std::string sql = "INSERT OR REPLACE INTO " + tableName + "(";
172         int index = 0;
173         for (const auto &fieldInfo : fieldInfoList) {
174             if (index != 0) {
175                 sql += ",";
176             }
177             sql += fieldInfo.GetFieldName();
178             index++;
179         }
180         sql += ") VALUES (";
181         while (index > 0) {
182             sql += "?";
183             if (index != 1) {
184                 sql += ", ";
185             }
186             index--;
187         }
188         sql += ");";
189         return sqlite3_prepare_v2(db, sql.c_str(), -1, &statement, nullptr);
190     }
191 
SimulateCommitData(sqlite3 * db,sqlite3_stmt * & statement)192     int SimulateCommitData(sqlite3 *db, sqlite3_stmt *&statement)
193     {
194         sqlite3_exec(db, "BEGIN IMMEDIATE TRANSACTION", nullptr, nullptr, nullptr);
195 
196         int rc = sqlite3_step(statement);
197 
198         sqlite3_exec(db, "COMMIT TRANSACTION", nullptr, nullptr, nullptr);
199         return rc;
200     }
201 
BindValue(const DataValue & item,sqlite3_stmt * stmt,int col)202     void BindValue(const DataValue &item, sqlite3_stmt *stmt, int col)
203     {
204         switch (item.GetType()) {
205             case StorageType::STORAGE_TYPE_INTEGER: {
206                 int64_t intData = 0;
207                 (void)item.GetInt64(intData);
208                 EXPECT_EQ(sqlite3_bind_int64(stmt, col, intData), SQLITE_OK);
209                 break;
210             }
211 
212             case StorageType::STORAGE_TYPE_REAL: {
213                 double doubleData = 0;
214                 (void)item.GetDouble(doubleData);
215                 EXPECT_EQ(sqlite3_bind_double(stmt, col, doubleData), SQLITE_OK);
216                 break;
217             }
218 
219             case StorageType::STORAGE_TYPE_TEXT: {
220                 std::string strData;
221                 (void)item.GetText(strData);
222                 EXPECT_EQ(SQLiteUtils::BindTextToStatement(stmt, col, strData), E_OK);
223                 break;
224             }
225 
226             case StorageType::STORAGE_TYPE_BLOB: {
227                 Blob blob;
228                 (void)item.GetBlob(blob);
229                 std::vector<uint8_t> blobData(blob.GetData(), blob.GetData() + blob.GetSize());
230                 EXPECT_EQ(SQLiteUtils::BindBlobToStatement(stmt, col, blobData, true), E_OK);
231                 break;
232             }
233 
234             case StorageType::STORAGE_TYPE_NULL: {
235                 EXPECT_EQ(SQLiteUtils::MapSQLiteErrno(sqlite3_bind_null(stmt, col)), E_OK);
236                 break;
237             }
238 
239             default:
240                 break;
241         }
242     }
243 
InsertValue(sqlite3 * db,std::map<std::string,DataValue> & dataMap,const std::vector<FieldInfo> & fieldInfoList,const std::string & tableName)244     void InsertValue(sqlite3 *db, std::map<std::string, DataValue> &dataMap,
245         const std::vector<FieldInfo> &fieldInfoList, const std::string &tableName)
246     {
247         sqlite3_stmt *stmt = nullptr;
248         EXPECT_EQ(PrepareInsert(db, stmt, fieldInfoList, tableName), SQLITE_OK);
249         for (int i = 0; i < static_cast<int>(fieldInfoList.size()); ++i) {
250             const auto &fieldName = fieldInfoList[i].GetFieldName();
251             ASSERT_TRUE(dataMap.find(fieldName) != dataMap.end());
252             const auto &item = dataMap[fieldName];
253             const int index = i + 1;
254             BindValue(item, stmt, index);
255         }
256         EXPECT_EQ(SimulateCommitData(db, stmt), SQLITE_DONE);
257         sqlite3_finalize(stmt);
258     }
259 
InsertValue(sqlite3 * db,std::map<std::string,DataValue> & dataMap)260     void InsertValue(sqlite3 *db, std::map<std::string, DataValue> &dataMap)
261     {
262         InsertValue(db, dataMap, g_fieldInfoList, g_tableName);
263     }
264 
SetNull(DataValue & dataValue)265     void SetNull(DataValue &dataValue)
266     {
267         dataValue.ResetValue();
268     }
269 
SetInt64(DataValue & dataValue)270     void SetInt64(DataValue &dataValue)
271     {
272         dataValue = INT64_MAX;
273     }
274 
SetDouble(DataValue & dataValue)275     void SetDouble(DataValue &dataValue)
276     {
277         dataValue = 1.0;
278     }
279 
SetText(DataValue & dataValue)280     void SetText(DataValue &dataValue)
281     {
282         dataValue.SetText(DEFAULT_TEXT);
283     }
284 
SetBlob(DataValue & dataValue)285     void SetBlob(DataValue &dataValue)
286     {
287         Blob blob;
288         blob.WriteBlob(DEFAULT_BLOB.data(), DEFAULT_BLOB.size());
289         dataValue.SetBlob(blob);
290     }
291 
GenerateValue(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> & fieldInfoList)292     void GenerateValue(std::map<std::string, DataValue> &dataMap, std::vector<FieldInfo> &fieldInfoList)
293     {
294         static std::map<StorageType, void(*)(DataValue&)> typeMapFunction = {
295             {StorageType::STORAGE_TYPE_NULL,    &SetNull},
296             {StorageType::STORAGE_TYPE_INTEGER, &SetInt64},
297             {StorageType::STORAGE_TYPE_REAL,    &SetDouble},
298             {StorageType::STORAGE_TYPE_TEXT,    &SetText},
299             {StorageType::STORAGE_TYPE_BLOB,    &SetBlob}
300         };
301         for (auto &fieldInfo : fieldInfoList) {
302             DataValue dataValue;
303             if (typeMapFunction.find(fieldInfo.GetStorageType()) == typeMapFunction.end()) {
304                 fieldInfo.SetStorageType(StorageType::STORAGE_TYPE_NULL);
305             }
306             typeMapFunction[fieldInfo.GetStorageType()](dataValue);
307             dataMap[fieldInfo.GetFieldName()] = std::move(dataValue);
308         }
309     }
310 
InsertFieldInfo(std::vector<FieldInfo> & fieldInfoList)311     void InsertFieldInfo(std::vector<FieldInfo> &fieldInfoList)
312     {
313         fieldInfoList.clear();
314         FieldInfo columnFirst;
315         columnFirst.SetFieldName("ID");
316         columnFirst.SetStorageType(StorageType::STORAGE_TYPE_INTEGER);
317         columnFirst.SetColumnId(0); // the first column
318         FieldInfo columnSecond;
319         columnSecond.SetFieldName("NAME");
320         columnSecond.SetStorageType(StorageType::STORAGE_TYPE_TEXT);
321         columnSecond.SetColumnId(1); // the 2nd column
322         FieldInfo columnThird;
323         columnThird.SetFieldName("AGE");
324         columnThird.SetStorageType(StorageType::STORAGE_TYPE_INTEGER);
325         columnThird.SetColumnId(2); // the 3rd column(index 2 base 0)
326         fieldInfoList.push_back(columnFirst);
327         fieldInfoList.push_back(columnSecond);
328         fieldInfoList.push_back(columnThird);
329     }
330 
BlockSync(const Query & query,SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)331     void BlockSync(const Query &query, SyncMode syncMode, DBStatus exceptStatus,
332         const std::vector<std::string> &devices)
333     {
334         std::map<std::string, std::vector<TableStatus>> statusMap;
335         SyncStatusCallback callBack = [&statusMap](
336             const std::map<std::string, std::vector<TableStatus>> &devicesMap) {
337             statusMap = devicesMap;
338         };
339         DBStatus callStatus = g_rdbDelegatePtr->Sync(devices, syncMode, query, callBack, true);
340         EXPECT_EQ(callStatus, OK);
341         for (const auto &tablesRes : statusMap) {
342             for (const auto &tableStatus : tablesRes.second) {
343                 EXPECT_EQ(tableStatus.status, exceptStatus);
344             }
345         }
346     }
347 
BlockSync(const std::string & tableName,SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)348     void BlockSync(const std::string &tableName, SyncMode syncMode, DBStatus exceptStatus,
349         const std::vector<std::string> &devices)
350     {
351         Query query = Query::Select(tableName);
352         BlockSync(query, syncMode, exceptStatus, devices);
353     }
354 
BlockSync(SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)355     void BlockSync(SyncMode syncMode, DBStatus exceptStatus, const std::vector<std::string> &devices)
356     {
357         BlockSync(g_tableName, syncMode, exceptStatus, devices);
358     }
359 
PrepareSelect(sqlite3 * db,sqlite3_stmt * & statement,const std::string & table)360     int PrepareSelect(sqlite3 *db, sqlite3_stmt *&statement, const std::string &table)
361     {
362         const std::string sql = "SELECT * FROM " + table;
363         return sqlite3_prepare_v2(db, sql.c_str(), -1, &statement, nullptr);
364     }
365 
GetDataValue(sqlite3_stmt * statement,int col,DataValue & dataValue)366     void GetDataValue(sqlite3_stmt *statement, int col, DataValue &dataValue)
367     {
368         int type = sqlite3_column_type(statement, col);
369         switch (type) {
370             case SQLITE_INTEGER: {
371                 dataValue = static_cast<int64_t>(sqlite3_column_int64(statement, col));
372                 break;
373             }
374             case SQLITE_FLOAT: {
375                 dataValue = sqlite3_column_double(statement, col);
376                 break;
377             }
378             case SQLITE_TEXT: {
379                 std::string str;
380                 SQLiteUtils::GetColumnTextValue(statement, col, str);
381                 dataValue.SetText(str);
382                 break;
383             }
384             case SQLITE_BLOB: {
385                 std::vector<uint8_t> blobValue;
386                 (void)SQLiteUtils::GetColumnBlobValue(statement, col, blobValue);
387                 Blob blob;
388                 blob.WriteBlob(blobValue.data(), static_cast<uint32_t>(blobValue.size()));
389                 dataValue.SetBlob(blob);
390                 break;
391             }
392             case SQLITE_NULL:
393                 break;
394             default:
395                 LOGW("unknown type[%d] column[%d] ignore", type, col);
396         }
397     }
398 
GetSyncDataStep(std::map<std::string,DataValue> & dataMap,sqlite3_stmt * statement,const std::vector<FieldInfo> & fieldInfoList)399     void GetSyncDataStep(std::map<std::string, DataValue> &dataMap, sqlite3_stmt *statement,
400         const std::vector<FieldInfo> &fieldInfoList)
401     {
402         int columnCount = sqlite3_column_count(statement);
403         ASSERT_EQ(static_cast<size_t>(columnCount), fieldInfoList.size());
404         for (int col = 0; col < columnCount; ++col) {
405             DataValue dataValue;
406             GetDataValue(statement, col, dataValue);
407             dataMap[fieldInfoList.at(col).GetFieldName()] = std::move(dataValue);
408         }
409     }
410 
GetSyncData(sqlite3 * db,std::map<std::string,DataValue> & dataMap,const std::string & tableName,const std::vector<FieldInfo> & fieldInfoList)411     void GetSyncData(sqlite3 *db, std::map<std::string, DataValue> &dataMap, const std::string &tableName,
412         const std::vector<FieldInfo> &fieldInfoList)
413     {
414         sqlite3_stmt *statement = nullptr;
415         EXPECT_EQ(PrepareSelect(db, statement, GetDeviceTableName(tableName)), SQLITE_OK);
416         while (true) {
417             int rc = sqlite3_step(statement);
418             if (rc != SQLITE_ROW) {
419                 LOGD("GetSyncData Exist by code[%d]", rc);
420                 break;
421             }
422             GetSyncDataStep(dataMap, statement, fieldInfoList);
423         }
424         sqlite3_finalize(statement);
425     }
426 
InsertValueToDB(std::map<std::string,DataValue> & dataMap)427     void InsertValueToDB(std::map<std::string, DataValue> &dataMap)
428     {
429         sqlite3 *db = nullptr;
430         EXPECT_EQ(GetDB(db), SQLITE_OK);
431         InsertValue(db, dataMap);
432         sqlite3_close(db);
433     }
434 
PrepareBasicTable(const std::string & tableName,std::vector<FieldInfo> & fieldInfoList,const std::vector<RelationalVirtualDevice * > & remoteDeviceVec,bool createDistributedTable=true)435     void PrepareBasicTable(const std::string &tableName, std::vector<FieldInfo> &fieldInfoList,
436         const std::vector<RelationalVirtualDevice *> &remoteDeviceVec, bool createDistributedTable = true)
437     {
438         sqlite3 *db = nullptr;
439         EXPECT_EQ(GetDB(db), SQLITE_OK);
440         if (fieldInfoList.empty()) {
441             InsertFieldInfo(fieldInfoList);
442         }
443         for (auto &dev : remoteDeviceVec) {
444             dev->SetLocalFieldInfo(fieldInfoList);
445         }
446         EXPECT_EQ(CreateTable(db, fieldInfoList, tableName), SQLITE_OK);
447         TableInfo tableInfo;
448         SQLiteUtils::AnalysisSchema(db, tableName, tableInfo);
449         for (auto &dev : remoteDeviceVec) {
450             dev->SetTableInfo(tableInfo);
451         }
452         if (createDistributedTable) {
453             EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK);
454         }
455 
456         sqlite3_close(db);
457     }
458 
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,std::vector<RelationalVirtualDevice * > remoteDeviceVec)459     void PrepareEnvironment(std::map<std::string, DataValue> &dataMap,
460         std::vector<RelationalVirtualDevice *> remoteDeviceVec)
461     {
462         PrepareBasicTable(g_tableName, g_fieldInfoList, remoteDeviceVec);
463         GenerateValue(dataMap, g_fieldInfoList);
464         InsertValueToDB(dataMap);
465     }
466 
PrepareVirtualEnvironment(std::map<std::string,DataValue> & dataMap,const std::string & tableName,std::vector<FieldInfo> & fieldInfoList,const std::vector<RelationalVirtualDevice * > remoteDeviceVec,bool createDistributedTable=true)467     void PrepareVirtualEnvironment(std::map<std::string, DataValue> &dataMap, const std::string &tableName,
468         std::vector<FieldInfo> &fieldInfoList, const std::vector<RelationalVirtualDevice *> remoteDeviceVec,
469         bool createDistributedTable = true)
470     {
471         PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec, createDistributedTable);
472         GenerateValue(dataMap, fieldInfoList);
473         VirtualRowData virtualRowData;
474         for (const auto &item : dataMap) {
475             virtualRowData.objectData.PutDataValue(item.first, item.second);
476         }
477         virtualRowData.logInfo.timestamp = 1;
478         g_deviceB->PutData(tableName, {virtualRowData});
479     }
480 
PrepareVirtualEnvironment(std::map<std::string,DataValue> & dataMap,const std::vector<RelationalVirtualDevice * > remoteDeviceVec,bool createDistributedTable=true)481     void PrepareVirtualEnvironment(std::map<std::string, DataValue> &dataMap,
482         const std::vector<RelationalVirtualDevice *> remoteDeviceVec, bool createDistributedTable = true)
483     {
484         PrepareVirtualEnvironment(dataMap, g_tableName, g_fieldInfoList, remoteDeviceVec, createDistributedTable);
485     }
486 
CheckData(const std::map<std::string,DataValue> & targetMap,const std::string & tableName,const std::vector<FieldInfo> & fieldInfoList)487     void CheckData(const std::map<std::string, DataValue> &targetMap, const std::string &tableName,
488         const std::vector<FieldInfo> &fieldInfoList)
489     {
490         std::map<std::string, DataValue> dataMap;
491         sqlite3 *db = nullptr;
492         EXPECT_EQ(GetDB(db), SQLITE_OK);
493         GetSyncData(db, dataMap, tableName, fieldInfoList);
494         sqlite3_close(db);
495 
496         for (const auto &[fieldName, dataValue] : targetMap) {
497             ASSERT_TRUE(dataMap.find(fieldName) != dataMap.end());
498             EXPECT_TRUE(dataMap[fieldName] == dataValue);
499         }
500     }
501 
CheckData(const std::map<std::string,DataValue> & targetMap)502     void CheckData(const std::map<std::string, DataValue> &targetMap)
503     {
504         CheckData(targetMap, g_tableName, g_fieldInfoList);
505     }
506 
CheckVirtualData(const std::string & tableName,std::map<std::string,DataValue> & data)507     void CheckVirtualData(const std::string &tableName, std::map<std::string, DataValue> &data)
508     {
509         std::vector<VirtualRowData> targetData;
510         g_deviceB->GetAllSyncData(tableName, targetData);
511         ASSERT_EQ(targetData.size(), 1u);
512         for (auto &[field, value] : data) {
513             DataValue target;
514             EXPECT_EQ(targetData[0].objectData.GetDataValue(field, target), E_OK);
515             LOGD("field %s actual_val[%s] except_val[%s]", field.c_str(), target.ToString().c_str(),
516                 value.ToString().c_str());
517             EXPECT_TRUE(target == value);
518         }
519     }
520 
CheckVirtualData(std::map<std::string,DataValue> & data)521     void CheckVirtualData(std::map<std::string, DataValue> &data)
522     {
523         CheckVirtualData(g_tableName, data);
524     }
525 
GetFieldInfo(std::vector<FieldInfo> & fieldInfoList,std::vector<StorageType> typeList)526     void GetFieldInfo(std::vector<FieldInfo> &fieldInfoList, std::vector<StorageType> typeList)
527     {
528         fieldInfoList.clear();
529         for (size_t index = 0; index < typeList.size(); index++) {
530             const auto &type = typeList[index];
531             FieldInfo fieldInfo;
532             fieldInfo.SetFieldName("field_" + std::to_string(index));
533             fieldInfo.SetColumnId(index);
534             fieldInfo.SetStorageType(type);
535             fieldInfoList.push_back(fieldInfo);
536         }
537     }
538 
InsertValueToDB(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> fieldInfoList,const std::string & tableName)539     void InsertValueToDB(std::map<std::string, DataValue> &dataMap,
540         std::vector<FieldInfo> fieldInfoList, const std::string &tableName)
541     {
542         sqlite3 *db = nullptr;
543         EXPECT_EQ(GetDB(db), SQLITE_OK);
544         InsertValue(db, dataMap, fieldInfoList, tableName);
545         sqlite3_close(db);
546     }
547 
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,const std::string & tableName,std::vector<FieldInfo> & localFieldInfoList,std::vector<FieldInfo> & remoteFieldInfoList,std::vector<RelationalVirtualDevice * > remoteDeviceVec)548     void PrepareEnvironment(std::map<std::string, DataValue> &dataMap, const std::string &tableName,
549         std::vector<FieldInfo> &localFieldInfoList, std::vector<FieldInfo> &remoteFieldInfoList,
550         std::vector<RelationalVirtualDevice *> remoteDeviceVec)
551     {
552         sqlite3 *db = nullptr;
553         EXPECT_EQ(GetDB(db), SQLITE_OK);
554 
555         EXPECT_EQ(CreateTable(db, remoteFieldInfoList, tableName), SQLITE_OK);
556         TableInfo tableInfo;
557         SQLiteUtils::AnalysisSchema(db, tableName, tableInfo);
558         for (auto &dev : remoteDeviceVec) {
559             dev->SetTableInfo(tableInfo);
560         }
561 
562         EXPECT_EQ(DropTable(db, tableName), SQLITE_OK);
563         EXPECT_EQ(CreateTable(db, localFieldInfoList, tableName), SQLITE_OK);
564         EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK);
565 
566         sqlite3_close(db);
567 
568         GenerateValue(dataMap, localFieldInfoList);
569         InsertValueToDB(dataMap, localFieldInfoList, tableName);
570         for (auto &dev : remoteDeviceVec) {
571             dev->SetLocalFieldInfo(remoteFieldInfoList);
572         }
573     }
574 
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> & localFieldInfoList,std::vector<FieldInfo> & remoteFieldInfoList,const std::vector<RelationalVirtualDevice * > remoteDeviceVec)575     void PrepareEnvironment(std::map<std::string, DataValue> &dataMap,
576         std::vector<FieldInfo> &localFieldInfoList, std::vector<FieldInfo> &remoteFieldInfoList,
577         const std::vector<RelationalVirtualDevice *> remoteDeviceVec)
578     {
579         PrepareEnvironment(dataMap, g_tableName, localFieldInfoList, remoteFieldInfoList, remoteDeviceVec);
580     }
581 
CheckIdentify(RelationalStoreObserverUnitTest * observer)582     void CheckIdentify(RelationalStoreObserverUnitTest *observer)
583     {
584         ASSERT_NE(observer, nullptr);
585         StoreProperty property = observer->GetStoreProperty();
586         EXPECT_EQ(property.appId, APP_ID);
587         EXPECT_EQ(property.storeId, STORE_ID_1);
588         EXPECT_EQ(property.userId, USER_ID);
589     }
590 
CheckSearchData(std::shared_ptr<ResultSet> result,std::map<std::string,DataValue> & dataMap)591     void CheckSearchData(std::shared_ptr<ResultSet> result, std::map<std::string, DataValue> &dataMap)
592     {
593         ASSERT_NE(result, nullptr);
594         EXPECT_EQ(result->GetCount(), 1);
595         ASSERT_TRUE(result->MoveToFirst());
596         std::vector<string> columnNames;
597         result->GetColumnNames(columnNames);
598         ASSERT_EQ(columnNames.size(), dataMap.size());
599         int index = 0;
600         for (auto &column : columnNames) {
601             ASSERT_TRUE(dataMap.find(column) != dataMap.end());
602             LOGD("now check %s", column.c_str());
603             if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_INTEGER) {
604                 int64_t expectVal = 0;
605                 dataMap[column].GetInt64(expectVal);
606                 int64_t actualVal = 0;
607                 ASSERT_EQ(result->Get(index, actualVal), OK);
608                 EXPECT_EQ(expectVal, actualVal);
609             } else if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_TEXT) {
610                 std::string expectVal = "";
611                 dataMap[column].GetText(expectVal);
612                 std::string actualVal = "";
613                 ASSERT_EQ(result->Get(index, actualVal), OK);
614                 EXPECT_EQ(expectVal, actualVal);
615             } else if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_REAL) {
616                 double expectVal = 0;
617                 dataMap[column].GetDouble(expectVal);
618                 double actualVal = 0;
619                 ASSERT_EQ(result->Get(index, actualVal), OK);
620                 EXPECT_EQ(expectVal, actualVal);
621             }
622             index++;
623         }
624     }
625 
GetCount(sqlite3 * db,const string & sql,size_t & count)626     int GetCount(sqlite3 *db, const string &sql, size_t &count)
627     {
628         sqlite3_stmt *stmt = nullptr;
629         int errCode = SQLiteUtils::GetStatement(db, sql, stmt);
630         if (errCode != E_OK) {
631             return errCode;
632         }
633         errCode = SQLiteUtils::StepWithRetry(stmt, false);
634         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
635             count = static_cast<size_t>(sqlite3_column_int64(stmt, 0));
636             errCode = E_OK;
637         }
638         SQLiteUtils::ResetStatement(stmt, true, errCode);
639         return errCode;
640     }
641 
GenerateSecurityData(std::vector<SecurityLabel> & labelList,std::vector<SecurityFlag> & flagList)642     void GenerateSecurityData(std::vector<SecurityLabel> &labelList, std::vector<SecurityFlag> &flagList)
643     {
644         labelList = {
645             SecurityLabel::NOT_SET, SecurityLabel::S0,
646             SecurityLabel::S1, SecurityLabel::S2,
647             SecurityLabel::S3, SecurityLabel::S4
648         };
649         flagList = {
650             SecurityFlag::ECE, SecurityFlag::SECE
651         };
652     }
653 
SelectSecurityOption(int & labelIndex,int & flagIndex,const std::vector<SecurityLabel> & labelList,const std::vector<SecurityFlag> & flagList)654     SecurityOption SelectSecurityOption(int &labelIndex, int &flagIndex,
655         const std::vector<SecurityLabel> &labelList, const std::vector<SecurityFlag> &flagList)
656     {
657         SecurityOption option;
658         if (labelIndex >= static_cast<int>(labelList.size()) || flagIndex >= static_cast<int>(flagList.size())) {
659             return option;
660         }
661         option.securityLabel = labelList[labelIndex];
662         option.securityFlag = flagList[flagIndex];
663         labelIndex++;
664         if (labelIndex >= static_cast<int>(labelList.size())) {
665             labelIndex = 0;
666             flagIndex++;
667         }
668         return option;
669     }
670 
SelectSecurityEnd(int flagIndex,const std::vector<SecurityFlag> & flagList)671     bool SelectSecurityEnd(int flagIndex, const std::vector<SecurityFlag> &flagList)
672     {
673         return flagIndex >= static_cast<int>(flagList.size());
674     }
675 
GetSecurityRes(const SecurityOption & localOption,const SecurityOption & remoteOption,bool checkDeviceResult)676     DBStatus GetSecurityRes(const SecurityOption &localOption, const SecurityOption &remoteOption,
677         bool checkDeviceResult)
678     {
679         if (!checkDeviceResult) {
680             return SECURITY_OPTION_CHECK_ERROR;
681         }
682         if (localOption.securityLabel == static_cast<int>(SecurityLabel::NOT_SET) ||
683             remoteOption.securityLabel == static_cast<int>(SecurityLabel::NOT_SET)) {
684             return OK;
685         }
686         if (localOption.securityLabel != remoteOption.securityLabel) {
687             return SECURITY_OPTION_CHECK_ERROR;
688         }
689         return OK;
690     }
691 
SyncWithSecurityCheck(const SecurityOption & localOption,const SecurityOption & remoteOption,bool remoteQuery,bool checkDeviceResult)692     void SyncWithSecurityCheck(const SecurityOption &localOption, const SecurityOption &remoteOption,
693         bool remoteQuery, bool checkDeviceResult)
694     {
695         std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
696         adapter->ForkCheckDeviceSecurityAbility(
697             [&localOption, &remoteOption, checkDeviceResult, remoteQuery](const std::string &devId,
698                 const SecurityOption &option) {
699             if (remoteQuery) {
700                 EXPECT_TRUE(remoteOption == option);
701                 EXPECT_EQ(devId, DEVICE_A);
702             } else {
703                 EXPECT_TRUE(localOption == option);
704             }
705             return checkDeviceResult;
706         });
707         adapter->ForkGetSecurityOption(
708             [&localOption, &remoteOption](const std::string &filePath, SecurityOption &option) {
709             if (filePath.empty()) {
710                 option = remoteOption;
711             } else {
712                 option = localOption;
713             }
714             return OK;
715         });
716         RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
717         DBStatus resStatus = GetSecurityRes(localOption, remoteOption, checkDeviceResult);
718         if (remoteQuery) {
719             RemoteCondition condition;
720             condition.sql = "SELECT * FROM " + g_tableName;
721             std::shared_ptr<ResultSet> result = nullptr;
722             ASSERT_NE(g_rdbDelegatePtr, nullptr);
723             EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), resStatus);
724         } else {
725             BlockSync(SYNC_MODE_PUSH_ONLY, resStatus, {DEVICE_B});
726         }
727         RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
728         LOGD("CloseStore Start");
729         ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
730         g_rdbDelegatePtr = nullptr;
731         OpenStore();
732     }
733 
TestWithSecurityCheck(bool remoteQuery)734     void TestWithSecurityCheck(bool remoteQuery)
735     {
736         /**
737          * @tc.steps: step1. create table and open store
738          * @tc.expected: step1. open store ok
739          */
740         std::map<std::string, DataValue> dataMap;
741         if (remoteQuery) {
742             PrepareEnvironment(dataMap, {g_deviceB});
743         } else {
744             PrepareVirtualEnvironment(dataMap, {g_deviceB});
745         }
746         ASSERT_NE(g_rdbDelegatePtr, nullptr);
747 
748         /**
749          * @tc.steps: step2. generate test data
750          */
751         std::vector<SecurityLabel> labelList;
752         std::vector<SecurityFlag> flagList;
753         int localLabelIndex = 0;
754         int localFlagIndex = 0;
755         GenerateSecurityData(labelList, flagList);
756 
757         // loop local
758         while (!SelectSecurityEnd(localFlagIndex, flagList)) {
759             SecurityOption localOption = SelectSecurityOption(localLabelIndex, localFlagIndex, labelList, flagList);
760             // loop remote
761             int remoteLabelIndex = 0;
762             int remoteFlagIndex = 0;
763             while (!SelectSecurityEnd(remoteFlagIndex, flagList)) {
764                 SecurityOption remoteOption = SelectSecurityOption(remoteLabelIndex, remoteFlagIndex,
765                     labelList, flagList);
766                 /**
767                  * @tc.steps: step3. call sync
768                  * @tc.expected: step3. sync result is based on security option
769                  */
770                 SyncWithSecurityCheck(localOption, remoteOption, remoteQuery, true);
771                 SyncWithSecurityCheck(localOption, remoteOption, remoteQuery, false);
772             }
773         }
774     }
775 
776 class DistributedDBRelationalVerP2PSyncTest : public testing::Test {
777 public:
778     static void SetUpTestCase();
779     static void TearDownTestCase();
780     void SetUp();
781     void TearDown();
782 };
783 
SetUpTestCase()784 void DistributedDBRelationalVerP2PSyncTest::SetUpTestCase()
785 {
786     /**
787     * @tc.setup: Init datadir and Virtual Communicator.
788     */
789     DistributedDBToolsUnitTest::TestDirInit(g_testDir);
790     g_dbDir = g_testDir + "/test.db";
791     sqlite3 *db = nullptr;
792     ASSERT_EQ(GetDB(db), SQLITE_OK);
793     sqlite3_close(db);
794 
795     g_communicatorAggregator = new (std::nothrow) VirtualCommunicatorAggregator();
796     ASSERT_TRUE(g_communicatorAggregator != nullptr);
797     RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator);
798 
799     g_id = g_mgr.GetRelationalStoreIdentifier(USER_ID, APP_ID, STORE_ID_1);
800 
801 #ifndef OMIT_ENCRYPT
802     g_correctPasswd.SetValue(reinterpret_cast<const uint8_t *>(CORRECT_KEY.data()), CORRECT_KEY.size());
803     g_rekeyPasswd.SetValue(reinterpret_cast<const uint8_t *>(REKEY_KEY.data()), REKEY_KEY.size());
804     g_incorrectPasswd.SetValue(reinterpret_cast<const uint8_t *>(INCORRECT_KEY.data()), INCORRECT_KEY.size());
805 #endif
806 }
807 
TearDownTestCase()808 void DistributedDBRelationalVerP2PSyncTest::TearDownTestCase()
809 {
810     /**
811     * @tc.teardown: Release virtual Communicator and clear data dir.
812     */
813     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
814         LOGE("rm test db files error!");
815     }
816     RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
817     LOGD("TearDownTestCase FINISH");
818 }
819 
SetUp(void)820 void DistributedDBRelationalVerP2PSyncTest::SetUp(void)
821 {
822     DistributedDBToolsUnitTest::PrintTestCaseInfo();
823     g_fieldInfoList.clear();
824     /**
825     * @tc.setup: create virtual device B, and get a KvStoreNbDelegate as deviceA
826     */
827     sqlite3 *db = nullptr;
828     ASSERT_EQ(GetDB(db), SQLITE_OK);
829     sqlite3_close(db);
830     OpenStore();
831     g_deviceB = new (std::nothrow) RelationalVirtualDevice(DEVICE_B);
832     ASSERT_TRUE(g_deviceB != nullptr);
833     g_deviceC = new (std::nothrow) RelationalVirtualDevice(DEVICE_C);
834     ASSERT_TRUE(g_deviceC != nullptr);
835     g_deviceD = new (std::nothrow) KvVirtualDevice(DEVICE_D);
836     ASSERT_TRUE(g_deviceD != nullptr);
837     auto *syncInterfaceB = new (std::nothrow) VirtualRelationalVerSyncDBInterface();
838     auto *syncInterfaceC = new (std::nothrow) VirtualRelationalVerSyncDBInterface();
839     auto *syncInterfaceD = new (std::nothrow) VirtualSingleVerSyncDBInterface();
840     ASSERT_TRUE(syncInterfaceB != nullptr);
841     ASSERT_TRUE(syncInterfaceC != nullptr);
842     ASSERT_TRUE(syncInterfaceD != nullptr);
843     ASSERT_EQ(g_deviceB->Initialize(g_communicatorAggregator, syncInterfaceB), E_OK);
844     ASSERT_EQ(g_deviceC->Initialize(g_communicatorAggregator, syncInterfaceC), E_OK);
845     ASSERT_EQ(g_deviceD->Initialize(g_communicatorAggregator, syncInterfaceD), E_OK);
846 
847     auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId, const std::string &storeId,
848         const std::string &deviceId, uint8_t flag) -> bool {
849         return true;
850     };
851     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
852 }
853 
TearDown(void)854 void DistributedDBRelationalVerP2PSyncTest::TearDown(void)
855 {
856     /**
857     * @tc.teardown: Release device A, B, C
858     */
859     if (g_rdbDelegatePtr != nullptr) {
860         LOGD("CloseStore Start");
861         ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
862         g_rdbDelegatePtr = nullptr;
863     }
864     if (g_deviceB != nullptr) {
865         delete g_deviceB;
866         g_deviceB = nullptr;
867     }
868     if (g_deviceC != nullptr) {
869         delete g_deviceC;
870         g_deviceC = nullptr;
871     }
872     if (g_deviceD != nullptr) {
873         delete g_deviceD;
874         g_deviceD = nullptr;
875     }
876     if (g_observer != nullptr) {
877         delete g_observer;
878         g_observer = nullptr;
879     }
880     PermissionCheckCallbackV2 nullCallback;
881     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(nullCallback), OK);
882     EXPECT_EQ(DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir), OK);
883     if (g_communicatorAggregator != nullptr) {
884         g_communicatorAggregator->RegOnDispatch(nullptr);
885     }
886     g_isAfterRekey = false;
887     LOGD("TearDown FINISH");
888 }
889 
890 /**
891 * @tc.name: Normal Sync 001
892 * @tc.desc: Test normal push sync for add data.
893 * @tc.type: FUNC
894 * @tc.require: AR000GK58N
895 * @tc.author: zhangqiquan
896 */
897 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync001, TestSize.Level0)
898 {
899     std::map<std::string, DataValue> dataMap;
900     PrepareEnvironment(dataMap, {g_deviceB});
901     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
902 
903     CheckVirtualData(dataMap);
904     DistributedDBToolsUnitTest::Dump();
905 }
906 
907 /**
908 * @tc.name: Normal Sync 002
909 * @tc.desc: Test normal pull sync for add data.
910 * @tc.type: FUNC
911 * @tc.require: AR000GK58N
912 * @tc.author: zhangqiquan
913 */
914 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync002, TestSize.Level0)
915 {
916     std::map<std::string, DataValue> dataMap;
917     PrepareEnvironment(dataMap, {g_deviceB});
918 
919     Query query = Query::Select(g_tableName);
920     g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, true);
921 
922     CheckVirtualData(dataMap);
923 }
924 
925 /**
926 * @tc.name: Normal Sync 003
927 * @tc.desc: Test normal push sync for update data.
928 * @tc.type: FUNC
929 * @tc.require: AR000GK58N
930 * @tc.author: zhangqiquan
931 */
932 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync003, TestSize.Level1)
933 {
934     std::map<std::string, DataValue> dataMap;
935     PrepareEnvironment(dataMap, {g_deviceB});
936 
937     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
938 
939     CheckVirtualData(dataMap);
940 
941     GenerateValue(dataMap, g_fieldInfoList);
942     dataMap["AGE"] = static_cast<int64_t>(1);
943     InsertValueToDB(dataMap);
944     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
945 
946     CheckVirtualData(dataMap);
947 }
948 
949 /**
950 * @tc.name: Normal Sync 004
951 * @tc.desc: Test normal push sync for delete data.
952 * @tc.type: FUNC
953 * @tc.require: AR000GK58N
954 * @tc.author: zhangqiquan
955 */
956 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync004, TestSize.Level1)
957 {
958     std::map<std::string, DataValue> dataMap;
959     PrepareEnvironment(dataMap, {g_deviceB});
960 
961     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
962 
963     CheckVirtualData(dataMap);
964 
965     sqlite3 *db = nullptr;
966     EXPECT_EQ(GetDB(db), SQLITE_OK);
967     std::string sql = "DELETE FROM TEST_TABLE WHERE 1 = 1";
968     EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK);
969     sqlite3_close(db);
970 
971     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
972 
973     std::vector<VirtualRowData> dataList;
974     EXPECT_EQ(g_deviceB->GetAllSyncData(g_tableName, dataList), E_OK);
975     EXPECT_EQ(static_cast<int>(dataList.size()), 0);
976 }
977 
978 /**
979 * @tc.name: Normal Sync 005
980 * @tc.desc: Test normal push sync for add data.
981 * @tc.type: FUNC
982 * @tc.require: AR000GK58N
983 * @tc.author: zhangqiquan
984 */
985 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync005, TestSize.Level0)
986 {
987     std::map<std::string, DataValue> dataMap;
988     PrepareVirtualEnvironment(dataMap, {g_deviceB});
989 
990     Query query = Query::Select(g_tableName);
991     g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
992 
993     CheckData(dataMap);
994 
995     g_rdbDelegatePtr->RemoveDeviceData(DEVICE_B);
996 
997     g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
998 
999     CheckData(dataMap);
1000 }
1001 
1002 /**
1003 * @tc.name: Normal Sync 006
1004 * @tc.desc: Test normal pull sync for add data.
1005 * @tc.type: FUNC
1006 * @tc.require: AR000GK58N
1007 * @tc.author: zhangqiquan
1008 */
1009 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync006, TestSize.Level1)
1010 {
1011     std::map<std::string, DataValue> dataMap;
1012     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1013 
1014     BlockSync(SYNC_MODE_PULL_ONLY, OK, {DEVICE_B});
1015 
1016     CheckData(dataMap);
1017 }
1018 
1019 /**
1020 * @tc.name: Normal Sync 007
1021 * @tc.desc: Test normal sync for miss query data.
1022 * @tc.type: FUNC
1023 * @tc.require: AR000GK58N
1024 * @tc.author: zhangqiquan
1025 */
1026 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync007, TestSize.Level1)
1027 {
1028     std::map<std::string, DataValue> dataMap;
1029     PrepareEnvironment(dataMap, {g_deviceB});
1030 
1031     Query query = Query::Select(g_tableName).EqualTo("NAME", DEFAULT_TEXT);
1032     BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1033 
1034     CheckVirtualData(dataMap);
1035 
1036     sqlite3 *db = nullptr;
1037     EXPECT_EQ(GetDB(db), SQLITE_OK);
1038     std::string sql = "UPDATE TEST_TABLE SET NAME = '' WHERE 1 = 1";
1039     EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK);
1040     sqlite3_close(db);
1041 
1042     BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1043 
1044     std::vector<VirtualRowData> dataList;
1045     EXPECT_EQ(g_deviceB->GetAllSyncData(g_tableName, dataList), E_OK);
1046     EXPECT_EQ(static_cast<int>(dataList.size()), 1);
1047     for (const auto &item : dataList) {
1048         EXPECT_EQ(item.logInfo.flag, DataItem::REMOTE_DEVICE_DATA_MISS_QUERY);
1049     }
1050 }
1051 
1052 /**
1053 * @tc.name: Normal Sync 008
1054 * @tc.desc: Test encry db sync for delete table;
1055 * @tc.type: FUNC
1056 * @tc.require: AR000GK58N
1057 * @tc.author: zhuwentao
1058 */
1059 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync008, TestSize.Level0)
1060 {
1061     /**
1062      * @tc.steps: step1. open rdb store, create distribute table, insert data and sync to deviceB
1063      */
1064     std::map<std::string, DataValue> dataMap;
1065     PrepareEnvironment(dataMap, {g_deviceB});
1066     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1067     CheckVirtualData(dataMap);
1068     /**
1069      * @tc.steps: step2.drop table operation and sync again
1070      */
1071     sqlite3 *db = nullptr;
1072     EXPECT_EQ(GetDB(db), SQLITE_OK);
1073     std::string dropTableSql = "drop table TEST_TABLE;";
1074     EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, dropTableSql), E_OK);
1075     std::vector<RelationalVirtualDevice *> remoteDeviceVec = {g_deviceB};
1076     PrepareBasicTable(g_tableName, g_fieldInfoList, remoteDeviceVec, true);
1077     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1078     /**
1079      * @tc.steps: step3.check data in deviceB
1080      */
1081     std::vector<VirtualRowData> targetData;
1082     g_deviceB->GetAllSyncData(g_tableName, targetData);
1083     ASSERT_EQ(targetData.size(), 0u);
1084     EXPECT_EQ(sqlite3_close_v2(db), SQLITE_OK);
1085 }
1086 
1087 /**
1088 * @tc.name: Normal Sync 009
1089 * @tc.desc: Test normal push sync for while create distribute table
1090 * @tc.type: FUNC
1091 * @tc.require: AR000GK58N
1092 * @tc.author: zhuwentao
1093 */
1094 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync009, TestSize.Level0)
1095 {
1096     std::map<std::string, DataValue> dataMap;
1097     PrepareEnvironment(dataMap, {g_deviceB});
1098 
1099     sqlite3 *db = nullptr;
1100     EXPECT_EQ(GetDB(db), SQLITE_OK);
1101     std::string sql = "alter table TEST_TABLE add column addr Text;";
1102     EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK);
1103     sqlite3_close(db);
1104 
1105     std::mutex syncMutex;
1106     std::condition_variable syncCv;
1107     std::mutex syncCallMutex;
1108     std::condition_variable syncCallCv;
1109     std::map<std::string, std::vector<TableStatus>> statusMap;
1110     SyncStatusCallback callBack = [&statusMap, &syncMutex, &syncCv](
__anon122cc5720602( const std::map<std::string, std::vector<TableStatus>> &devicesMap) 1111         const std::map<std::string, std::vector<TableStatus>> &devicesMap) {
1112         statusMap = devicesMap;
1113         std::unique_lock<std::mutex> lock(syncMutex);
1114         syncCv.notify_one();
1115     };
__anon122cc5720702null1116     std::thread t1([] {
1117         std::this_thread::sleep_for(std::chrono::milliseconds(10));
1118         g_rdbDelegatePtr->CreateDistributedTable(g_tableName);
1119     });
1120     DBStatus callStatus = OK;
__anon122cc5720802null1121     std::thread t2([&syncCallCv, &callBack, &callStatus] {
1122         Query query = Query::Select(g_tableName);
1123         callStatus = g_rdbDelegatePtr->Sync({DEVICE_B}, SYNC_MODE_PUSH_ONLY, query, callBack, false);
1124         syncCallCv.notify_one();
1125     });
1126     {
1127         std::unique_lock<std::mutex> callLock(syncCallMutex);
1128         syncCallCv.wait(callLock);
1129     }
1130     if (callStatus == OK) {
1131         std::unique_lock<std::mutex> lock(syncMutex);
1132         syncCv.wait(lock);
1133     }
1134     t1.join();
1135     t2.join();
1136 }
1137 
1138 /**
1139 * @tc.name: AutoLaunchSync 001
1140 * @tc.desc: Test rdb autoLaunch success when callback return true.
1141 * @tc.type: FUNC
1142 * @tc.require: AR000GK58N
1143 * @tc.author: zhangqiquan
1144 */
1145 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync001, TestSize.Level3)
1146 {
1147     /**
1148      * @tc.steps: step1. open rdb store, create distribute table and insert data
1149      */
1150     std::map<std::string, DataValue> dataMap;
1151     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1152 
1153     /**
1154      * @tc.steps: step2. set auto launch callBack
1155      */
1156     int currentStatus = 0;
1157     const AutoLaunchNotifier notifier = [&currentStatus](const std::string &userId,
__anon122cc5720902(const std::string &userId, const std::string &appId, const std::string &storeId, AutoLaunchStatus status) 1158         const std::string &appId, const std::string &storeId, AutoLaunchStatus status) {
1159         currentStatus = static_cast<int>(status);
1160     };
__anon122cc5720a02(const std::string &identifier, AutoLaunchParam &param) 1161     const AutoLaunchRequestCallback callback = [&notifier](const std::string &identifier, AutoLaunchParam &param) {
1162         if (g_id != identifier) {
1163             return false;
1164         }
1165         param.path    = g_dbDir;
1166         param.appId   = APP_ID;
1167         param.userId  = USER_ID;
1168         param.storeId = STORE_ID_1;
1169         param.notifier = notifier;
1170 #ifndef OMIT_ENCRYPT
1171         param.option.isEncryptedDb = true;
1172         param.option.cipher = CipherType::DEFAULT;
1173         param.option.passwd = g_correctPasswd;
1174         param.option.iterateTimes = DEFAULT_ITER;
1175 #endif
1176         return true;
1177     };
1178     g_mgr.SetAutoLaunchRequestCallback(callback);
1179     /**
1180      * @tc.steps: step3. close store ensure communicator has closed
1181      */
1182     g_mgr.CloseStore(g_rdbDelegatePtr);
1183     g_rdbDelegatePtr = nullptr;
1184     /**
1185      * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1186      */
1187     LabelType labelType(g_id.begin(), g_id.end());
1188     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1189     std::this_thread::sleep_for(std::chrono::seconds(1));
1190     EXPECT_EQ(currentStatus, 0);
1191     /**
1192      * @tc.steps: step5. Call sync expect sync successful
1193      */
1194     Query query = Query::Select(g_tableName);
1195     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1196     /**
1197      * @tc.steps: step6. check sync data ensure sync successful
1198      */
1199     CheckData(dataMap);
1200 
1201     OpenStore();
1202     RuntimeConfig::ReleaseAutoLaunch(USER_ID, APP_ID, STORE_ID_1, DBType::DB_RELATION);
1203 }
1204 
1205 /**
1206 * @tc.name: AutoLaunchSync 002
1207 * @tc.desc: Test rdb autoLaunch failed when callback return false.
1208 * @tc.type: FUNC
1209 * @tc.require: AR000GK58N
1210 * @tc.author: zhangqiquan
1211 */
1212 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync002, TestSize.Level3)
1213 {
1214     /**
1215      * @tc.steps: step1. open rdb store, create distribute table and insert data
1216      */
1217     std::map<std::string, DataValue> dataMap;
1218     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1219 
1220     /**
1221      * @tc.steps: step2. set auto launch callBack
1222      */
__anon122cc5720b02(const std::string &identifier, AutoLaunchParam &param) 1223     const AutoLaunchRequestCallback callback = [](const std::string &identifier, AutoLaunchParam &param) {
1224         return false;
1225     };
1226     g_mgr.SetAutoLaunchRequestCallback(callback);
1227     /**
1228      * @tc.steps: step2. close store ensure communicator has closed
1229      */
1230     g_mgr.CloseStore(g_rdbDelegatePtr);
1231     g_rdbDelegatePtr = nullptr;
1232     /**
1233      * @tc.steps: step3. store can't autoLaunch because callback return false
1234      */
1235     LabelType labelType(g_id.begin(), g_id.end());
1236     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1237     std::this_thread::sleep_for(std::chrono::seconds(1));
1238     /**
1239      * @tc.steps: step4. Call sync expect sync fail
1240      */
1241     Query query = Query::Select(g_tableName);
__anon122cc5720c02(const std::map<std::string, int> &statusMap) 1242     SyncOperation::UserCallback callBack = [](const std::map<std::string, int> &statusMap) {
1243         for (const auto &entry : statusMap) {
1244             EXPECT_EQ(entry.second, static_cast<int>(SyncOperation::OP_COMM_ABNORMAL));
1245         }
1246     };
1247     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, callBack, true), E_OK);
1248 
1249     OpenStore();
1250     std::this_thread::sleep_for(std::chrono::minutes(1));
1251 }
1252 
1253 /**
1254 * @tc.name: AutoLaunchSync 003
1255 * @tc.desc: Test rdb autoLaunch failed when callback is nullptr.
1256 * @tc.type: FUNC
1257 * @tc.require: AR000GK58N
1258 * @tc.author: zhangqiquan
1259 */
1260 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync003, TestSize.Level3)
1261 {
1262     /**
1263      * @tc.steps: step1. open rdb store, create distribute table and insert data
1264      */
1265     std::map<std::string, DataValue> dataMap;
1266     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1267 
1268     g_mgr.SetAutoLaunchRequestCallback(nullptr);
1269     /**
1270      * @tc.steps: step2. close store ensure communicator has closed
1271      */
1272     g_mgr.CloseStore(g_rdbDelegatePtr);
1273     g_rdbDelegatePtr = nullptr;
1274     /**
1275      * @tc.steps: step3. store can't autoLaunch because callback is nullptr
1276      */
1277     LabelType labelType(g_id.begin(), g_id.end());
1278     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1279     std::this_thread::sleep_for(std::chrono::seconds(1));
1280     /**
1281      * @tc.steps: step4. Call sync expect sync fail
1282      */
1283     Query query = Query::Select(g_tableName);
__anon122cc5720d02(const std::map<std::string, int> &statusMap) 1284     SyncOperation::UserCallback callBack = [](const std::map<std::string, int> &statusMap) {
1285         for (const auto &entry : statusMap) {
1286             EXPECT_EQ(entry.second, static_cast<int>(SyncOperation::OP_COMM_ABNORMAL));
1287         }
1288     };
1289     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, callBack, true), E_OK);
1290 
1291     OpenStore();
1292     std::this_thread::sleep_for(std::chrono::minutes(1));
1293 }
1294 
1295 
1296 /**
1297 * @tc.name: AutoLaunchSync 004
1298 * @tc.desc: Test invalid db type for autoLaunch.
1299 * @tc.type: FUNC
1300 * @tc.require:
1301 * @tc.author: zhangshijie
1302 */
1303 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync004, TestSize.Level3)
1304 {
1305     /**
1306      * @tc.steps: step1. open rdb store, create distribute table and insert data
1307      */
1308     std::map<std::string, DataValue> dataMap;
1309     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1310 
1311     /**
1312      * @tc.steps: step2. set auto launch callBack
1313      */
1314     int currentStatus = 0;
1315     const AutoLaunchNotifier notifier = [&currentStatus](const std::string &userId,
__anon122cc5720e02(const std::string &userId, const std::string &appId, const std::string &storeId, AutoLaunchStatus status) 1316         const std::string &appId, const std::string &storeId, AutoLaunchStatus status) {
1317         printf("SET STATUS = %d\n", static_cast<int>(status));
1318         currentStatus = static_cast<int>(status);
1319     };
__anon122cc5720f02(const std::string &identifier, AutoLaunchParam &param) 1320     const AutoLaunchRequestCallback callback = [&notifier](const std::string &identifier, AutoLaunchParam &param) {
1321         if (g_id != identifier) {
1322             return false;
1323         }
1324         param.path    = g_dbDir;
1325         param.appId   = APP_ID;
1326         param.userId  = USER_ID;
1327         param.storeId = STORE_ID_1;
1328         param.notifier = notifier;
1329 #ifndef OMIT_ENCRYPT
1330         param.option.isEncryptedDb = true;
1331         param.option.cipher = CipherType::DEFAULT;
1332         param.option.passwd = g_correctPasswd;
1333         param.option.iterateTimes = DEFAULT_ITER;
1334 #endif
1335             return true;
1336     };
1337     RuntimeConfig::SetAutoLaunchRequestCallback(callback, static_cast<DBType>(3)); // 3 is invalid db type
1338 
1339     /**
1340      * @tc.steps: step3. close store ensure communicator has closed
1341      */
1342     g_mgr.CloseStore(g_rdbDelegatePtr);
1343     g_rdbDelegatePtr = nullptr;
1344     /**
1345      * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1346      */
1347     LabelType labelType(g_id.begin(), g_id.end());
1348     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1349     std::this_thread::sleep_for(std::chrono::seconds(1));
1350     EXPECT_EQ(currentStatus, AutoLaunchStatus::INVALID_PARAM);
1351 }
1352 
1353 /**
1354 * @tc.name: Ability Sync 001
1355 * @tc.desc: Test ability sync success when has same schema.
1356 * @tc.type: FUNC
1357 * @tc.require: AR000GK58N
1358 * @tc.author: zhangqiquan
1359 */
1360 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync001, TestSize.Level1)
1361 {
1362     std::map<std::string, DataValue> dataMap;
1363     std::vector<FieldInfo> localFieldInfo;
1364     GetFieldInfo(localFieldInfo, g_storageType);
1365 
1366     PrepareEnvironment(dataMap, localFieldInfo, localFieldInfo, {g_deviceB});
1367     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1368 
1369     CheckVirtualData(dataMap);
1370 }
1371 
1372 /**
1373 * @tc.name: Ability Sync 002
1374 * @tc.desc: Test ability sync failed when has different schema.
1375 * @tc.type: FUNC
1376 * @tc.require: AR000GK58N
1377 * @tc.author: zhangqiquan
1378 */
1379 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync002, TestSize.Level1)
1380 {
1381     /**
1382      * @tc.steps: step1. set local schema is (BOOL, INTEGER, REAL, TEXT, BLOB, INTEGER)
1383      */
1384     std::map<std::string, DataValue> dataMap;
1385     std::vector<FieldInfo> localFieldInfo;
1386     std::vector<StorageType> localStorageType = g_storageType;
1387     localStorageType.push_back(StorageType::STORAGE_TYPE_INTEGER);
1388     GetFieldInfo(localFieldInfo, localStorageType);
1389 
1390     /**
1391      * @tc.steps: step2. set remote schema is (BOOL, INTEGER, REAL, TEXT, BLOB, TEXT)
1392      */
1393     std::vector<FieldInfo> remoteFieldInfo;
1394     std::vector<StorageType> remoteStorageType = g_storageType;
1395     remoteStorageType.push_back(StorageType::STORAGE_TYPE_TEXT);
1396     GetFieldInfo(remoteFieldInfo, remoteStorageType);
1397 
1398     /**
1399      * @tc.steps: step3. call sync
1400      * @tc.expected: sync fail when abilitySync
1401      */
1402     PrepareEnvironment(dataMap, localFieldInfo, remoteFieldInfo, {g_deviceB});
1403     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, SCHEMA_MISMATCH, {DEVICE_B});
1404 }
1405 
1406 /**
1407 * @tc.name: Ability Sync 003
1408 * @tc.desc: Test ability sync failed when has different schema.
1409 * @tc.type: FUNC
1410 * @tc.require: AR000GK58N
1411 * @tc.author: zhangqiquan
1412 */
1413 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync003, TestSize.Level1)
1414 {
1415     /**
1416      * @tc.steps: step1. set local and remote schema is (BOOL, INTEGER, REAL, TEXT, BLOB)
1417      */
1418     std::map<std::string, DataValue> dataMap;
1419     std::vector<FieldInfo> schema;
1420     std::vector<StorageType> localStorageType = g_storageType;
1421     GetFieldInfo(schema, localStorageType);
1422 
1423     /**
1424      * @tc.steps: step2. create table and insert data
1425      */
1426     PrepareEnvironment(dataMap, schema, schema, {g_deviceB});
1427 
1428     /**
1429      * @tc.steps: step3. change local table to (BOOL, INTEGER, REAL, TEXT, BLOB)
1430      * @tc.expected: sync fail
1431      */
__anon122cc5721002(const std::string &target, Message *inMsg) 1432     g_communicatorAggregator->RegOnDispatch([](const std::string &target, Message *inMsg) {
1433         if (target != "real_device") {
1434             return;
1435         }
1436         if (inMsg->GetMessageType() != TYPE_NOTIFY || inMsg->GetMessageId() != ABILITY_SYNC_MESSAGE) {
1437             return;
1438         }
1439         sqlite3 *db = nullptr;
1440         EXPECT_EQ(GetDB(db), SQLITE_OK);
1441         ASSERT_NE(db, nullptr);
1442         std::string alterSql = "ALTER TABLE " + g_tableName + " ADD COLUMN NEW_COLUMN TEXT DEFAULT 'DEFAULT_TEXT'";
1443         EXPECT_EQ(sqlite3_exec(db, alterSql.c_str(), nullptr, nullptr, nullptr), SQLITE_OK);
1444         EXPECT_EQ(sqlite3_close(db), SQLITE_OK);
1445         EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(g_tableName), OK);
1446     });
1447 
1448     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1449 
1450     g_communicatorAggregator->RegOnDispatch(nullptr);
1451 }
1452 
1453 /**
1454 * @tc.name: Ability Sync 004
1455 * @tc.desc: Test ability sync failed when one device hasn't distributed table.
1456 * @tc.type: FUNC
1457 * @tc.require: AR000GK58N
1458 * @tc.author: zhangqiquan
1459 */
1460 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync004, TestSize.Level1)
1461 {
1462     std::map<std::string, DataValue> dataMap;
1463     PrepareVirtualEnvironment(dataMap, {g_deviceB}, false);
1464 
1465     Query query = Query::Select(g_tableName);
1466     int res = DB_ERROR;
__anon122cc5721102(std::map<std::string, int> resMap) 1467     auto callBack = [&res](std::map<std::string, int> resMap) {
1468         if (resMap.find("real_device") != resMap.end()) {
1469             res = resMap["real_device"];
1470         }
1471     };
1472     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, callBack, true), E_OK);
1473     EXPECT_EQ(res, static_cast<int>(SyncOperation::Status::OP_SCHEMA_INCOMPATIBLE));
1474 }
1475 
1476 /**
1477 * @tc.name: WaterMark 001
1478 * @tc.desc: Test sync success after erase waterMark.
1479 * @tc.type: FUNC
1480 * @tc.require: AR000GK58N
1481 * @tc.author: zhangqiquan
1482 */
1483 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, WaterMark001, TestSize.Level1)
1484 {
1485     std::map<std::string, DataValue> dataMap;
1486     PrepareEnvironment(dataMap, {g_deviceB});
1487     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1488 
1489     CheckVirtualData(dataMap);
1490 
1491     EXPECT_EQ(g_rdbDelegatePtr->RemoveDeviceData(g_deviceB->GetDeviceId(), g_tableName), OK);
1492     g_deviceB->EraseSyncData(g_tableName);
1493 
1494     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1495 
1496     CheckVirtualData(dataMap);
1497 }
1498 
1499 /*
1500 * @tc.name: pressure sync 001
1501 * @tc.desc: Test rdb sync different table at same time
1502 * @tc.type: FUNC
1503 * @tc.require: AR000GK58N
1504 * @tc.author: zhangqiquan
1505 */
1506 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, PressureSync001, TestSize.Level1)
1507 {
1508     /**
1509      * @tc.steps: step1. create table A and device A push data to device B
1510      * @tc.expected: step1. all is ok
1511      */
1512     std::map<std::string, DataValue> tableADataMap;
1513     std::vector<FieldInfo> tableAFieldInfo;
1514     std::vector<StorageType> localStorageType = g_storageType;
1515     localStorageType.push_back(StorageType::STORAGE_TYPE_INTEGER);
1516     GetFieldInfo(tableAFieldInfo, localStorageType);
1517     const std::string tableNameA = "TABLE_A";
1518     PrepareEnvironment(tableADataMap, tableNameA, tableAFieldInfo, tableAFieldInfo, {g_deviceB});
1519 
1520     /**
1521      * @tc.steps: step2. create table B and device B push data to device A
1522      * @tc.expected: step2. all is ok
1523      */
1524     std::map<std::string, DataValue> tableBDataMap;
1525     std::vector<FieldInfo> tableBFieldInfo;
1526     localStorageType = g_storageType;
1527     localStorageType.push_back(StorageType::STORAGE_TYPE_REAL);
1528     GetFieldInfo(tableBFieldInfo, localStorageType);
1529     const std::string tableNameB = "TABLE_B";
1530     PrepareVirtualEnvironment(tableBDataMap, tableNameB, tableBFieldInfo, {g_deviceB});
1531 
1532     std::condition_variable cv;
1533     bool subFinish = false;
__anon122cc5721202() 1534     std::thread subThread = std::thread([&subFinish, &cv, &tableNameA, &tableADataMap]() {
1535         BlockSync(tableNameA, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1536 
1537         CheckVirtualData(tableNameA, tableADataMap);
1538         subFinish = true;
1539         cv.notify_all();
1540     });
1541     subThread.detach();
1542 
1543     Query query = Query::Select(tableNameB);
1544     g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
1545     CheckData(tableBDataMap, tableNameB, tableBFieldInfo);
1546 
1547     std::mutex mutex;
1548     std::unique_lock<std::mutex> lock(mutex);
__anon122cc5721302null1549     cv.wait(lock, [&subFinish] { return subFinish; });
1550 }
1551 
1552 /*
1553 * @tc.name: relation observer 001
1554 * @tc.desc: Test relation observer while normal pull sync
1555 * @tc.type: FUNC
1556 * @tc.require:
1557 * @tc.author: zhuwentao
1558 */
1559 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer001, TestSize.Level0)
1560 {
1561     /**
1562      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1563      * @tc.expected: step1. create and insert ok
1564      */
1565     g_observer->ResetToZero();
1566     std::map<std::string, DataValue> dataMap;
1567     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1568     /**
1569      * @tc.steps: step2. device A pull sync mode
1570      * @tc.expected: step2. sync ok
1571      */
1572     BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, OK, {DEVICE_B, DEVICE_C});
1573     /**
1574      * @tc.steps: step3. device A check observer
1575      * @tc.expected: step2. data change device is deviceB
1576      */
1577     EXPECT_EQ(g_observer->GetCallCount(), 1u);
1578     EXPECT_EQ(g_observer->GetDataChangeDevice(), DEVICE_B);
1579     CheckIdentify(g_observer);
1580 }
1581 
1582 /**
1583 * @tc.name: relation observer 002
1584 * @tc.desc: Test rdb observer ok in autolauchCallback scene
1585 * @tc.type: FUNC
1586 * @tc.require: AR000GK58N
1587 * @tc.author: zhuwentao
1588 */
1589 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer002, TestSize.Level3)
1590 {
1591     /**
1592      * @tc.steps: step1. open rdb store, create distribute table and insert data
1593      */
1594     g_observer->ResetToZero();
1595     std::map<std::string, DataValue> dataMap;
1596     PrepareVirtualEnvironment(dataMap, {g_deviceB});
1597 
1598     /**
1599      * @tc.steps: step2. set auto launch callBack
1600      */
1601     RelationalStoreObserverUnitTest *observer = new (std::nothrow) RelationalStoreObserverUnitTest();
__anon122cc5721402(const std::string &identifier, AutoLaunchParam &param) 1602     const AutoLaunchRequestCallback callback = [observer](const std::string &identifier, AutoLaunchParam &param) {
1603         if (g_id != identifier) {
1604             return false;
1605         }
1606         param.path    = g_dbDir;
1607         param.appId   = APP_ID;
1608         param.userId  = USER_ID;
1609         param.storeId = STORE_ID_1;
1610         param.option.storeObserver = observer;
1611 #ifndef OMIT_ENCRYPT
1612         param.option.isEncryptedDb = true;
1613         param.option.cipher = CipherType::DEFAULT;
1614         param.option.passwd = g_correctPasswd;
1615         param.option.iterateTimes = DEFAULT_ITER;
1616 #endif
1617         return true;
1618     };
1619     g_mgr.SetAutoLaunchRequestCallback(callback);
1620     /**
1621      * @tc.steps: step3. close store ensure communicator has closed
1622      */
1623     g_mgr.CloseStore(g_rdbDelegatePtr);
1624     g_rdbDelegatePtr = nullptr;
1625     /**
1626      * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1627      */
1628     LabelType labelType(g_id.begin(), g_id.end());
1629     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1630     std::this_thread::sleep_for(std::chrono::seconds(1));
1631     /**
1632      * @tc.steps: step5. Call sync expect sync successful and device A check observer
1633      */
1634     Query query = Query::Select(g_tableName);
1635     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1636     EXPECT_EQ(observer->GetCallCount(), 1u);
1637     EXPECT_EQ(observer->GetDataChangeDevice(), DEVICE_B);
1638     CheckIdentify(observer);
1639     std::this_thread::sleep_for(std::chrono::minutes(1));
1640     delete observer;
1641 }
1642 
1643 /*
1644 * @tc.name: relation observer 003
1645 * @tc.desc: Test relation observer without manager
1646 * @tc.type: FUNC
1647 * @tc.require:
1648 * @tc.author: zhangqiquan
1649 */
1650 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer003, TestSize.Level0)
1651 {
1652     /**
1653      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1654      * @tc.expected: step1. create and insert ok
1655      */
1656     g_observer->ResetToZero();
1657     std::map<std::string, DataValue> dataMap;
1658     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1659     std::shared_ptr<RelationalStoreManager> mgr = std::make_shared<RelationalStoreManager>(APP_ID, USER_ID);
1660     ASSERT_NE(mgr, nullptr);
1661     RelationalStoreDelegate::Option option;
1662     option.observer = g_observer;
1663 #ifndef OMIT_ENCRYPT
1664     option.isEncryptedDb = true;
1665     option.iterateTimes = DEFAULT_ITER;
1666     option.passwd = g_isAfterRekey ? g_rekeyPasswd : g_correctPasswd;
1667     option.cipher = CipherType::DEFAULT;
1668 #endif
1669     RelationalStoreDelegate *rdbDelegatePtr = nullptr;
1670     mgr->OpenStore(g_dbDir, STORE_ID_1, option, rdbDelegatePtr);
1671     mgr = nullptr;
1672     /**
1673      * @tc.steps: step2. device A pull sync mode
1674      * @tc.expected: step2. sync ok
1675      */
1676     Query query = Query::Select(g_tableName);
1677     DBStatus callStatus = rdbDelegatePtr->Sync({DEVICE_B, DEVICE_C}, SyncMode::SYNC_MODE_PULL_ONLY, query,
1678         nullptr, true);
1679     EXPECT_EQ(callStatus, OK);
1680     /**
1681      * @tc.steps: step3. device A check observer
1682      * @tc.expected: step2. data change device is deviceB
1683      */
1684     EXPECT_EQ(g_observer->GetCallCount(), 1u);
1685     EXPECT_EQ(g_observer->GetDataChangeDevice(), DEVICE_B);
1686     CheckIdentify(g_observer);
1687     mgr = std::make_shared<RelationalStoreManager>(APP_ID, USER_ID);
1688     ASSERT_NE(mgr, nullptr);
1689     mgr->CloseStore(rdbDelegatePtr);
1690     mgr = nullptr;
1691 }
1692 
1693 /*
1694 * @tc.name: relation observer 004
1695 * @tc.desc: Test relation register observer
1696 * @tc.type: FUNC
1697 * @tc.require:
1698 * @tc.author: zhangqiquan
1699 */
1700 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer004, TestSize.Level0)
1701 {
1702     /**
1703      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1704      * @tc.expected: step1. create and insert ok
1705      */
1706     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1707     g_observer->ResetToZero();
1708     auto observer = new (std::nothrow) RelationalStoreObserverUnitTest();
1709     std::map<std::string, DataValue> dataMap;
1710     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1711     g_rdbDelegatePtr->RegisterObserver(observer);
1712     /**
1713      * @tc.steps: step2. device A pull sync mode
1714      * @tc.expected: step2. sync ok
1715      */
1716     BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, OK, {DEVICE_B, DEVICE_C});
1717     /**
1718      * @tc.steps: step3. device A check observer
1719      * @tc.expected: step2. data change device is deviceB
1720      */
1721     EXPECT_EQ(observer->GetCallCount(), 1u);
1722     EXPECT_EQ(g_observer->GetCallCount(), 0u);
1723     EXPECT_EQ(observer->GetDataChangeDevice(), DEVICE_B);
1724     CheckIdentify(observer);
1725 }
1726 
1727 /*
1728 * @tc.name: relation observer 005
1729 * @tc.desc: Test relation unregister observer
1730 * @tc.type: FUNC
1731 * @tc.require:
1732 * @tc.author: zhangqiquan
1733 */
1734 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer005, TestSize.Level0)
1735 {
1736     /**
1737      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1738      * @tc.expected: step1. create and insert ok
1739      */
1740     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1741     g_observer->ResetToZero();
1742     std::map<std::string, DataValue> dataMap;
1743     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1744     g_rdbDelegatePtr->UnRegisterObserver();
1745     /**
1746      * @tc.steps: step2. device A pull sync mode
1747      * @tc.expected: step2. sync ok
1748      */
1749     BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, OK, {DEVICE_B, DEVICE_C});
1750     /**
1751      * @tc.steps: step3. device A check observer
1752      * @tc.expected: step2. data change device is deviceB
1753      */
1754     EXPECT_EQ(g_observer->GetCallCount(), 0u);
1755 }
1756 
1757 
1758 /*
1759 * @tc.name: relation observer 006
1760 * @tc.desc: Test observer is destructed when sync finish
1761 * @tc.type: FUNC
1762 * @tc.require:
1763 * @tc.author: zhangshijie
1764 */
1765 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer006, TestSize.Level3)
1766 {
1767     /**
1768      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1769      * @tc.expected: step1. create and insert ok
1770      */
1771     g_observer->ResetToZero();
1772     std::map<std::string, DataValue> dataMap;
1773     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1774 
1775     /**
1776      * @tc.steps: step2. device A pull sync mode
1777      * @tc.expected: step2. sync ok
1778      */
1779     int count = 0;
1780     PermissionCheckCallbackV2 callback = [&count](const std::string &userId, const std::string &appId,
__anon122cc5721502(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 1781         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
1782         if ((flag == CHECK_FLAG_RECEIVE) && (count == 0)) {
1783             for (int i = 0; i < 10; i++) { // 10 is capacity of thread pool
1784                 RuntimeContext::GetInstance()->ScheduleTask([] () {
1785                     std::this_thread::sleep_for(std::chrono::seconds(6)); // sleep 6 seconds
1786                 });
1787             }
1788             count++;
1789         }
1790         return true;
1791     };
1792     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(callback), E_OK);
1793 
1794     /**
1795      * @tc.steps: step3. device A check observer
1796      * @tc.expected: step2. data change device is deviceB
1797      */
1798     Query query = Query::Select(g_tableName);
1799     g_rdbDelegatePtr->Sync({DEVICE_B}, SyncMode::SYNC_MODE_PULL_ONLY, query, nullptr, false);
1800     std::this_thread::sleep_for(std::chrono::seconds(1));
1801     ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
1802     g_rdbDelegatePtr = nullptr;
1803     delete g_observer;
1804     g_observer = nullptr;
1805     std::this_thread::sleep_for(std::chrono::seconds(10)); // sleep 10 second to wait sync finish
1806     RuntimeContext::GetInstance()->StopTaskPool();
1807 }
1808 
1809 /*
1810 * @tc.name: relation observer 007
1811 * @tc.desc: Test open store observer will not overwrite autolaunch observer
1812 * @tc.type: FUNC
1813 * @tc.require:
1814 * @tc.author: zhangshijie
1815 */
1816 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer007, TestSize.Level3)
1817 {
1818     /**
1819      * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1820      * @tc.expected: step1. create and insert ok
1821      */
1822     g_observer->ResetToZero();
1823     std::map<std::string, DataValue> dataMap;
1824     PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1825 
1826     /**
1827      * @tc.steps: step2. device A pull sync mode
1828      * @tc.expected: step2. sync ok
1829      */
1830     RelationalStoreObserverUnitTest *observer = new (std::nothrow) RelationalStoreObserverUnitTest();
1831     ASSERT_NE(observer, nullptr);
__anon122cc5721702(const std::string &identifier, AutoLaunchParam &param) 1832     const AutoLaunchRequestCallback callback = [observer](const std::string &identifier, AutoLaunchParam &param) {
1833         if (g_id != identifier) {
1834             return false;
1835         }
1836         param.path    = g_dbDir;
1837         param.appId   = APP_ID;
1838         param.userId  = USER_ID;
1839         param.storeId = STORE_ID_1;
1840         param.option.storeObserver = observer;
1841 #ifndef OMIT_ENCRYPT
1842         param.option.isEncryptedDb = true;
1843         param.option.cipher = CipherType::DEFAULT;
1844         param.option.passwd = g_correctPasswd;
1845         param.option.iterateTimes = DEFAULT_ITER;
1846 #endif
1847         return true;
1848     };
1849 
1850     /**
1851      * @tc.steps: step2. SetAutoLaunchRequestCallback
1852      * @tc.expected: step2. success.
1853      */
1854     g_mgr.SetAutoLaunchRequestCallback(callback);
1855 
1856     /**
1857      * @tc.steps: step3. RunCommunicatorLackCallback
1858      * @tc.expected: step3. success.
1859      */
1860     LabelType labelType(g_id.begin(), g_id.end());
1861     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1862 
1863     /**
1864      * @tc.steps: step4. start sync
1865      * @tc.expected: step4. success
1866      */
1867     Query query = Query::Select(g_tableName);
1868     g_rdbDelegatePtr->Sync({DEVICE_B}, SyncMode::SYNC_MODE_PULL_ONLY, query, nullptr, false);
1869 
1870     /**
1871      * @tc.steps: step5. open store with observer1
1872      * @tc.expected: step5. success.
1873      */
1874     auto observer1 = new (std::nothrow) RelationalStoreObserverUnitTest();
1875     ASSERT_NE(observer1, nullptr);
1876     RelationalStoreDelegate::Option option;
1877     option.observer = observer1;
1878 #ifndef OMIT_ENCRYPT
1879     option.isEncryptedDb = true;
1880     option.iterateTimes = DEFAULT_ITER;
1881     option.passwd = g_isAfterRekey ? g_rekeyPasswd : g_correctPasswd;
1882     option.cipher = CipherType::DEFAULT;
1883 #endif
1884     RelationalStoreDelegate *rdb1 = nullptr;
1885     g_mgr.OpenStore(g_dbDir, STORE_ID_1, option, rdb1);
1886     ASSERT_TRUE(rdb1 != nullptr);
1887 
1888     /**
1889      * @tc.steps: step6. close store and delete observer1
1890      * @tc.expected: step6. success.
1891      */
1892     ASSERT_EQ(g_mgr.CloseStore(rdb1), OK);
1893     rdb1 = nullptr;
1894     delete observer1;
1895     observer1 = nullptr;
1896     std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep 2 second to wait sync finish
1897     std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5 second to wait sync finish
1898     RuntimeConfig::ReleaseAutoLaunch(USER_ID, APP_ID, STORE_ID_1, DBType::DB_RELATION);
1899     RuntimeContext::GetInstance()->StopTaskPool();
1900 }
1901 
1902 
1903 /**
1904 * @tc.name: remote query 001
1905 * @tc.desc: Test rdb remote query
1906 * @tc.type: FUNC
1907 * @tc.require: AR000GK58G
1908 * @tc.author: zhangqiquan
1909 */
1910 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery001, TestSize.Level1)
1911 {
1912     std::map<std::string, DataValue> dataMap;
1913     PrepareEnvironment(dataMap, {g_deviceB});
1914     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1915     RemoteCondition condition;
1916     condition.sql = "SELECT * FROM " + g_tableName;
1917     std::shared_ptr<ResultSet> result = nullptr;
1918     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), OK);
1919 
1920     EXPECT_NE(result, nullptr);
1921 }
1922 
1923 /**
1924 * @tc.name: remote query 002
1925 * @tc.desc: Test rdb remote query
1926 * @tc.type: FUNC
1927 * @tc.require: AR000GK58G
1928 * @tc.author: zhangqiquan
1929 */
1930 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery002, TestSize.Level1)
1931 {
1932     std::map<std::string, DataValue> dataMap;
1933     PrepareEnvironment(dataMap, {g_deviceB});
1934     ASSERT_NE(g_deviceB, nullptr);
1935     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1936     RemoteCondition condition;
1937     condition.sql = "SELECT * FROM " + g_tableName;
1938     std::shared_ptr<ResultSet> result = nullptr;
1939     EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), OK);
1940     CheckSearchData(result, dataMap);
1941 }
1942 
1943 /**
1944 * @tc.name: remote query 003
1945 * @tc.desc: Test rdb remote query but query not data
1946 * @tc.type: FUNC
1947 * @tc.require: AR000GK58G
1948 * @tc.author: zhangqiquan
1949 */
1950 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery003, TestSize.Level1)
1951 {
1952     std::map<std::string, DataValue> dataMap;
1953     PrepareEnvironment(dataMap, {g_deviceB});
1954     ASSERT_NE(g_deviceB, nullptr);
1955     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1956     RemoteCondition condition;
1957     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1958     std::shared_ptr<ResultSet> result = nullptr;
1959     EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), OK);
1960     ASSERT_NE(result, nullptr);
1961     EXPECT_EQ(result->GetCount(), 0);
1962 }
1963 
1964 /**
1965 * @tc.name: remote query 004
1966 * @tc.desc: Test rdb queue size
1967 * @tc.type: FUNC
1968 * @tc.require: AR000GK58G
1969 * @tc.author: zhangqiquan
1970 */
1971 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery004, TestSize.Level3)
1972 {
1973     std::map<std::string, DataValue> dataMap;
1974     PrepareEnvironment(dataMap, {g_deviceB});
1975     ASSERT_NE(g_rdbDelegatePtr, nullptr);
1976     RemoteCondition condition;
1977     condition.sql = "SELECT * FROM " + g_tableName;
1978     std::vector<std::string> deviceMap = {DEVICE_B, DEVICE_C};
__anon122cc5721802(const std::string &device, Message *inMsg) 1979     g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
1980         ASSERT_NE(inMsg, nullptr);
1981         inMsg->SetMessageId(INVALID_MESSAGE_ID);
1982     });
1983     const size_t MAX_SIZE = 7;
1984     std::vector<std::thread *> threadList;
1985     for (size_t j = 0; j < deviceMap.size(); j++) {
1986         for (size_t i = 0; i < MAX_SIZE; i++) {
1987             std::string device = deviceMap[j];
__anon122cc5721902() 1988             threadList.push_back(new std::thread([&, device]() {
1989                 std::shared_ptr<ResultSet> result = nullptr;
1990                 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(device, condition,
1991                     DBConstant::MIN_TIMEOUT, result), TIME_OUT);
1992                 EXPECT_EQ(result, nullptr);
1993             }));
1994         }
1995     }
1996     for (size_t i = 0; i < threadList.size(); i++) {
1997         threadList[i]->join();
1998         delete threadList[i];
1999         threadList[i] = nullptr;
2000     }
2001 }
2002 
2003 /**
2004 * @tc.name: remote query 005
2005 * @tc.desc: Test rdb remote query timeout by invalid message
2006 * @tc.type: FUNC
2007 * @tc.require: AR000GK58G
2008 * @tc.author: zhangqiquan
2009 */
2010 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery005, TestSize.Level1)
2011 {
2012     std::map<std::string, DataValue> dataMap;
2013     PrepareEnvironment(dataMap, {g_deviceB});
2014     ASSERT_NE(g_deviceB, nullptr);
2015     ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anon122cc5721a02(const std::string &device, Message *inMsg) 2016     g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
2017         ASSERT_NE(inMsg, nullptr);
2018         inMsg->SetMessageId(INVALID_MESSAGE_ID);
2019     });
2020     RemoteCondition condition;
2021     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2022     std::shared_ptr<ResultSet> result = nullptr;
2023     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), TIME_OUT);
2024     ASSERT_EQ(result, nullptr);
2025 }
2026 
2027 /**
2028 * @tc.name: remote query 006
2029 * @tc.desc: Test rdb remote query commfailure by offline
2030 * @tc.type: FUNC
2031 * @tc.require: AR000GK58G
2032 * @tc.author: zhangqiquan
2033 */
2034 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery006, TestSize.Level1)
2035 {
2036     std::map<std::string, DataValue> dataMap;
2037     PrepareEnvironment(dataMap, {g_deviceB});
2038     ASSERT_NE(g_deviceB, nullptr);
2039     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2040     std::thread offlineThread;
2041     std::atomic<bool> offline = false;
__anon122cc5721b02(const std::string &device, Message *inMsg) 2042     g_communicatorAggregator->RegOnDispatch([&offlineThread, &offline](const std::string &device, Message *inMsg) {
2043         ASSERT_NE(inMsg, nullptr);
2044         inMsg->SetMessageId(INVALID_MESSAGE_ID);
2045         if (offline) {
2046             return;
2047         }
2048         offline = true;
2049         std::thread t([]() {
2050             g_deviceB->Offline();
2051         });
2052         offlineThread = std::move(t);
2053     });
2054     RemoteCondition condition;
2055     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2056     std::shared_ptr<ResultSet> result = nullptr;
2057     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), COMM_FAILURE);
2058     ASSERT_EQ(result, nullptr);
2059     if (offline) {
2060         offlineThread.join();
2061     }
2062 }
2063 
2064 /**
2065 * @tc.name: remote query 007
2066 * @tc.desc: Test rdb remote query failed by permission check
2067 * @tc.type: FUNC
2068 * @tc.require: AR000GK58G
2069 * @tc.author: zhangqiquan
2070 */
2071 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery007, TestSize.Level1)
2072 {
2073     std::map<std::string, DataValue> dataMap;
2074     PrepareEnvironment(dataMap, {g_deviceB});
2075     ASSERT_NE(g_deviceB, nullptr);
2076     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2077     PermissionCheckCallbackV2 callback = [](const std::string &userId, const std::string &appId,
__anon122cc5721d02(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2078         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2079         return false;
2080     };
2081     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(callback), OK);
2082     RemoteCondition condition;
2083     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2084     std::shared_ptr<ResultSet> result = nullptr;
2085     EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result),
2086         PERMISSION_CHECK_FORBID_SYNC);
2087     ASSERT_EQ(result, nullptr);
2088     callback = nullptr;
2089     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(callback), OK);
2090 }
2091 
2092 /**
2093 * @tc.name: remote query 008
2094 * @tc.desc: Test rdb remote query timeout but not effected by invalid message
2095 * @tc.type: FUNC
2096 * @tc.require: AR000GK58G
2097 * @tc.author: zhangqiquan
2098 */
2099 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery008, TestSize.Level1)
2100 {
2101     std::map<std::string, DataValue> dataMap;
2102     PrepareEnvironment(dataMap, {g_deviceB});
2103     ASSERT_NE(g_deviceB, nullptr);
2104     ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anon122cc5721e02(const std::string &device, Message *inMsg) 2105     g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
2106         ASSERT_NE(inMsg, nullptr);
2107         if (device != DEVICE_B) {
2108             return;
2109         }
2110         inMsg->SetMessageId(INVALID_MESSAGE_ID);
2111         std::thread t([]() {
2112             auto *msg = new (std::nothrow) Message(REMOTE_EXECUTE_MESSAGE);
2113             ASSERT_NE(msg, nullptr);
2114             auto *packet = new (std::nothrow) RemoteExecutorAckPacket();
2115             if (packet != nullptr) {
2116                 packet->SetAckCode(-E_FEEDBACK_COMMUNICATOR_NOT_FOUND);
2117             }
2118             if (msg->SetExternalObject(packet) != E_OK) {
2119                 delete packet;
2120                 packet = nullptr;
2121             }
2122             msg->SetMessageType(TYPE_RESPONSE);
2123             msg->SetErrorNo(E_FEEDBACK_COMMUNICATOR_NOT_FOUND);
2124             msg->SetSessionId(0u);
2125             msg->SetSequenceId(1u);
2126             g_communicatorAggregator->DispatchMessage(DEVICE_B, DEVICE_A, msg, nullptr);
2127             LOGD("DispatchMessage Finish");
2128         });
2129         t.detach();
2130     });
2131     RemoteCondition condition;
2132     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2133     std::shared_ptr<ResultSet> result = nullptr;
2134     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), TIME_OUT);
2135     ASSERT_EQ(result, nullptr);
2136 }
2137 
2138 /**
2139 * @tc.name: remote query 009
2140 * @tc.desc: Test rdb remote query busy before timeout
2141 * @tc.type: FUNC
2142 * @tc.require: AR000GK58G
2143 * @tc.author: zhangqiquan
2144 */
2145 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery009, TestSize.Level1)
2146 {
2147     std::map<std::string, DataValue> dataMap;
2148     PrepareEnvironment(dataMap, {g_deviceB});
2149     ASSERT_NE(g_deviceB, nullptr);
2150     ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anon122cc5722002(const std::string &device, Message *inMsg) 2151     g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
2152         ASSERT_NE(inMsg, nullptr);
2153         inMsg->SetMessageId(INVALID_MESSAGE_ID);
2154     });
2155     RemoteCondition condition;
2156     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2157     std::shared_ptr<ResultSet> result = nullptr;
__anon122cc5722102() 2158     std::thread t([]() {
2159         std::this_thread::sleep_for(std::chrono::seconds(1));
2160         if (g_rdbDelegatePtr != nullptr) {
2161             LOGD("CloseStore Start");
2162             ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
2163             g_rdbDelegatePtr = nullptr;
2164         }
2165     });
2166     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), BUSY);
2167     ASSERT_EQ(result, nullptr);
2168     t.join();
2169 }
2170 
2171 /**
2172 * @tc.name: remote query 010
2173 * @tc.desc: Test rdb remote query with kv db
2174 * @tc.type: FUNC
2175 * @tc.require: AR000GK58G
2176 * @tc.author: zhangqiquan
2177 */
2178 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery010, TestSize.Level1)
2179 {
2180     std::map<std::string, DataValue> dataMap;
2181     PrepareEnvironment(dataMap, {g_deviceB});
2182     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2183     RemoteCondition condition;
2184     condition.sql = "SELECT * FROM " + g_tableName;
2185     std::shared_ptr<ResultSet> result = nullptr;
2186     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_D, condition, DBConstant::MIN_TIMEOUT, result), NOT_SUPPORT);
2187 
2188     EXPECT_EQ(result, nullptr);
2189 }
2190 
2191 /**
2192 * @tc.name: remote query 010
2193 * @tc.desc: Test rdb remote query with error sql
2194 * @tc.type: FUNC
2195 * @tc.require: AR000GK58G
2196 * @tc.author: zhangqiquan
2197 */
2198 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery011, TestSize.Level1)
2199 {
2200     std::map<std::string, DataValue> dataMap;
2201     PrepareEnvironment(dataMap, {g_deviceB});
2202     ASSERT_NE(g_deviceB, nullptr);
2203     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2204     RemoteCondition condition;
2205     condition.sql = "This is error sql";
2206     std::shared_ptr<ResultSet> result = nullptr;
2207     EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), DB_ERROR);
2208     EXPECT_EQ(result, nullptr);
2209 }
2210 
2211 /**
2212 * @tc.name: remote query 012
2213 * @tc.desc: Test rdb remote query with invalid dev
2214 * @tc.type: FUNC
2215 * @tc.require: AR000GK58G
2216 * @tc.author: zhangqiquan
2217 */
2218 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery012, TestSize.Level1)
2219 {
2220     std::map<std::string, DataValue> dataMap;
2221     std::string invalidDev = std::string(DBConstant::MAX_DEV_LENGTH + 1, '0');
2222     PrepareEnvironment(dataMap, {g_deviceB});
2223     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2224     RemoteCondition condition;
2225     condition.sql = "SELECT * FROM " + g_tableName;
2226     std::shared_ptr<ResultSet> result = nullptr;
2227     EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(invalidDev, condition, DBConstant::MIN_TIMEOUT, result), INVALID_ARGS);
2228     EXPECT_EQ(result, nullptr);
2229 }
2230 
2231 /**
2232 * @tc.name: RelationalPemissionTest001
2233 * @tc.desc: deviceB PermissionCheck not pass test, SYNC_MODE_PUSH_ONLY
2234 * @tc.type: FUNC
2235 * @tc.require: AR000GK58N
2236 * @tc.author: zhangshijie
2237 */
2238 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest001, TestSize.Level0)
2239 {
2240     /**
2241      * @tc.steps: step1. SetPermissionCheckCallback
2242      * @tc.expected: step1. return OK.
2243      */
2244     auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anon122cc5722202(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2245         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2246             LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2247             bool empty = userId.empty() || appId.empty() || storeId.empty();
2248             EXPECT_TRUE(empty == false);
2249             if (flag & (CHECK_FLAG_SEND)) {
2250                 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
2251                 return false;
2252             } else {
2253                 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
2254                 return true;
2255             }
2256         };
2257     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2258 
2259     /**
2260      * @tc.steps: step2. sync with deviceB
2261      */
2262     std::map<std::string, DataValue> dataMap;
2263     PrepareEnvironment(dataMap, { g_deviceB });
2264     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
2265 
2266     /**
2267      * @tc.steps: step3. check data in deviceB
2268      * @tc.expected: step3. deviceB has no data
2269      */
2270     std::vector<VirtualRowData> targetData;
2271     g_deviceB->GetAllSyncData(g_tableName, targetData);
2272 
2273     ASSERT_EQ(targetData.size(), 0u);
2274 }
2275 
2276 /**
2277 * @tc.name: RelationalPemissionTest002
2278 * @tc.desc: deviceB PermissionCheck not pass test, SYNC_MODE_PULL_ONLY
2279 * @tc.type: FUNC
2280 * @tc.require: AR000GK58N
2281 * @tc.author: zhangshijie
2282 */
2283 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest002, TestSize.Level0)
2284 {
2285     /**
2286      * @tc.steps: step1. SetPermissionCheckCallback
2287      * @tc.expected: step1. return OK.
2288      */
2289     auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anon122cc5722302(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2290         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2291             LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2292             bool empty = userId.empty() || appId.empty() || storeId.empty();
2293             EXPECT_TRUE(empty == false);
2294             if (flag & (CHECK_FLAG_RECEIVE)) {
2295                 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
2296                 return false;
2297             } else {
2298                 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
2299                 return true;
2300             }
2301         };
2302     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2303 
2304     /**
2305      * @tc.steps: step2. sync with deviceB
2306      */
2307     std::map<std::string, DataValue> dataMap;
2308     PrepareEnvironment(dataMap, { g_deviceB });
2309     BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
2310 
2311     /**
2312      * @tc.steps: step3. check data in deviceB
2313      * @tc.expected: step3. deviceB has no data
2314      */
2315     std::vector<VirtualRowData> targetData;
2316     g_deviceB->GetAllSyncData(g_tableName, targetData);
2317 
2318     ASSERT_EQ(targetData.size(), 0u);
2319 }
2320 
2321 /**
2322 * @tc.name: RelationalPemissionTest003
2323 * @tc.desc: deviceB PermissionCheck not pass test, flag CHECK_FLAG_SPONSOR
2324 * @tc.type: FUNC
2325 * @tc.require: AR000GK58N
2326 * @tc.author: zhangshijie
2327 */
2328 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest003, TestSize.Level0)
2329 {
2330     /**
2331      * @tc.steps: step1. SetPermissionCheckCallback
2332      * @tc.expected: step1. return OK.
2333      */
2334     auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anon122cc5722402(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2335         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2336             LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2337             bool empty = userId.empty() || appId.empty() || storeId.empty();
2338             EXPECT_TRUE(empty == false);
2339             if (flag &  CHECK_FLAG_SPONSOR) {
2340                 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
2341                 return false;
2342             } else {
2343                 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
2344                 return true;
2345             }
2346         };
2347     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2348 
2349     /**
2350      * @tc.steps: step2. sync with deviceB
2351      */
2352     std::map<std::string, DataValue> dataMap;
2353     PrepareEnvironment(dataMap, { g_deviceB });
2354     BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
2355 
2356     /**
2357      * @tc.steps: step3. check data in deviceB
2358      * @tc.expected: step3. deviceB has no data
2359      */
2360     std::vector<VirtualRowData> targetData;
2361     g_deviceB->GetAllSyncData(g_tableName, targetData);
2362 
2363     ASSERT_EQ(targetData.size(), 0u);
2364 }
2365 
2366 /**
2367 * @tc.name: RelationalPemissionTest004
2368 * @tc.desc: deviceB PermissionCheck pass test. deviceC not pass, SYNC_MODE_PUSH_ONLY
2369 * @tc.type: FUNC
2370 * @tc.require: AR000GK58N
2371 * @tc.author: zhangshijie
2372 */
2373 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest004, TestSize.Level0)
2374 {
2375     /**
2376      * @tc.steps: step1. SetPermissionCheckCallback
2377      * @tc.expected: step1. return OK.
2378      */
2379     auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anon122cc5722502(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2380         const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2381             LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2382             if (deviceId == g_deviceC->GetDeviceId()) {
2383                 LOGE("in RunPermissionCheck callback, check pass, device:%s", deviceId.c_str());
2384                 return false;
2385             } else {
2386                 LOGE("in RunPermissionCheck callback, check not pass, device:%s", deviceId.c_str());
2387                 return true;
2388             }
2389         };
2390     EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2391 
2392     std::map<std::string, DataValue> dataMap;
2393     PrepareEnvironment(dataMap, { g_deviceB, g_deviceC });
2394 
2395     /**
2396      * @tc.steps: step2. sync with deviceB
2397      */
2398     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, { DEVICE_B });
2399 
2400     /**
2401      * @tc.steps: step3. check data in deviceB
2402      * @tc.expected: step3. deviceB has data
2403      */
2404     std::vector<VirtualRowData> targetData;
2405     g_deviceB->GetAllSyncData(g_tableName, targetData);
2406     ASSERT_EQ(targetData.size(), 1u);
2407 
2408     /**
2409      * @tc.steps: step4. sync with deviceC
2410      */
2411     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_C });
2412 
2413     /**
2414      * @tc.steps: step5. check data in deviceC
2415      * @tc.expected: step5. deviceC has no data
2416      */
2417     targetData.clear();
2418     g_deviceC->GetAllSyncData(g_tableName, targetData);
2419     ASSERT_EQ(targetData.size(), 0u);
2420 }
2421 
2422 /**
2423 * @tc.name: SecurityOptionCheck001
2424 * @tc.desc: Test sync failed when getSecurityOption return error
2425 * @tc.type: FUNC
2426 * @tc.require: AR000GK58N
2427 * @tc.author: zhangqiquan
2428 */
2429 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, SecurityOptionCheck001, TestSize.Level1)
2430 {
2431     std::vector<std::string> devices;
2432     devices.push_back(g_deviceB->GetDeviceId());
2433 
2434     /**
2435      * @tc.steps: step1. make getSecurityOption return -1
2436      */
2437     std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
2438     adapter->ForkGetSecurityOption(
__anon122cc5722602(const std::string &filePath, SecurityOption &option) 2439         [](const std::string &filePath, SecurityOption &option) {
2440             (void)filePath;
2441             (void)option;
2442             return DB_ERROR;
2443     });
2444     RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
2445 
2446     std::map<std::string, DataValue> dataMap;
2447     PrepareEnvironment(dataMap, { g_deviceB });
2448 
2449     /**
2450      * @tc.steps: step2. sync with deviceB
2451      */
2452     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, SECURITY_OPTION_CHECK_ERROR, { DEVICE_B });
2453     RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
2454 }
2455 
2456 /**
2457 * @tc.name: SecurityOptionCheck002
2458 * @tc.desc: Test remote query failed when getSecurityOption return error
2459 * @tc.type: FUNC
2460 * @tc.require: AR000GK58G
2461 * @tc.author: zhangqiquan
2462 */
2463 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, SecurityOptionCheck002, TestSize.Level1)
2464 {
2465     /**
2466      * @tc.steps: step1. make getSecurityOption return -1
2467      */
2468     std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
2469     adapter->ForkGetSecurityOption(
__anon122cc5722702(const std::string &filePath, SecurityOption &option) 2470         [](const std::string &filePath, SecurityOption &option) {
2471         (void)filePath;
2472         (void)option;
2473         return DB_ERROR;
2474     });
2475     RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
2476 
2477     /**
2478      * @tc.steps: step2. remote query with deviceB
2479      */
2480     std::map<std::string, DataValue> dataMap;
2481     PrepareEnvironment(dataMap, {g_deviceB});
2482     ASSERT_NE(g_deviceB, nullptr);
2483     ASSERT_NE(g_rdbDelegatePtr, nullptr);
2484     RemoteCondition condition;
2485     condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2486     std::shared_ptr<ResultSet> result = nullptr;
2487     EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result),
2488         SECURITY_OPTION_CHECK_ERROR);
2489     EXPECT_EQ(result, nullptr);
2490     RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
2491 }
2492 
2493 /**
2494 * @tc.name: OrderbyWriteTimeSync001
2495 * @tc.desc: sync query with order by writeTime
2496 * @tc.type: FUNC
2497 * @tc.require: AR000H5VLO
2498 * @tc.author: zhuwentao
2499 */
2500 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, OrderbyWriteTimeSync001, TestSize.Level0)
2501 {
2502     std::map<std::string, DataValue> dataMap;
2503     PrepareEnvironment(dataMap, {g_deviceB});
2504     Query query = Query::Select(g_tableName).OrderByWriteTime(true);;
2505     EXPECT_EQ(g_rdbDelegatePtr->Sync({DEVICE_B}, DistributedDB::SYNC_MODE_PUSH_ONLY, query, nullptr, false),
2506         NOT_SUPPORT);
2507 }
2508 
2509 /**
2510 * @tc.name: RDBSecurityOptionCheck001
2511 * @tc.desc: Test sync with security option.
2512 * @tc.type: FUNC
2513 * @tc.require: AR000GK58N
2514 * @tc.author: zhangqiquan
2515 */
2516 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RDBSecurityOptionCheck001, TestSize.Level3)
2517 {
2518     TestWithSecurityCheck(false);
2519 }
2520 
2521 /**
2522 * @tc.name: RDBSecurityOptionCheck002
2523 * @tc.desc: Test remote query with security option.
2524 * @tc.type: FUNC
2525 * @tc.require: AR000GK58N
2526 * @tc.author: zhangqiquan
2527 */
2528 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RDBSecurityOptionCheck002, TestSize.Level1)
2529 {
2530     TestWithSecurityCheck(true);
2531 }
2532 
2533 /**
2534 * @tc.name: EncryptedAlgoUpgrade001
2535   * @tc.desc: Test upgrade encrypted db can sync normally
2536   * @tc.type: FUNC
2537   * @tc.require: AR000HI2JS
2538   * @tc.author: zhuwentao
2539 */
2540 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, EncryptedAlgoUpgrade001, TestSize.Level0)
2541 {
2542     if (g_rdbDelegatePtr != nullptr) {
2543         LOGD("CloseStore Start");
2544         ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
2545         g_rdbDelegatePtr = nullptr;
2546     }
2547     EXPECT_EQ(OS::RemoveFile(g_dbDir), E_OK);
2548     /**
2549      * @tc.steps: step1. open old db use sha1 algo and insert some data
2550      * @tc.expected: step1. interface return ok
2551      */
2552     sqlite3 *db = nullptr;
2553     EXPECT_EQ(GetDB(db, false), SQLITE_OK);
2554     const std::string user_version_sql = "PRAGMA user_version=101;";
2555     EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, user_version_sql), E_OK);
2556     sqlite3_close(db);
2557 
2558     /**
2559      * @tc.steps: step2. open db by OpenStore
2560      * @tc.expected: step2. interface return ok
2561      */
2562     OpenStore();
2563     /**
2564      * @tc.steps: step3. sync with push
2565      * @tc.expected: step3. interface return ok
2566      */
2567     std::map<std::string, DataValue> dataMap;
2568     PrepareEnvironment(dataMap, {g_deviceB});
2569     BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
2570     CheckVirtualData(dataMap);
2571     dataMap.clear();
2572 
2573     /**
2574      * @tc.steps: step4. sync with pull
2575      * @tc.expected: step4. interface return ok
2576      */
2577 
2578     Query query = Query::Select(g_tableName);
2579     g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, true);
2580     CheckVirtualData(dataMap);
2581 }
2582 
2583 /**
2584  * @tc.name: QueryParamCheck001
2585  * @tc.desc: Test sync query param
2586  * @tc.type: FUNC
2587  * @tc.require:
2588  * @tc.author: zhangqiquan
2589  */
2590 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, QueryParamCheck001, TestSize.Level0)
2591 {
2592     std::map<std::string, DataValue> dataMap;
2593     PrepareEnvironment(dataMap, {g_deviceB});
2594     Query query = Query::Select().FromTable({ g_tableName });
2595     EXPECT_EQ(g_rdbDelegatePtr->Sync({DEVICE_B}, DistributedDB::SYNC_MODE_PUSH_ONLY, query, nullptr, false),
2596         NOT_SUPPORT);
2597 }
2598 
2599 #ifndef OMIT_ENCRYPT
2600 /**
2601 * @tc.name: AutoLaunchSyncAfterRekey_001
2602 * @tc.desc: Test auto launch sync ok after rekey.
2603 * @tc.type: FUNC
2604 * @tc.require: AR000H68LL
2605 * @tc.author: lidongwei
2606 */
2607 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSyncAfterRekey_001, TestSize.Level3)
2608 {
2609     /**
2610      * @tc.steps: step1. open rdb store, create distribute table and insert data
2611      */
2612     std::map<std::string, DataValue> dataMap;
2613     PrepareVirtualEnvironment(dataMap, {g_deviceB});
2614 
2615     /**
2616      * @tc.steps: step2. set auto launch callBack
2617      */
2618     AutoLaunchParam encryptedParam { USER_ID, APP_ID, STORE_ID_1, AutoLaunchOption {}, nullptr, g_dbDir };
2619     encryptedParam.option.isEncryptedDb = true;
2620     encryptedParam.option.cipher = CipherType::DEFAULT;
2621     encryptedParam.option.passwd = g_correctPasswd;
2622     encryptedParam.option.iterateTimes = DEFAULT_ITER;
__anon122cc5722802(const std::string &identifier, AutoLaunchParam &param) 2623     AutoLaunchRequestCallback callback = [&encryptedParam](const std::string &identifier, AutoLaunchParam &param) {
2624         if (g_id != identifier) {
2625             return false;
2626         }
2627         param = encryptedParam;
2628         return true;
2629     };
2630     g_mgr.SetAutoLaunchRequestCallback(callback);
2631     /**
2632      * @tc.steps: step3. close store ensure communicator has closed
2633      */
2634     g_mgr.CloseStore(g_rdbDelegatePtr);
2635     g_rdbDelegatePtr = nullptr;
2636     /**
2637      * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
2638      */
2639     LabelType labelType(g_id.begin(), g_id.end());
2640     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
2641     std::this_thread::sleep_for(std::chrono::seconds(1));
2642 
2643     /**
2644      * @tc.steps: step5. Rekey
2645      */
2646     sqlite3 *db = nullptr;
2647     EXPECT_EQ(GetDB(db), SQLITE_OK);
__anon122cc5722902null2648     std::thread t1([&db] {
2649         std::string sql = "PARGMA rekey=" + REKEY_KEY;
2650         EXPECT_EQ(sqlite3_rekey(db, REKEY_KEY.data(), REKEY_KEY.size()), SQLITE_OK);
2651     });
2652     t1.join();
2653     g_isAfterRekey = true;
2654 
2655     /**
2656      * @tc.steps: step6. Call sync expect sync failed
2657      */
2658     Query query = Query::Select(g_tableName);
2659     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
2660     size_t count = 0;
2661     GetCount(db, "SELECT count(*) FROM sqlite_master WHERE name='" + GetDeviceTableName(g_tableName) + "';", count);
2662     EXPECT_EQ(count, 0u);
2663 
2664     /**
2665      * @tc.steps: step7. Set callback.
2666      */
2667     encryptedParam.option.passwd = g_rekeyPasswd;
2668     g_mgr.SetAutoLaunchRequestCallback(callback);
2669     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
2670     std::this_thread::sleep_for(std::chrono::seconds(2));
2671 
2672     /**
2673      * @tc.steps: step8. Call sync expect sync success
2674      */
2675     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
2676     GetCount(db, "SELECT count(*) FROM sqlite_master WHERE name='" + GetDeviceTableName(g_tableName) + "';", count);
2677     EXPECT_EQ(count, 1u);
2678     GetSyncData(db, dataMap, g_tableName, g_fieldInfoList);
2679     EXPECT_EQ(dataMap.size(), 3u);
2680     OpenStore();
2681     std::this_thread::sleep_for(std::chrono::minutes(1));
2682     sqlite3_close(db);
2683     db = nullptr;
2684 }
2685 
2686 /**
2687 * @tc.name: AutoLaunchSyncAfterRekey_002
2688 * @tc.desc: Test auto launch close check after rekey.
2689 * @tc.type: FUNC
2690 * @tc.require: AR000H68LL
2691 * @tc.author: zhangqiquan
2692 */
2693 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSyncAfterRekey_002, TestSize.Level3)
2694 {
2695     /**
2696      * @tc.steps: step1. open rdb store, create distribute table and insert data
2697      */
2698     std::map<std::string, DataValue> dataMap;
2699     PrepareVirtualEnvironment(dataMap, {g_deviceB});
2700     /**
2701      * @tc.steps: step2. set auto launch callBack
2702      */
2703     AutoLaunchParam encryptedParam { USER_ID, APP_ID, STORE_ID_1, AutoLaunchOption {}, nullptr, g_dbDir };
2704     encryptedParam.option.isEncryptedDb = true;
2705     encryptedParam.option.cipher = CipherType::DEFAULT;
2706     encryptedParam.option.passwd = g_correctPasswd;
2707     encryptedParam.option.iterateTimes = DEFAULT_ITER;
__anon122cc5722a02(const std::string &identifier, AutoLaunchParam &param) 2708     AutoLaunchRequestCallback callback = [&encryptedParam](const std::string &identifier, AutoLaunchParam &param) {
2709         param = encryptedParam;
2710         return true;
2711     };
2712     RelationalStoreManager::SetAutoLaunchRequestCallback(callback);
2713     /**
2714      * @tc.steps: step3. close store ensure communicator has closed
2715      */
2716     g_mgr.CloseStore(g_rdbDelegatePtr);
2717     g_rdbDelegatePtr = nullptr;
2718     /**
2719      * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
2720      */
2721     LabelType labelType(g_id.begin(), g_id.end());
2722     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
2723     std::this_thread::sleep_for(std::chrono::seconds(2)); // wait 2s for auto launch
2724     /**
2725      * @tc.steps: step5. Rekey
2726      */
2727     sqlite3 *db = nullptr;
2728     EXPECT_EQ(GetDB(db), SQLITE_OK);
2729     std::string sql = "PARGMA rekey=" + REKEY_KEY;
2730     EXPECT_EQ(sqlite3_rekey(db, REKEY_KEY.data(), REKEY_KEY.size()), SQLITE_OK);
2731     g_isAfterRekey = true;
2732 
2733     RelationalDBProperties properties;
2734     properties.SetStringProp(DBProperties::USER_ID, USER_ID);
2735     properties.SetStringProp(DBProperties::APP_ID, APP_ID);
2736     properties.SetStringProp(DBProperties::STORE_ID, STORE_ID_1);
2737     properties.SetIntProp(DBProperties::AUTO_LAUNCH_ID, 7); // 7: invalid AUTO LAUNCH ID
2738     const string &id = RelationalStoreManager::GetRelationalStoreIdentifier(USER_ID, APP_ID, STORE_ID_1);
2739     properties.SetStringProp(DBProperties::IDENTIFIER_DATA, id);
2740     RuntimeContext::GetInstance()->CloseAutoLaunchConnection(DBTypeInner::DB_RELATION, properties);
2741 
2742     encryptedParam.option.passwd = g_rekeyPasswd;
2743     RelationalStoreManager::SetAutoLaunchRequestCallback(callback);
2744     g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
2745     std::this_thread::sleep_for(std::chrono::seconds(2)); // wait 2s for auto launch
2746 
2747     Query query = Query::Select(g_tableName);
2748     EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
2749     size_t count = 0;
2750     GetCount(db, "SELECT count(*) FROM sqlite_master WHERE name='" + GetDeviceTableName(g_tableName) + "';", count);
2751     EXPECT_EQ(count, 0u);
2752 
2753     OpenStore();
2754     std::this_thread::sleep_for(std::chrono::minutes(1));
2755     sqlite3_close(db);
2756     db = nullptr;
2757 }
2758 
2759 /**
2760 * @tc.name: AutoLaunchSyncAfterRekey_002
2761 * @tc.desc: Test AddSyncTarget will not cause heap_use_after_free
2762 * @tc.type: FUNC
2763 * @tc.require:
2764 * @tc.author: zhangshijie
2765 */
2766 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, SyncTargetTest001, TestSize.Level1) {
2767     MockSyncTaskContext syncTaskContext;
2768     SyncOperation *operation = new SyncOperation(1, {}, 0, nullptr, false);
2769     EXPECT_NE(operation, nullptr);
__anon122cc5722b02() 2770     std::thread addTarget([&syncTaskContext, &operation]() {
2771         auto *newTarget = new (std::nothrow) SingleVerSyncTarget;
2772         EXPECT_NE(newTarget, nullptr);
2773         newTarget->SetTaskType(ISyncTarget::REQUEST);
2774         EXPECT_EQ(syncTaskContext.AddSyncTarget(newTarget), E_OK);
2775         newTarget->SetSyncOperation(operation);
2776     });
2777 
__anon122cc5722c02() 2778     std::thread removeTarget([&syncTaskContext]() {
2779         syncTaskContext.ClearAllSyncTask();
2780     });
2781     addTarget.join();
2782     removeTarget.join();
2783     syncTaskContext.ClearAllSyncTask();
2784     RefObject::KillAndDecObjRef(operation);
2785 }
2786 }
2787 #endif
2788 #endif