• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
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 
17 #ifndef SRC_TRACE_PROCESSOR_SQLITE_REGISTER_FUNCTION_H_
18 #define SRC_TRACE_PROCESSOR_SQLITE_REGISTER_FUNCTION_H_
19 
20 #include <sqlite3.h>
21 #include <memory>
22 
23 #include "src/trace_processor/sqlite/sqlite_utils.h"
24 
25 namespace perfetto {
26 namespace trace_processor {
27 
28 // Prototype for a C++ function which can be registered with SQLite.
29 //
30 // Usage
31 //
32 // Define a subclass of this struct as follows:
33 // struct YourFunction : public SqlFunction {
34 //   // Optional if you want a custom context object (i.e. an object
35 //   // passed in at registration time which will be passed to Run on
36 //   // every invocation)
37 //   struct YourContext { /* define context fields here */ };
38 //
39 //   static base::Status Run(/* see parameters below */) {
40 //     /* function body here */
41 //   }
42 //
43 //   static base::Status Cleanup(/* see parameters below */) {
44 //     /* function body here */
45 //   }
46 // }
47 //
48 // Then, register this function with SQLite using RegisterFunction (see below);
49 // you'll likely want to do this in TraceProcessorImpl:
50 // RegisterFunction<YourFunction>(/* see arguments below */)
51 struct SqlFunction {
52   // The type of the context object which will be passed to the function.
53   // Can be redefined in any sub-classes to override the context.
54   using Context = void;
55 
56   // Struct which holds destructors for strings/bytes returned from the
57   // function. Passed as an argument to |Run| to allow implementations to
58   // override the destructors.
59   struct Destructors {
60     sqlite3_destructor_type string_destructor = sqlite_utils::kSqliteTransient;
61     sqlite3_destructor_type bytes_destructor = sqlite_utils::kSqliteTransient;
62   };
63 
64   // The function which will be exectued with the arguments from SQL.
65   //
66   // Implementations MUST define this function themselves; this function is
67   // declared but *not* defined so linker errors will be thrown if not defined.
68   //
69   // |ctx|:         the context object passed at registration time.
70   // |argc|:        number of arguments.
71   // |argv|:        arguments to the function.
72   // |out|:         the return value of the function.
73   // |destructors|: destructors for string/bytes return values.
74   static base::Status Run(Context* ctx,
75                           size_t argc,
76                           sqlite3_value** argv,
77                           SqlValue& out,
78                           Destructors& destructors);
79 
80   // Executed after the result from |Run| is reported to SQLite.
81   // Allows any pending state to be cleaned up post-copy of results by SQLite.
82   //
83   // Implementations do not need to define this function; a default no-op
84   // implementation will be used in this case.
85   static base::Status Cleanup(Context*);
86 };
87 
88 // Registers a C++ function to be runnable from SQL.
89 // The format of the function is given by the |SqlFunction|; see the
90 // documentaion above.
91 //
92 // |db|:          sqlite3 database object
93 // |name|:        name of the function in SQL
94 // |argc|:        number of arguments for this function, -1 if variable
95 // |ctx|:         context object for the function (see SqlFunction::Run above);
96 //                this object *must* outlive the function so should likely be
97 //                either static or scoped to the lifetime of TraceProcessor.
98 // |determistic|: whether this function has deterministic output given the
99 //                same set of arguments.
100 template <typename Function>
101 base::Status RegisterSqlFunction(sqlite3* db,
102                                  const char* name,
103                                  int argc,
104                                  typename Function::Context* ctx,
105                                  bool deterministic = true);
106 
107 // Same as above except allows a unique_ptr to be passed for the context; this
108 // allows for SQLite to manage the lifetime of this pointer instead of the
109 // essentially static requirement of the context pointer above.
110 template <typename Function>
111 base::Status RegisterSqlFunction(
112     sqlite3* db,
113     const char* name,
114     int argc,
115     std::unique_ptr<typename Function::Context> ctx,
116     bool deterministic = true);
117 
118 }  // namespace trace_processor
119 }  // namespace perfetto
120 
121 // The rest of this file is just implementation details which we need
122 // in the header file because it is templated code. We separate it out
123 // like this to keep the API people actually care about easy to read.
124 
125 namespace perfetto {
126 namespace trace_processor {
127 
128 namespace sqlite_internal {
129 template <typename Function>
WrapSqlFunction(sqlite3_context * ctx,int argc,sqlite3_value ** argv)130 void WrapSqlFunction(sqlite3_context* ctx, int argc, sqlite3_value** argv) {
131   using Context = typename Function::Context;
132   auto* ud = static_cast<Context*>(sqlite3_user_data(ctx));
133 
134   SqlValue value{};
135   SqlFunction::Destructors destructors{};
136   base::Status status =
137       Function::Run(ud, static_cast<size_t>(argc), argv, value, destructors);
138 
139   if (!status.ok()) {
140     sqlite3_result_error(ctx, status.c_message(), -1);
141     return;
142   }
143   sqlite_utils::ReportSqlValue(ctx, value, destructors.string_destructor,
144                                destructors.bytes_destructor);
145 
146   status = Function::Cleanup(ud);
147   if (!status.ok()) {
148     sqlite3_result_error(ctx, status.c_message(), -1);
149     return;
150   }
151 }
152 }  // namespace sqlite_internal
153 
154 template <typename Function>
RegisterSqlFunction(sqlite3 * db,const char * name,int argc,typename Function::Context * ctx,bool deterministic)155 base::Status RegisterSqlFunction(sqlite3* db,
156                                  const char* name,
157                                  int argc,
158                                  typename Function::Context* ctx,
159                                  bool deterministic) {
160   int flags = SQLITE_UTF8 | (deterministic ? SQLITE_DETERMINISTIC : 0);
161   int ret = sqlite3_create_function_v2(
162       db, name, static_cast<int>(argc), flags, ctx,
163       sqlite_internal::WrapSqlFunction<Function>, nullptr, nullptr, nullptr);
164   if (ret != SQLITE_OK) {
165     return base::ErrStatus("Unable to register function with name %s", name);
166   }
167   return base::OkStatus();
168 }
169 
170 template <typename Function>
RegisterSqlFunction(sqlite3 * db,const char * name,int argc,std::unique_ptr<typename Function::Context> user_data,bool deterministic)171 base::Status RegisterSqlFunction(
172     sqlite3* db,
173     const char* name,
174     int argc,
175     std::unique_ptr<typename Function::Context> user_data,
176     bool deterministic) {
177   int flags = SQLITE_UTF8 | (deterministic ? SQLITE_DETERMINISTIC : 0);
178   int ret = sqlite3_create_function_v2(
179       db, name, static_cast<int>(argc), flags, user_data.release(),
180       sqlite_internal::WrapSqlFunction<Function>, nullptr, nullptr,
181       [](void* ptr) { delete static_cast<typename Function::Context*>(ptr); });
182   if (ret != SQLITE_OK) {
183     return base::ErrStatus("Unable to register function with name %s", name);
184   }
185   return base::OkStatus();
186 }
187 
188 }  // namespace trace_processor
189 }  // namespace perfetto
190 
191 #endif  // SRC_TRACE_PROCESSOR_SQLITE_REGISTER_FUNCTION_H_
192