• 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 
16 #include <gtest/gtest.h>
17 
18 #include "db_common.h"
19 #include "db_constant.h"
20 #include "db_errno.h"
21 #include "distributeddb_tools_unit_test.h"
22 #include "iprocess_system_api_adapter.h"
23 #include "kv_store_delegate_manager.h"
24 #include "kv_store_nb_delegate.h"
25 #include "log_print.h"
26 #include "platform_specific.h"
27 #include "process_system_api_adapter_impl.h"
28 #include "runtime_context.h"
29 #include "sqlite_single_ver_natural_store.h"
30 #include "sqlite_utils.h"
31 
32 using namespace testing::ext;
33 using namespace DistributedDB;
34 using namespace DistributedDBUnitTest;
35 using namespace std;
36 
37 namespace {
38     // define some variables to init a KvStoreDelegateManager object.
39     KvStoreDelegateManager g_mgr("app0", "user0");
40     enum ForkConcurrentStatus : int {
41         NOT_RUN = 0,
42         RUNNING,
43         FINISHED,
44     };
45     string g_testDir;
46     KvStoreConfig g_config;
47     string g_identifier;
48     string g_databaseName;
49     string g_newDatabaseName;
50     string g_localdatabaseName;
51     Value g_origValue = {'c', 'e'};
52     string g_flag = "2";
53     CipherPassword g_passwd;
54     int g_forkconcurrent = ForkConcurrentStatus::NOT_RUN;
55     static std::shared_ptr<ProcessSystemApiAdapterImpl> g_adapter;
56     string g_maindbPath;
57     string g_metadbPath;
58     string g_cachedbPath;
59     DBStatus g_valueStatus = INVALID_ARGS;
60     Value g_value;
61     auto g_valueCallback = bind(&DistributedDBToolsUnitTest::ValueCallback,
62         placeholders::_1, placeholders::_2, std::ref(g_valueStatus), std::ref(g_value));
63 
64     // define the g_kvNbDelegateCallback, used to get some information when open a kv store.
65     DBStatus g_kvDelegateStatus = INVALID_ARGS;
66     KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr;
67     const std::vector<std::string> ORIG_DATABASE_V1 = {
68         "CREATE TABLE IF NOT EXISTS local_data(key BLOB PRIMARY KEY NOT NULL, value BLOB);",
69         "CREATE TABLE IF NOT EXISTS sync_data(key BLOB NOT NULL, value BLOB, timestamp INT NOT NULL," \
70             "flag INT NOT NULL, device BLOB, ori_device BLOB, hash_key BLOB PRIMARY KEY NOT NULL);",
71         "CREATE TABLE IF NOT EXISTS meta_data(key BLOB PRIMARY KEY NOT NULL, value BLOB);",
72         "CREATE INDEX IF NOT EXISTS key_index ON sync_data (key);",
73         "CREATE INDEX IF NOT EXISTS time_index ON sync_data (timestamp);",
74         "CREATE INDEX IF NOT EXISTS dev_index ON sync_data (device);",
75         "PRAGMA user_version=101;"
76     };
77 
78     const std::vector<std::string> ORIG_DATABASE_V2 = {
79         "CREATE TABLE IF NOT EXISTS local_data(key BLOB PRIMARY KEY NOT NULL," \
80             "value BLOB, timestamp INT, hash_key BLOB);",
81         "CREATE TABLE IF NOT EXISTS sync_data(key BLOB NOT NULL, value BLOB, timestamp INT NOT NULL," \
82             "flag INT NOT NULL, device BLOB, ori_device BLOB, hash_key BLOB PRIMARY KEY NOT NULL, w_timestamp INT);",
83         "CREATE TABLE IF NOT EXISTS meta_data(key BLOB PRIMARY KEY NOT NULL, value BLOB);",
84         "CREATE INDEX IF NOT EXISTS key_index ON sync_data (key, flag);",
85         "CREATE INDEX IF NOT EXISTS time_index ON sync_data (timestamp);",
86         "CREATE INDEX IF NOT EXISTS dev_index ON sync_data (device);",
87         "CREATE INDEX IF NOT EXISTS local_hashkey_index ON local_data (hash_key);",
88         "PRAGMA user_version=102;"
89     };
90 
91     const std::vector<std::string> ORIG_DATABASE_V3 = {
92         "CREATE TABLE IF NOT EXISTS local_data(key BLOB PRIMARY KEY NOT NULL, value BLOB, " \
93             "timestamp INT, hash_key BLOB);",
94         "CREATE TABLE IF NOT EXISTS sync_data(key BLOB NOT NULL, value BLOB, timestamp INT NOT NULL," \
95             "flag INT NOT NULL, device BLOB, ori_device BLOB, hash_key BLOB PRIMARY KEY NOT NULL, w_timestamp INT);",
96         "CREATE INDEX IF NOT EXISTS key_index ON sync_data (key, flag);",
97         "CREATE INDEX IF NOT EXISTS time_index ON sync_data (timestamp);",
98         "CREATE INDEX IF NOT EXISTS dev_index ON sync_data (device);",
99         "CREATE INDEX IF NOT EXISTS local_hashkey_index ON local_data (hash_key);",
100         "PRAGMA user_version=103;"
101     };
102 
103     const std::vector<std::string> INSERT_DATA_V1 = {
104         "INSERT INTO sync_data VALUES('ab', 'cd', 100, 2, '', '', 'efdef');" \
105     };
106 
107     const std::string INSERT_LOCAL_DATA_V1 = {
108         "INSERT INTO local_data VALUES(?, 'ce');"
109     };
110 
111     const std::vector<std::string> INSERT_DATA_V2 = {
112         "INSERT INTO sync_data VALUES('ab', 'cd', 100, " + g_flag + ", '', '', 'efdef', 100);"
113     };
114 
115     const std::string INSERT_LOCAL_DATA_V2 = {
116         "INSERT INTO local_data VALUES(?, 'ce',3169633545069981070,'efdef');"
117     };
118 
119     const std::string INSERT_META_DATA_V2 = {
120         "INSERT INTO meta_data VALUES('ab', 'ce');"
121     };
122 
123     const std::string CHECK_V1_SYNC_UPGRADE =
124         "SELECT w_timestamp, timestamp FROM sync_data;";
125 
126     const std::string CHECK_V2_SYNC_UPGRADE =
127         "SELECT flag FROM sync_data;";
128 
129     const std::string CHECK_V1_LOCAL_UPGRADE =
130         "SELECT timestamp, hash_key FROM local_data;";
131 
KvStoreNbDelegateCallback(DBStatus statusSrc,KvStoreNbDelegate * kvStoreSrc,DBStatus & statusDst,KvStoreNbDelegate * & kvStoreDst)132     void KvStoreNbDelegateCallback(
133         DBStatus statusSrc, KvStoreNbDelegate *kvStoreSrc, DBStatus &statusDst, KvStoreNbDelegate *&kvStoreDst)
134     {
135         statusDst = statusSrc;
136         kvStoreDst = kvStoreSrc;
137     }
138 
139     auto g_kvNbDelegateCallback = bind(&KvStoreNbDelegateCallback, placeholders::_1,
140         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr));
141 
CreateDatabase(const std::vector<std::string> & insertSqls,const std::string & insertLocalDataSql,const OpenDbProperties & property)142     void CreateDatabase(const std::vector<std::string> &insertSqls, const std::string &insertLocalDataSql,
143         const OpenDbProperties &property)
144     {
145         sqlite3 *db = nullptr;
146         EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
147         ASSERT_NE(db, nullptr);
148 
149         for (const auto &item : insertSqls) {
150             ASSERT_EQ(SQLiteUtils::ExecuteRawSQL(db, item), E_OK);
151         }
152         sqlite3_stmt *statement = nullptr;
153         ASSERT_EQ(SQLiteUtils::GetStatement(db, insertLocalDataSql, statement), E_OK);
154         ASSERT_NE(statement, nullptr);
155         EXPECT_EQ(SQLiteUtils::BindBlobToStatement(statement, 1, g_origValue, false), E_OK);
156         EXPECT_EQ(SQLiteUtils::StepWithRetry(statement, false), -SQLITE_DONE);
157         EXPECT_EQ(sqlite3_finalize(statement), SQLITE_OK);
158 
159         (void)sqlite3_close_v2(db);
160     }
161 
CheckSyncDataV1ToV2(sqlite3 * db)162     void CheckSyncDataV1ToV2(sqlite3 *db)
163     {
164         sqlite3_stmt *statement = nullptr;
165         ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V1_SYNC_UPGRADE, statement), E_OK);
166         ASSERT_NE(statement, nullptr);
167         ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
168         ASSERT_EQ(sqlite3_column_int64(statement, 0), sqlite3_column_int64(statement, 1));
169         ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
170     }
171 
CheckSyncDataV2ToV3(sqlite3 * db)172     void CheckSyncDataV2ToV3(sqlite3 *db)
173     {
174         sqlite3_stmt *statement = nullptr;
175         ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V2_SYNC_UPGRADE, statement), E_OK);
176         ASSERT_NE(statement, nullptr);
177         ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
178         long int targetFlagValue = sqlite3_column_int64(statement, 0);
179         ASSERT_EQ(targetFlagValue, stol(g_flag));
180         ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
181     }
182 
CheckLocalDataV1ToV2(sqlite3 * db)183     void CheckLocalDataV1ToV2(sqlite3 *db)
184     {
185         sqlite3_stmt *statement = nullptr;
186         ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V1_LOCAL_UPGRADE, statement), E_OK);
187         ASSERT_NE(statement, nullptr);
188         ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
189         Timestamp stamp = static_cast<uint64_t>(sqlite3_column_int64(statement, 0));
190         EXPECT_NE(stamp, 0UL);
191 
192         Value readHashValue;
193         Value calcValue;
194         EXPECT_EQ(DBCommon::CalcValueHash(g_origValue, calcValue), E_OK);
195         ASSERT_EQ(SQLiteUtils::GetColumnBlobValue(statement, 1, readHashValue), E_OK);
196         EXPECT_EQ(readHashValue, calcValue);
197         ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
198     }
199 
CheckDirectoryV2ToV3(bool expectedValue,bool expecteMetaDbExist)200     void CheckDirectoryV2ToV3(bool expectedValue, bool expecteMetaDbExist)
201     {
202         std::string identifier = DBCommon::TransferStringToHex(g_identifier);
203         std::string newDatabaseName = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
204             DBConstant::MAINDB_DIR + "/" + DBConstant::SINGLE_VER_DATA_STORE + ".db";
205         std::string newMetadatabaseName = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
206             DBConstant::METADB_DIR + "/" + DBConstant::SINGLE_VER_META_STORE + ".db";
207         std::string newCacheDirectory = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
208             DBConstant::CACHEDB_DIR + "/";
209         EXPECT_EQ(OS::CheckPathExistence(newDatabaseName), expectedValue);
210         EXPECT_EQ(OS::CheckPathExistence(newMetadatabaseName), expecteMetaDbExist);
211         EXPECT_EQ(OS::CheckPathExistence(newCacheDirectory), expectedValue);
212     }
213 
CheckVersionV3(sqlite3 * db)214     void CheckVersionV3(sqlite3 *db)
215     {
216         int version = SOFTWARE_VERSION_BASE;
217         SQLiteUtils::GetVersion(db, version);
218         EXPECT_EQ(version, SINGLE_VER_STORE_VERSION_CURRENT);
219     }
220 
CheckSecOpt(const SecurityOption & currentSecOpt)221     void CheckSecOpt(const SecurityOption &currentSecOpt)
222     {
223         SecurityOption checkSecOpt;
224         SecurityOption currentMetaSecOpt {SecurityLabel::S2, SecurityFlag::ECE};
225         int errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_maindbPath, checkSecOpt);
226         EXPECT_TRUE(currentSecOpt == checkSecOpt);
227         EXPECT_TRUE(errCode == E_OK);
228         if (OS::CheckPathExistence(g_cachedbPath)) {
229             errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_cachedbPath, checkSecOpt);
230             EXPECT_TRUE(currentSecOpt == checkSecOpt);
231             EXPECT_TRUE(errCode == E_OK);
232         }
233         if (OS::CheckPathExistence(g_metadbPath)) {
234             errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_metadbPath, checkSecOpt);
235             EXPECT_TRUE(currentMetaSecOpt == checkSecOpt);
236             EXPECT_TRUE(errCode == E_OK);
237         }
238     }
239 
GetKvStoreProcess(const KvStoreNbDelegate::Option & option,bool putCheck,bool secOptCheck,const SecurityOption & secopt)240     void GetKvStoreProcess(const KvStoreNbDelegate::Option &option, bool putCheck, bool secOptCheck,
241         const SecurityOption &secopt)
242     {
243         Key keyTmp = {'1'};
244         Value valueRead;
245         Value value = {'7'};
246         g_mgr.GetKvStore("TestUpgradeNb", option, g_kvNbDelegateCallback);
247         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
248         EXPECT_TRUE(g_kvDelegateStatus == OK);
249         if (secOptCheck) {
250             CheckSecOpt(secopt);
251         }
252         if (putCheck) {
253             EXPECT_TRUE(g_kvNbDelegatePtr->Put(keyTmp, value) == OK);
254             EXPECT_TRUE(g_kvNbDelegatePtr->Get(keyTmp, valueRead) == OK);
255         }
256         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
257         g_kvNbDelegatePtr = nullptr;
258     }
259 }
260 
261 class DistributedDBStorageSingleVerUpgradeTest : public testing::Test {
262 public:
263     static void SetUpTestCase(void);
264     static void TearDownTestCase(void);
265     void SetUp();
266     void TearDown();
267 };
268 
SetUpTestCase(void)269 void DistributedDBStorageSingleVerUpgradeTest::SetUpTestCase(void)
270 {
271     DistributedDBToolsUnitTest::TestDirInit(g_testDir);
272     g_config.dataDir = g_testDir;
273     g_mgr.SetKvStoreConfig(g_config);
274 
275     std::string oriIdentifier = "user0-app0-TestUpgradeNb";
276     g_identifier = DBCommon::TransferHashString(oriIdentifier);
277     std::string identifier = DBCommon::TransferStringToHex(g_identifier);
278     g_databaseName = "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
279         DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION;
280     g_newDatabaseName = "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR + "/" +
281         DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION;
282     g_localdatabaseName = "/" + identifier + "/" + DBConstant::LOCAL_SUB_DIR + "/" +
283         DBConstant::LOCAL_DATABASE_NAME + DBConstant::SQLITE_DB_EXTENSION;
284     const int passwdLen = 5;
285     const int passwdVal = 1;
286     vector<uint8_t> passwdBuffer1(passwdLen, passwdVal);
287     int errCode = g_passwd.SetValue(passwdBuffer1.data(), passwdBuffer1.size());
288     ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK);
289     g_adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
290     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
291     g_maindbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR +
292         "/" + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION;
293     g_metadbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::METADB_DIR +
294         "/" + DBConstant::SINGLE_VER_META_STORE + DBConstant::SQLITE_DB_EXTENSION;
295     g_cachedbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::CACHEDB_DIR +
296         "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::SQLITE_DB_EXTENSION;
297 }
298 
TearDownTestCase(void)299 void DistributedDBStorageSingleVerUpgradeTest::TearDownTestCase(void)
300 {
301     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
302 }
303 
SetUp(void)304 void DistributedDBStorageSingleVerUpgradeTest::SetUp(void)
305 {
306     DistributedDBToolsUnitTest::PrintTestCaseInfo();
307     std::string identifier = DBCommon::TransferStringToHex(g_identifier);
308     DBCommon::CreateDirectory(g_testDir + "/" + identifier);
309     DBCommon::CreateDirectory(g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR);
310     DBCommon::CreateDirectory(g_testDir + "/" + identifier + "/" + DBConstant::LOCAL_SUB_DIR);
311 }
312 
TearDown(void)313 void DistributedDBStorageSingleVerUpgradeTest::TearDown(void)
314 {
315     while (g_forkconcurrent == ForkConcurrentStatus::RUNNING) {
316         sleep(1);
317     }
318     g_adapter->ResetSecOptDic();
319     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
320         LOGE("rm test db files error!");
321     }
322 }
323 
324 /**
325   * @tc.name: UpgradeTest001
326   * @tc.desc: Test the NbDelegate upgrade from the old version V1.
327   * @tc.type: FUNC
328   * @tc.require: AR000DPTQ7
329   * @tc.author: wangbingquan
330   */
331 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest001, TestSize.Level2)
332 {
333     /**
334      * @tc.steps:step1. create old version V1 db.
335      */
336     std::string dbPath = g_testDir + g_databaseName;
337     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V1};
338     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
339     SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
340     CreateDatabase(INSERT_DATA_V1, INSERT_LOCAL_DATA_V1, property);
341     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
342     EXPECT_EQ(isDatabaseExists, true);
343     /**
344      * @tc.steps:step2. Get the nb delegate.
345      * @tc.expected: step1. Get results OK and non-null delegate.
346      */
347     KvStoreNbDelegate::Option option = {true, false, false};
348     option.secOption = secopt;
349     GetKvStoreProcess(option, true, true, SecurityOption());
350 
351     sqlite3 *db = nullptr;
352     dbPath = g_testDir + g_newDatabaseName;
353     property = {dbPath, true, false};
354     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
355     ASSERT_NE(db, nullptr);
356     /**
357      * @tc.steps:step3. check result is ok.
358      * @tc.expected: dir is ok,version is ok.
359      */
360     CheckLocalDataV1ToV2(db);
361     CheckSyncDataV1ToV2(db);
362     CheckDirectoryV2ToV3(true, false);
363     CheckVersionV3(db);
364     (void)sqlite3_close_v2(db);
365     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
366 }
367 
368 /**
369   * @tc.name: UpgradeTest002
370   * @tc.desc: Test the NbDelegate upgrade from the old version V2.
371   * @tc.type: FUNC
372   * @tc.require: AR000DPTQ7
373   * @tc.author: zhuwentao
374   */
375 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest002, TestSize.Level2)
376 {
377     /**
378      * @tc.steps:step1. create old version V2 db.
379      */
380     std::string dbPath = g_testDir + g_databaseName;
381     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
382     CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
383     SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
384     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
385     EXPECT_EQ(isDatabaseExists, true);
386     /**
387      * @tc.steps:step2. Get the nb delegate.
388      * @tc.expected: step1. Get results OK and non-null delegate.
389      */
390     KvStoreNbDelegate::Option option = {true, false, false};
391     option.secOption = secopt;
392     GetKvStoreProcess(option, true, true, SecurityOption());
393 
394     sqlite3 *db = nullptr;
395     dbPath = g_testDir + g_newDatabaseName;
396     property = {dbPath, true, false};
397     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
398     ASSERT_NE(db, nullptr);
399     /**
400      * @tc.steps:step3. check result is ok.
401      * @tc.expected: dir is ok,version is ok.
402      */
403     CheckDirectoryV2ToV3(true, false);
404     CheckVersionV3(db);
405     (void)sqlite3_close_v2(db);
406     GetKvStoreProcess(option, false, true, SecurityOption());
407     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
408 }
409 #ifndef OMIT_JSON
410 /**
411   * @tc.name: UpgradeTest003
412   * @tc.desc: Test the NbDelegate upgrade from the old version V2 with schema.
413   * @tc.type: FUNC
414   * @tc.require: AR000DPTQ7
415   * @tc.author: zhuwentao
416   */
417 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest003, TestSize.Level2)
418 {
419     /**
420      * @tc.steps:step1. create old version V2 db.
421      */
422     std::string dbPath = g_testDir + g_databaseName;
423     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
424     std::string val = "{\"field_name1\":true, \"field_name2\":{\"field_name3\":1, \"field_name4\":1, \"field_name5\":1,\
425         \"field_name6\":\"1\", \"field_name7\":null, \"field_name8\":null}}";
426     std::string insertValueSql = "INSERT INTO sync_data VALUES('ab', '";
427     insertValueSql += val;
428     insertValueSql += "', 100, " + g_flag + ", '', '', 'efdef', 100);";
429     CreateDatabase(std::vector<std::string> {insertValueSql}, INSERT_LOCAL_DATA_V2, property);
430     SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
431     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
432     EXPECT_EQ(isDatabaseExists, true);
433     /**
434      * @tc.steps:step2. Get the nb delegate.
435      * @tc.expected: step1. Get results OK and non-null delegate.
436      */
437     KvStoreNbDelegate::Option option = {true, false, false};
438     option.secOption = secopt;
439     option.schema = "{\"SCHEMA_VERSION\":\"1.0\","
440                     "\"SCHEMA_MODE\":\"STRICT\","
441                     "\"SCHEMA_DEFINE\":{"
442                         "\"field_name1\":\"BOOL\","
443                         "\"field_name2\":{"
444                             "\"field_name3\":\"INTEGER, NOT NULL\","
445                             "\"field_name4\":\"LONG, DEFAULT 100\","
446                             "\"field_name5\":\"DOUBLE, NOT NULL, DEFAULT 3.14\","
447                             "\"field_name6\":\"STRING, NOT NULL, DEFAULT '3.1415'\","
448                             "\"field_name7\":[],"
449                             "\"field_name8\":{}"
450                         "}"
451                     "},"
452                     "\"SCHEMA_INDEXES\":[\"$.field_name1\", \"$.field_name2.field_name6\"]}";
453     GetKvStoreProcess(option, false, true, SecurityOption());
454 
455     sqlite3 *db = nullptr;
456     dbPath = g_testDir + g_newDatabaseName;
457     property = {dbPath, true, false};
458     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
459     ASSERT_NE(db, nullptr);
460     /**
461      * @tc.steps:step3. check result is ok.
462      * @tc.expected: dir is ok,version is ok.
463      */
464     CheckDirectoryV2ToV3(true, false);
465     CheckVersionV3(db);
466     (void)sqlite3_close_v2(db);
467 
468     GetKvStoreProcess(option, false, true, SecurityOption());
469     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
470 }
471 #endif
472 /**
473   * @tc.name: UpgradeTest004
474   * @tc.desc: Test the NbDelegate upgrade from the old version V2 while secOption from NOT_SET to S3SECE.
475   * @tc.type: FUNC
476   * @tc.require: AR000DPTQ7
477   * @tc.author: zhuwentao
478   */
479 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest004, TestSize.Level2)
480 {
481     /**
482      * @tc.steps:step1. create old version V2 db.
483      */
484     std::string dbPath = g_testDir + g_databaseName;
485     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
486     CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
487     SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
488     SecurityOption checkSecOpt;
489     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
490     EXPECT_EQ(isDatabaseExists, true);
491     /**
492      * @tc.steps:step2. Get the nb delegate without secoption and Get the nb delegate again with secoption.
493      * @tc.expected: step1. Get results OK and non-null delegate.
494      */
495     KvStoreNbDelegate::Option option = {true, false, false};
496     GetKvStoreProcess(option, false, true, SecurityOption());
497     RuntimeContext::GetInstance()->GetSecurityOption(g_maindbPath, checkSecOpt);
498     EXPECT_TRUE(checkSecOpt.securityLabel == NOT_SET);
499 
500     option.secOption = secopt;
501     GetKvStoreProcess(option, true, true, SecurityOption());
502 
503     sqlite3 *db = nullptr;
504     dbPath = g_testDir + g_newDatabaseName;
505     property = {dbPath, true, false};
506     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
507     ASSERT_NE(db, nullptr);
508     /**
509      * @tc.steps:step3. check result is ok.
510      * @tc.expected: dir is ok,version is ok.
511      */
512     CheckDirectoryV2ToV3(true, false);
513     CheckVersionV3(db);
514     (void)sqlite3_close_v2(db);
515 
516     GetKvStoreProcess(option, false, false, secopt);
517     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
518 }
519 
520 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest005, TestSize.Level2)
521 {
522     /**
523      * @tc.steps:step1. create old version V2 db.
524      */
525     std::string dbPath = g_testDir + g_databaseName;
526     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
527     CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
528     SecurityOption secopt = {SecurityLabel::S2, SecurityFlag::ECE};
529     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
530     EXPECT_EQ(isDatabaseExists, true);
531     /**
532      * @tc.steps:step2. Get the nb delegate while not sprite meta_db scene
533      * @tc.expected: step1. Get results OK and non-null delegate.
534      */
535     KvStoreNbDelegate::Option option = {true, false, false};
536     option.secOption = secopt;
537     GetKvStoreProcess(option, true, true, SecurityOption());
538 
539     sqlite3 *db = nullptr;
540     dbPath = g_testDir + g_newDatabaseName;
541     property = {dbPath, true, false};
542     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
543     ASSERT_NE(db, nullptr);
544     /**
545      * @tc.steps:step3. check result is ok.
546      * @tc.expected: dir is ok,version is ok.
547      */
548     CheckSyncDataV2ToV3(db);
549     CheckDirectoryV2ToV3(true, false);
550     CheckVersionV3(db);
551     (void)sqlite3_close_v2(db);
552     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
553 }
554 
555 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest006, TestSize.Level2)
556 {
557     /**
558      * @tc.steps:step1. create old version V2 db.
559      */
560     std::string dbPath = g_testDir + g_databaseName;
561     OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
562     CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
563     SecurityOption secopt = {SecurityLabel::S3, SecurityFlag::ECE};
564     bool isDatabaseExists = OS::CheckPathExistence(dbPath);
565     EXPECT_EQ(isDatabaseExists, true);
566     /**
567      * @tc.steps:step2. Get the nb delegate while not sprite meta_db scene
568      * @tc.expected: step2. Get results OK and non-null delegate.
569      */
570     KvStoreNbDelegate::Option option = {true, false, false};
571     option.secOption = secopt;
572     GetKvStoreProcess(option, true, true, SecurityOption());
573 
574     sqlite3 *db = nullptr;
575     dbPath = g_testDir + g_newDatabaseName;
576     property = {dbPath, true, false};
577     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
578     ASSERT_NE(db, nullptr);
579     /**
580      * @tc.steps:step3. check result is ok.
581      * @tc.expected: dir is ok,version is ok.
582      */
583     CheckSyncDataV2ToV3(db);
584     CheckDirectoryV2ToV3(true, false);
585     CheckVersionV3(db);
586     (void)sqlite3_close_v2(db);
587     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
588 }
589 
590 /**
591   * @tc.name: UpgradeErrTest001
592   * @tc.desc: Upgrade test when db file exists
593   * @tc.type: FUNC
594   * @tc.require:
595   * @tc.author: bty
596   */
597 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeErrTest001, TestSize.Level2)
598 {
599     /**
600      * @tc.steps:step1. Upgrade after creating an upgrade Lock File
601      * @tc.expected: the upgrade lock File was deleted
602      */
603     KvStoreNbDelegate::Option option = {true, false, false};
604     std::string upgradeLockFileDir = g_testDir + "/" + DBCommon::TransferStringToHex(g_identifier)
605         + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::UPGRADE_POSTFIX;
606     EXPECT_EQ(OS::CreateFileByFileName(upgradeLockFileDir), E_OK);
607     GetKvStoreProcess(option, false, false, SecurityOption());
608     EXPECT_FALSE(OS::CheckPathExistence(upgradeLockFileDir));
609 
610     /**
611      * @tc.steps:step2. Upgrade after opening a db File
612      * @tc.expected: the db File was deleted
613      */
614     sqlite3 *db = nullptr;
615     std::string dbPath = g_testDir + g_databaseName;
616     OpenDbProperties property = {dbPath, true, false};
617     EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
618     ASSERT_NE(db, nullptr);
619     EXPECT_TRUE(OS::CheckPathExistence(dbPath));
620     GetKvStoreProcess(option, false, false, SecurityOption());
621     EXPECT_FALSE(OS::CheckPathExistence(dbPath));
622     (void)sqlite3_close_v2(db);
623     EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
624 }