1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * \author guonix
17 * \date Nov 2020
18 * \brief
19 */
20
21#pragma once
22
23#include <sqlite3.h>
24#include <functional>
25#include <memory>
26#include <string>
27
28namespace proxima {
29namespace be {
30namespace meta {
31namespace sqlite {
32
33//! Predefine class
34class Statement;
35//! Alias for StatementPtr
36using StatementPtr = std::shared_ptr<Statement>;
37
38
39/*!
40 * Statement object
41 */
42class Statement {
43 public:
44 //! Constructors
45 Statement();
46 Statement(std::string database, const char *sql);
47 Statement(std::string database, std::string sql);
48 Statement(Statement &&stmt) noexcept;
49 Statement(const Statement &stmt) = delete;
50
51 //! Destructor
52 ~Statement();
53
54 public:
55 //! Initialize Statement, 0 for success, otherwise failed
56 int initialize();
57
58 //! Cleanup statement, 0 for success, otherwise failed
59 int cleanup();
60
61 //! Execute statement, 0 for success, otherwise failed
62 //! @param binder: bind the params to statements
63 //! @param fetcher: fetch the records returned from sqlite_step
64 //! @param retry: the times retry exec sql
65 int exec(const std::function<int(sqlite3_stmt *)> &binder = nullptr,
66 const std::function<int(sqlite3_stmt *)> &fetcher = nullptr,
67 uint32_t retry = 1);
68
69 //! Prepare sql
70 int prepare_sql(const std::string &sql);
71
72 private:
73 //! Reset the values banded to statement, 0 for success, otherwise failed
74 int reset();
75
76 //! cleanup
77 int do_cleanup();
78
79 //! compile sql
80 int compile_sql();
81
82 private:
83 //! the path of databases
84 std::string database_{};
85
86 //! database connection
87 sqlite3 *connection_{nullptr};
88
89 //! sql
90 std::string sql_{};
91
92 //! statement of sqlite
93 sqlite3_stmt *statement_{nullptr};
94};
95
96
97} // namespace sqlite
98} // namespace meta
99} // namespace be
100} // namespace proxima
101