1 /*
2 * Copyright (c) 2022 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 "native_sqlite.h"
17
18 namespace DistributedDB {
CreateDataBase(const std::string & dbUri)19 sqlite3 *NativeSqlite::CreateDataBase(const std::string &dbUri)
20 {
21 LOGD("Create database: %s", dbUri.c_str());
22 sqlite3 *db = nullptr;
23 if (int r = sqlite3_open_v2(dbUri.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) != SQLITE_OK) {
24 LOGE("Open database [%s] failed. %d", dbUri.c_str(), r);
25 if (db != nullptr) {
26 (void)sqlite3_close_v2(db);
27 db = nullptr;
28 }
29 }
30 return db;
31 }
32
ExecSql(sqlite3 * db,const std::string & sql)33 int NativeSqlite::ExecSql(sqlite3 *db, const std::string &sql)
34 {
35 if (db == nullptr || sql.empty()) {
36 return -E_INVALID_ARGS;
37 }
38 char *errMsg = nullptr;
39 int errCode = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &errMsg);
40 if (errCode != SQLITE_OK && errMsg != nullptr) {
41 LOGE("Execute sql failed. %d err: %s", errCode, errMsg);
42 }
43 sqlite3_free(errMsg);
44 return errCode;
45 }
46 }