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 #ifndef RD_SQLITE_UTILS_H
17 #define RD_SQLITE_UTILS_H
18 
19 #include <functional>
20 #include <string>
21 #include <vector>
22 
23 #include "sqlite3sym.h"
24 
25 namespace DocumentDB {
26 enum class TransactType {
27     DEFERRED,
28     IMMEDIATE,
29 };
30 
31 class RDSQLiteUtils {
32 public:
33     static int CreateDataBase(const std::string &path, int flag, sqlite3 *&db);
34 
35     static int GetStatement(sqlite3 *db, const std::string &sql, sqlite3_stmt *&statement);
36     static int StepWithRetry(sqlite3_stmt *statement);
37     static int ResetStatement(sqlite3_stmt *&statement, bool finalize);
38 
39     static int BindBlobToStatement(sqlite3_stmt *statement, int index, const std::vector<uint8_t> &value);
40     static int GetColumnBlobValue(sqlite3_stmt *statement, int index, std::vector<uint8_t> &value);
41 
42     static int BindTextToStatement(sqlite3_stmt *statement, int index, const std::string &value);
43 
44     static int BeginTransaction(sqlite3 *db, TransactType type = TransactType::DEFERRED);
45     static int CommitTransaction(sqlite3 *db);
46     static int RollbackTransaction(sqlite3 *db);
47 
48     static int ExecSql(sqlite3 *db, const std::string &sql);
49     static int ExecSql(sqlite3 *db, const std::string &sql, const std::function<int(sqlite3_stmt *)> &bindCallback,
50         const std::function<int(sqlite3_stmt *, bool &)> &resultCallback);
51 
52 private:
53     static void SqliteLogCallback(void *data, int err, const char *msg);
54 };
55 } // namespace DocumentDB
56 #endif // SQLITE_UTILS_H