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
ExecSql(sqlite3 * db,const std::string & sql,const std::function<int (sqlite3_stmt *)> & bindCallback,const std::function<int (sqlite3_stmt *)> & resultCallback)47 int NativeSqlite::ExecSql(sqlite3 *db, const std::string &sql, const std::function<int (sqlite3_stmt *)> &bindCallback,
48 const std::function<int (sqlite3_stmt *)> &resultCallback)
49 {
50 if (db == nullptr || sql.empty()) {
51 return -E_INVALID_ARGS;
52 }
53
54 bool bindFinish = true;
55 sqlite3_stmt *stmt = nullptr;
56 int ret = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr);
57 if (ret != SQLITE_OK) {
58 goto END;
59 }
60
61 do {
62 if (bindCallback) {
63 ret = bindCallback(stmt);
64 if (ret != E_OK && ret != -E_UNFINISHED) {
65 goto END;
66 }
67 bindFinish = (ret != -E_UNFINISHED);
68 }
69
70 while (true) {
71 ret = sqlite3_step(stmt);
72 if (ret == SQLITE_DONE) {
73 ret = E_OK; // step finished
74 break;
75 } else if (ret != SQLITE_ROW) {
76 goto END; // step return error
77 }
78
79 if (resultCallback != nullptr && (ret = resultCallback(stmt)) != E_OK) {
80 goto END;
81 }
82 // continue step stmt while callback return E_OK
83 }
84 (void)sqlite3_reset(stmt);
85 } while (!bindFinish);
86
87 END:
88 (void)sqlite3_finalize(stmt);
89 return ret;
90 }
91 }