1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 
16 #include "kv_store_manager.h"
17 
18 #include "doc_errno.h"
19 #include "rd_log_print.h"
20 #include "rd_sqlite_utils.h"
21 #include "sqlite_store_executor_impl.h"
22 
23 namespace DocumentDB {
GetKvStore(const std::string & path,const DBConfig & config,bool isFirstOpen,KvStoreExecutor * & executor)24 int KvStoreManager::GetKvStore(const std::string &path, const DBConfig &config, bool isFirstOpen,
25     KvStoreExecutor *&executor)
26 {
27     if (executor != nullptr) {
28         return -E_INVALID_ARGS;
29     }
30 
31     sqlite3 *db = nullptr;
32     int errCode = SqliteStoreExecutorImpl::CreateDatabase(path, config, db);
33     if (errCode != E_OK) {
34         GLOGE("Get kv store failed. %d", errCode);
35         return errCode;
36     }
37 
38     auto *sqliteExecutor = new (std::nothrow) SqliteStoreExecutorImpl(db);
39     if (sqliteExecutor == nullptr) {
40         sqlite3_close_v2(db);
41         return -E_OUT_OF_MEMORY;
42     }
43 
44     std::string oriConfigStr;
45     errCode = sqliteExecutor->GetDBConfig(oriConfigStr);
46     if (errCode == -E_NOT_FOUND) {
47         errCode = sqliteExecutor->SetDBConfig(config.ToString());
48         if (errCode != E_OK) {
49             GLOGE("Set db config failed. %d", errCode);
50             goto END;
51         }
52     } else if (errCode != E_OK) {
53         goto END;
54     } else {
55         DBConfig oriDbConfig = DBConfig::ReadConfig(oriConfigStr, errCode);
56         if (errCode != E_OK) {
57             GLOGE("Read db config failed. %d", errCode);
58             goto END;
59         }
60         if ((isFirstOpen ? (!config.CheckPersistenceEqual(oriDbConfig)) : (config != oriDbConfig))) {
61             errCode = -E_INVALID_CONFIG_VALUE;
62             GLOGE("Get kv store failed, db config changed. %d", errCode);
63             goto END;
64         }
65     }
66     executor = sqliteExecutor;
67     return E_OK;
68 
69 END:
70     delete sqliteExecutor;
71     return errCode;
72 }
73 } // namespace DocumentDB