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 LOGW("sql is %s", item.c_str());
151 ASSERT_EQ(SQLiteUtils::ExecuteRawSQL(db, item), E_OK);
152 }
153 sqlite3_stmt *statement = nullptr;
154 ASSERT_EQ(SQLiteUtils::GetStatement(db, insertLocalDataSql, statement), E_OK);
155 ASSERT_NE(statement, nullptr);
156 EXPECT_EQ(SQLiteUtils::BindBlobToStatement(statement, 1, g_origValue, false), E_OK);
157 EXPECT_EQ(SQLiteUtils::StepWithRetry(statement, false), -SQLITE_DONE);
158 EXPECT_EQ(sqlite3_finalize(statement), SQLITE_OK);
159
160 (void)sqlite3_close_v2(db);
161 }
162
CheckSyncDataV1ToV2(sqlite3 * db)163 void CheckSyncDataV1ToV2(sqlite3 *db)
164 {
165 sqlite3_stmt *statement = nullptr;
166 ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V1_SYNC_UPGRADE, statement), E_OK);
167 ASSERT_NE(statement, nullptr);
168 ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
169 ASSERT_EQ(sqlite3_column_int64(statement, 0), sqlite3_column_int64(statement, 1));
170 ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
171 }
172
CheckSyncDataV2ToV3(sqlite3 * db)173 void CheckSyncDataV2ToV3(sqlite3 *db)
174 {
175 sqlite3_stmt *statement = nullptr;
176 ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V2_SYNC_UPGRADE, statement), E_OK);
177 ASSERT_NE(statement, nullptr);
178 ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
179 long int targetFlagValue = sqlite3_column_int64(statement, 0);
180 ASSERT_EQ(targetFlagValue, stol(g_flag));
181 ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
182 }
183
CheckLocalDataV1ToV2(sqlite3 * db)184 void CheckLocalDataV1ToV2(sqlite3 *db)
185 {
186 sqlite3_stmt *statement = nullptr;
187 ASSERT_EQ(SQLiteUtils::GetStatement(db, CHECK_V1_LOCAL_UPGRADE, statement), E_OK);
188 ASSERT_NE(statement, nullptr);
189 ASSERT_EQ(SQLiteUtils::StepWithRetry(statement), SQLiteUtils::MapSQLiteErrno(SQLITE_ROW));
190 Timestamp stamp = static_cast<uint64_t>(sqlite3_column_int64(statement, 0));
191 EXPECT_NE(stamp, 0UL);
192
193 Value readHashValue;
194 Value calcValue;
195 EXPECT_EQ(DBCommon::CalcValueHash(g_origValue, calcValue), E_OK);
196 ASSERT_EQ(SQLiteUtils::GetColumnBlobValue(statement, 1, readHashValue), E_OK);
197 EXPECT_EQ(readHashValue, calcValue);
198 ASSERT_EQ(sqlite3_finalize(statement), SQLITE_OK);
199 }
200
CheckDirectoryV2ToV3(bool expectedValue,bool expecteMetaDbExist)201 void CheckDirectoryV2ToV3(bool expectedValue, bool expecteMetaDbExist)
202 {
203 std::string identifier = DBCommon::TransferStringToHex(g_identifier);
204 std::string newDatabaseName = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
205 DBConstant::MAINDB_DIR + "/" + DBConstant::SINGLE_VER_DATA_STORE + ".db";
206 std::string newMetadatabaseName = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
207 DBConstant::METADB_DIR + "/" + DBConstant::SINGLE_VER_META_STORE + ".db";
208 std::string newCacheDirectory = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
209 DBConstant::CACHEDB_DIR + "/";
210 EXPECT_EQ(OS::CheckPathExistence(newDatabaseName), expectedValue);
211 EXPECT_EQ(OS::CheckPathExistence(newMetadatabaseName), expecteMetaDbExist);
212 EXPECT_EQ(OS::CheckPathExistence(newCacheDirectory), expectedValue);
213 }
214
CheckVersionV3(sqlite3 * db)215 void CheckVersionV3(sqlite3 *db)
216 {
217 int version = SOFTWARE_VERSION_BASE;
218 SQLiteUtils::GetVersion(db, version);
219 EXPECT_EQ(version, SINGLE_VER_STORE_VERSION_CURRENT);
220 }
221
CheckSecOpt(const SecurityOption & currentSecOpt)222 void CheckSecOpt(const SecurityOption ¤tSecOpt)
223 {
224 SecurityOption checkSecOpt;
225 SecurityOption currentMetaSecOpt {SecurityLabel::S2, SecurityFlag::ECE};
226 int errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_maindbPath, checkSecOpt);
227 EXPECT_EQ(currentSecOpt.securityLabel, checkSecOpt.securityLabel);
228 EXPECT_EQ(currentSecOpt.securityFlag, checkSecOpt.securityFlag);
229 EXPECT_EQ(errCode, E_OK);
230 if (OS::CheckPathExistence(g_cachedbPath)) {
231 errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_cachedbPath, checkSecOpt);
232 EXPECT_TRUE(currentSecOpt == checkSecOpt);
233 EXPECT_TRUE(errCode == E_OK);
234 }
235 if (OS::CheckPathExistence(g_metadbPath)) {
236 errCode = RuntimeContext::GetInstance()->GetSecurityOption(g_metadbPath, checkSecOpt);
237 EXPECT_TRUE(currentMetaSecOpt == checkSecOpt);
238 EXPECT_TRUE(errCode == E_OK);
239 }
240 }
241
GetKvStoreProcess(const KvStoreNbDelegate::Option & option,bool putCheck,bool secOptCheck,const SecurityOption & secopt)242 void GetKvStoreProcess(const KvStoreNbDelegate::Option &option, bool putCheck, bool secOptCheck,
243 const SecurityOption &secopt)
244 {
245 Key keyTmp = {'1'};
246 Value valueRead;
247 Value value = {'7'};
248 g_mgr.GetKvStore("TestUpgradeNb", option, g_kvNbDelegateCallback);
249 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
250 EXPECT_TRUE(g_kvDelegateStatus == OK);
251 if (secOptCheck) {
252 CheckSecOpt(secopt);
253 }
254 if (putCheck) {
255 EXPECT_TRUE(g_kvNbDelegatePtr->Put(keyTmp, value) == OK);
256 EXPECT_TRUE(g_kvNbDelegatePtr->Get(keyTmp, valueRead) == OK);
257 }
258 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
259 g_kvNbDelegatePtr = nullptr;
260 }
261 }
262
263 class DistributedDBStorageSingleVerUpgradeTest : public testing::Test {
264 public:
265 static void SetUpTestCase(void);
266 static void TearDownTestCase(void);
267 void SetUp();
268 void TearDown();
269 };
270
SetUpTestCase(void)271 void DistributedDBStorageSingleVerUpgradeTest::SetUpTestCase(void)
272 {
273 DistributedDBToolsUnitTest::TestDirInit(g_testDir);
274 g_config.dataDir = g_testDir;
275 g_mgr.SetKvStoreConfig(g_config);
276
277 std::string oriIdentifier = "user0-app0-TestUpgradeNb";
278 g_identifier = DBCommon::TransferHashString(oriIdentifier);
279 std::string identifier = DBCommon::TransferStringToHex(g_identifier);
280 g_databaseName = "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
281 DBConstant::SINGLE_VER_DATA_STORE + DBConstant::DB_EXTENSION;
282 g_newDatabaseName = "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR + "/" +
283 DBConstant::SINGLE_VER_DATA_STORE + DBConstant::DB_EXTENSION;
284 g_localdatabaseName = "/" + identifier + "/" + DBConstant::LOCAL_SUB_DIR + "/" +
285 DBConstant::LOCAL_DATABASE_NAME + DBConstant::DB_EXTENSION;
286 const int passwdLen = 5;
287 const int passwdVal = 1;
288 vector<uint8_t> passwdBuffer1(passwdLen, passwdVal);
289 int errCode = g_passwd.SetValue(passwdBuffer1.data(), passwdBuffer1.size());
290 ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK);
291 g_adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
292 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
293 g_maindbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR +
294 "/" + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::DB_EXTENSION;
295 g_metadbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::METADB_DIR +
296 "/" + DBConstant::SINGLE_VER_META_STORE + DBConstant::DB_EXTENSION;
297 g_cachedbPath = g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::CACHEDB_DIR +
298 "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::DB_EXTENSION;
299 }
300
TearDownTestCase(void)301 void DistributedDBStorageSingleVerUpgradeTest::TearDownTestCase(void)
302 {
303 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
304 }
305
SetUp(void)306 void DistributedDBStorageSingleVerUpgradeTest::SetUp(void)
307 {
308 DistributedDBToolsUnitTest::PrintTestCaseInfo();
309 std::string identifier = DBCommon::TransferStringToHex(g_identifier);
310 DBCommon::CreateDirectory(g_testDir + "/" + identifier);
311 DBCommon::CreateDirectory(g_testDir + "/" + identifier + "/" + DBConstant::SINGLE_SUB_DIR);
312 DBCommon::CreateDirectory(g_testDir + "/" + identifier + "/" + DBConstant::LOCAL_SUB_DIR);
313 }
314
TearDown(void)315 void DistributedDBStorageSingleVerUpgradeTest::TearDown(void)
316 {
317 while (g_forkconcurrent == ForkConcurrentStatus::RUNNING) {
318 sleep(1);
319 }
320 g_adapter->ResetSecOptDic();
321 if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
322 LOGE("rm test db files error!");
323 }
324 }
325
326 /**
327 * @tc.name: UpgradeTest001
328 * @tc.desc: Test the NbDelegate upgrade from the old version V1.
329 * @tc.type: FUNC
330 * @tc.require: AR000DPTQ7
331 * @tc.author: wangbingquan
332 */
333 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest001, TestSize.Level0)
334 {
335 /**
336 * @tc.steps:step1. create old version V1 db.
337 */
338 std::string dbPath = g_testDir + g_databaseName;
339 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V1};
340 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
341 SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
342 CreateDatabase(INSERT_DATA_V1, INSERT_LOCAL_DATA_V1, property);
343 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
344 EXPECT_EQ(isDatabaseExists, true);
345 /**
346 * @tc.steps:step2. Get the nb delegate.
347 * @tc.expected: step1. Get results OK and non-null delegate.
348 */
349 KvStoreNbDelegate::Option option = {true, false, false};
350 option.secOption = secopt;
351 // check sec option update to s3
352 GetKvStoreProcess(option, true, true, secopt);
353
354 sqlite3 *db = nullptr;
355 dbPath = g_testDir + g_newDatabaseName;
356 property = {dbPath, true, false};
357 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
358 ASSERT_NE(db, nullptr);
359 /**
360 * @tc.steps:step3. check result is ok.
361 * @tc.expected: dir is ok,version is ok.
362 */
363 CheckLocalDataV1ToV2(db);
364 CheckSyncDataV1ToV2(db);
365 // sec option update to s3, create cache db
366 CheckDirectoryV2ToV3(true, true);
367 CheckVersionV3(db);
368 (void)sqlite3_close_v2(db);
369 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
370 }
371
372 /**
373 * @tc.name: UpgradeTest002
374 * @tc.desc: Test the NbDelegate upgrade from the old version V2.
375 * @tc.type: FUNC
376 * @tc.require: AR000DPTQ7
377 * @tc.author: zhuwentao
378 */
379 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest002, TestSize.Level2)
380 {
381 /**
382 * @tc.steps:step1. create old version V2 db.
383 */
384 std::string dbPath = g_testDir + g_databaseName;
385 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
386 CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
387 SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
388 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
389 EXPECT_EQ(isDatabaseExists, true);
390 /**
391 * @tc.steps:step2. Get the nb delegate.
392 * @tc.expected: step1. Get results OK and non-null delegate.
393 */
394 KvStoreNbDelegate::Option option = {true, false, false};
395 option.secOption = secopt;
396 // check sec option update to s3
397 GetKvStoreProcess(option, true, true, secopt);
398
399 sqlite3 *db = nullptr;
400 dbPath = g_testDir + g_newDatabaseName;
401 property = {dbPath, true, false};
402 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
403 ASSERT_NE(db, nullptr);
404 /**
405 * @tc.steps:step3. check result is ok.
406 * @tc.expected: dir is ok,version is ok.
407 */
408 // sec option update to s3, create cache db
409 CheckDirectoryV2ToV3(true, true);
410 CheckVersionV3(db);
411 (void)sqlite3_close_v2(db);
412 // check sec option update to s3
413 GetKvStoreProcess(option, false, true, secopt);
414 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
415 }
416 #ifndef OMIT_JSON
417 /**
418 * @tc.name: UpgradeTest003
419 * @tc.desc: Test the NbDelegate upgrade from the old version V2 with schema.
420 * @tc.type: FUNC
421 * @tc.require: AR000DPTQ7
422 * @tc.author: zhuwentao
423 */
424 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest003, TestSize.Level2)
425 {
426 /**
427 * @tc.steps:step1. create old version V2 db.
428 */
429 std::string dbPath = g_testDir + g_databaseName;
430 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
431 std::string val = "{\"field_name1\":true, \"field_name2\":{\"field_name3\":1, \"field_name4\":1, \"field_name5\":1,\
432 \"field_name6\":\"1\", \"field_name7\":null, \"field_name8\":null}}";
433 std::string insertValueSql = "INSERT INTO sync_data VALUES('ab', '";
434 insertValueSql += val;
435 insertValueSql += "', 100, " + g_flag + ", '', '', 'efdef', 100);";
436 CreateDatabase(std::vector<std::string> {insertValueSql}, INSERT_LOCAL_DATA_V2, property);
437 SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
438 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
439 EXPECT_EQ(isDatabaseExists, true);
440 /**
441 * @tc.steps:step2. Get the nb delegate.
442 * @tc.expected: step1. Get results OK and non-null delegate.
443 */
444 KvStoreNbDelegate::Option option = {true, false, false};
445 option.secOption = secopt;
446 option.schema = "{\"SCHEMA_VERSION\":\"1.0\","
447 "\"SCHEMA_MODE\":\"STRICT\","
448 "\"SCHEMA_DEFINE\":{"
449 "\"field_name1\":\"BOOL\","
450 "\"field_name2\":{"
451 "\"field_name3\":\"INTEGER, NOT NULL\","
452 "\"field_name4\":\"LONG, DEFAULT 100\","
453 "\"field_name5\":\"DOUBLE, NOT NULL, DEFAULT 3.14\","
454 "\"field_name6\":\"STRING, NOT NULL, DEFAULT '3.1415'\","
455 "\"field_name7\":[],"
456 "\"field_name8\":{}"
457 "}"
458 "},"
459 "\"SCHEMA_INDEXES\":[\"$.field_name1\", \"$.field_name2.field_name6\"]}";
460 GetKvStoreProcess(option, false, true, secopt);
461
462 sqlite3 *db = nullptr;
463 dbPath = g_testDir + g_newDatabaseName;
464 property = {dbPath, true, false};
465 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
466 ASSERT_NE(db, nullptr);
467 /**
468 * @tc.steps:step3. check result is ok.
469 * @tc.expected: dir is ok,version is ok.
470 */
471 CheckDirectoryV2ToV3(true, true);
472 CheckVersionV3(db);
473 (void)sqlite3_close_v2(db);
474
475 GetKvStoreProcess(option, false, true, secopt);
476 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
477 }
478 #endif
479 /**
480 * @tc.name: UpgradeTest004
481 * @tc.desc: Test the NbDelegate upgrade from the old version V2 while secOption from NOT_SET to S3SECE.
482 * @tc.type: FUNC
483 * @tc.require: AR000DPTQ7
484 * @tc.author: zhuwentao
485 */
486 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest004, TestSize.Level2)
487 {
488 /**
489 * @tc.steps:step1. create old version V2 db.
490 */
491 std::string dbPath = g_testDir + g_databaseName;
492 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
493 CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
494 SecurityOption secopt{SecurityLabel::S3, SecurityFlag::SECE};
495 SecurityOption checkSecOpt;
496 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
497 EXPECT_EQ(isDatabaseExists, true);
498 /**
499 * @tc.steps:step2. Get the nb delegate without secoption and Get the nb delegate again with secoption.
500 * @tc.expected: step1. Get results OK and non-null delegate.
501 */
502 KvStoreNbDelegate::Option option = {true, false, false};
503 GetKvStoreProcess(option, false, true, SecurityOption());
504 RuntimeContext::GetInstance()->GetSecurityOption(g_maindbPath, checkSecOpt);
505 EXPECT_TRUE(checkSecOpt.securityLabel == NOT_SET);
506
507 option.secOption = secopt;
508 GetKvStoreProcess(option, true, true, secopt);
509
510 sqlite3 *db = nullptr;
511 dbPath = g_testDir + g_newDatabaseName;
512 property = {dbPath, true, false};
513 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
514 ASSERT_NE(db, nullptr);
515 /**
516 * @tc.steps:step3. check result is ok.
517 * @tc.expected: dir is ok,version is ok.
518 */
519 CheckDirectoryV2ToV3(true, true);
520 CheckVersionV3(db);
521 (void)sqlite3_close_v2(db);
522
523 GetKvStoreProcess(option, false, false, secopt);
524 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
525 }
526
527 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest005, TestSize.Level2)
528 {
529 /**
530 * @tc.steps:step1. create old version V2 db.
531 */
532 std::string dbPath = g_testDir + g_databaseName;
533 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
534 CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
535 SecurityOption secopt = {SecurityLabel::S2, SecurityFlag::ECE};
536 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
537 EXPECT_EQ(isDatabaseExists, true);
538 /**
539 * @tc.steps:step2. Get the nb delegate while not sprite meta_db scene
540 * @tc.expected: step1. Get results OK and non-null delegate.
541 */
542 KvStoreNbDelegate::Option option = {true, false, false};
543 option.secOption = secopt;
544 GetKvStoreProcess(option, true, true, secopt);
545
546 sqlite3 *db = nullptr;
547 dbPath = g_testDir + g_newDatabaseName;
548 property = {dbPath, true, false};
549 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
550 ASSERT_NE(db, nullptr);
551 /**
552 * @tc.steps:step3. check result is ok.
553 * @tc.expected: dir is ok,version is ok.
554 */
555 CheckSyncDataV2ToV3(db);
556 CheckDirectoryV2ToV3(true, false);
557 CheckVersionV3(db);
558 (void)sqlite3_close_v2(db);
559 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
560 }
561
562 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeTest006, TestSize.Level2)
563 {
564 /**
565 * @tc.steps:step1. create old version V2 db.
566 */
567 std::string dbPath = g_testDir + g_databaseName;
568 OpenDbProperties property = {dbPath, true, false, ORIG_DATABASE_V2};
569 CreateDatabase(INSERT_DATA_V2, INSERT_LOCAL_DATA_V2, property);
570 SecurityOption secopt = {SecurityLabel::S3, SecurityFlag::ECE};
571 bool isDatabaseExists = OS::CheckPathExistence(dbPath);
572 EXPECT_EQ(isDatabaseExists, true);
573 /**
574 * @tc.steps:step2. Get the nb delegate while not sprite meta_db scene
575 * @tc.expected: step2. Get results OK and non-null delegate.
576 */
577 KvStoreNbDelegate::Option option = {true, false, false};
578 option.secOption = secopt;
579 GetKvStoreProcess(option, true, true, secopt);
580
581 sqlite3 *db = nullptr;
582 dbPath = g_testDir + g_newDatabaseName;
583 property = {dbPath, true, false};
584 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
585 ASSERT_NE(db, nullptr);
586 /**
587 * @tc.steps:step3. check result is ok.
588 * @tc.expected: dir is ok,version is ok.
589 */
590 CheckSyncDataV2ToV3(db);
591 CheckDirectoryV2ToV3(true, false);
592 CheckVersionV3(db);
593 (void)sqlite3_close_v2(db);
594 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
595 }
596
597 /**
598 * @tc.name: UpgradeErrTest001
599 * @tc.desc: Upgrade test when db file exists
600 * @tc.type: FUNC
601 * @tc.require:
602 * @tc.author: bty
603 */
604 HWTEST_F(DistributedDBStorageSingleVerUpgradeTest, UpgradeErrTest001, TestSize.Level2)
605 {
606 /**
607 * @tc.steps:step1. Upgrade after creating an upgrade Lock File
608 * @tc.expected: the upgrade lock File was deleted
609 */
610 KvStoreNbDelegate::Option option = {true, false, false};
611 std::string upgradeLockFileDir = g_testDir + "/" + DBCommon::TransferStringToHex(g_identifier)
612 + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::UPGRADE_POSTFIX;
613 EXPECT_EQ(OS::CreateFileByFileName(upgradeLockFileDir), E_OK);
614 GetKvStoreProcess(option, false, false, SecurityOption());
615 EXPECT_FALSE(OS::CheckPathExistence(upgradeLockFileDir));
616
617 /**
618 * @tc.steps:step2. Upgrade after opening a db File
619 * @tc.expected: the db File was deleted
620 */
621 sqlite3 *db = nullptr;
622 std::string dbPath = g_testDir + g_databaseName;
623 OpenDbProperties property = {dbPath, true, false};
624 EXPECT_EQ(SQLiteUtils::OpenDatabase(property, db), E_OK);
625 ASSERT_NE(db, nullptr);
626 EXPECT_TRUE(OS::CheckPathExistence(dbPath));
627 GetKvStoreProcess(option, false, false, SecurityOption());
628 EXPECT_FALSE(OS::CheckPathExistence(dbPath));
629 (void)sqlite3_close_v2(db);
630 EXPECT_EQ(g_mgr.DeleteKvStore("TestUpgradeNb"), OK);
631 }