Cppgres
Build Postgres extensions in C++
Loading...
Searching...
No Matches
function.hpp
Go to the documentation of this file.
1
4#pragma once
5
6#include "datum.hpp"
7#include "guard.hpp"
8#include "imports.h"
9#include "record.hpp"
10#include "set.hpp"
11#include "syscache.hpp"
12#include "types.hpp"
14#include "utils/utils.hpp"
15#include "value.hpp"
16
17#include <array>
18#include <complex>
19#include <iostream>
20#include <stack>
21#include <tuple>
22#include <typeinfo>
23
24namespace cppgres {
25
26template <typename T>
29
38template <typename Func>
40 requires { typename utils::function_traits::function_traits<Func>::argument_types; } &&
44 { std::apply(f, args) } -> convertible_into_nullable_datum_or_set_iterator_or_void;
45 };
46
48 function_call_info(::FunctionCallInfo info) : info_(info) {}
49
50 operator FunctionCallInfo() const { return info_; }
51
55 short nargs() const { return info_->nargs; }
56
61 auto args() const {
62 return std::views::iota(0, nargs()) | std::views::transform([this](int i) -> nullable_datum {
63 return nullable_datum(info_->args[i]);
64 });
65 }
66
70 auto arg_types() const {
71 return std::views::iota(0, nargs()) | std::views::transform([this](int i) -> type {
72 return {.oid = ffi_guard{::get_fn_expr_argtype}(info_->flinfo, i)};
73 });
74 }
75
80 auto arg_values() const {
81 return std::views::iota(0, nargs()) | std::views::transform([this](int i) -> value {
82 return value(nullable_datum(info_->args[i]),
83 {.oid = ffi_guard{::get_fn_expr_argtype}(info_->flinfo, i)});
84 });
85 }
86
90 oid called_function_oid() const { return info_->flinfo->fn_oid; }
91
95 type return_type() const { return {.oid = ffi_guard{::get_fn_expr_rettype}(info_->flinfo)}; }
96
97 oid collation() const { return info_->fncollation; }
98
99private:
100 ::FunctionCallInfo info_;
101};
102
104
105 static std::optional<bool> atomic() {
106 if (!calls.empty()) {
107 auto ctx = calls.top()->context;
108 if (ctx != nullptr && IsA(ctx, CallContext)) {
109 return reinterpret_cast<::CallContext *>(ctx)->atomic;
110 }
111 }
112
113 return std::nullopt;
114 }
115
116 static std::optional<function_call_info> call_info() {
117 if (!calls.empty()) {
118 return calls.top();
119 }
120
121 return std::nullopt;
122 }
123
124 template <datumable_function Func> friend struct postgres_function;
125
126private:
127 struct handle {
128 ~handle() { calls.pop(); }
129
130 friend struct current_postgres_function;
131
132 private:
133 handle() {}
134 };
135
136 static handle push(::FunctionCallInfo fcinfo) {
137 calls.push(fcinfo);
138 return handle{};
139 }
140 static void pop() { calls.pop(); }
141
142 static inline std::stack<::FunctionCallInfo> calls;
143};
144
155template <datumable_function Func> struct postgres_function {
156 Func func;
157
158 explicit postgres_function(Func f) : func(f) {}
159
160 // Use the function_traits to extract argument types.
162 using argument_types = typename traits::argument_types;
163 using return_type = utils::function_traits::invoke_result_from_tuple_t<Func, argument_types>;
164 static constexpr std::size_t arity = traits::arity;
165
169 auto operator()(FunctionCallInfo fc) -> ::Datum {
170
171 return exception_guard([&] {
172 // return type
173 auto rettype = type{.oid = ffi_guard{::get_fn_expr_rettype}(fc->flinfo)};
174 auto retset = fc->flinfo->fn_retset;
175
176 if constexpr (datumable_iterator<return_type>) {
177 // Check this before checking the type of `retset`
178 auto rsinfo = reinterpret_cast<::ReturnSetInfo *>(fc->resultinfo);
179 if (rsinfo == nullptr) {
180 report(ERROR, "caller is not expecting a set");
181 }
182 }
183
184 if (!OidIsValid(rettype.oid)) {
185 // TODO: not very efficient to look it up every time
186 syscache<Form_pg_proc, oid> cache(fc->flinfo->fn_oid);
187 rettype = type{.oid = (*cache).prorettype};
188 retset = (*cache).proretset;
189 }
190
191 if (retset) {
192 if constexpr (datumable_iterator<return_type>) {
193 using set_value_type = set_iterator_traits<return_type>::value_type;
194 if (!type_traits<set_value_type>().is(rettype)) {
195 report(ERROR, "unexpected set's return type, can't convert `%s` into `%.*s`",
196 rettype.name().data(), utils::type_name<set_value_type>().length(),
197 utils::type_name<set_value_type>().data());
198 }
199 } else {
200 report(ERROR,
201 "unexpected return type, set is expected, but `%.*s` does not conform to "
202 "`cppgres::datumable_iterator`",
203 utils::type_name<return_type>().length(), utils::type_name<return_type>().data());
204 }
205 } else if (!type_traits<return_type>().is(rettype)) {
206 report(ERROR, "unexpected return type, can't convert `%s` into `%.*s`",
207 rettype.name().data(), utils::type_name<return_type>().length(),
208 utils::type_name<return_type>().data());
209 }
210
211 // arguments
212 short accounted_for_args = 0;
213 auto t = [&]<std::size_t... Is>(std::index_sequence<Is...>) {
214 return argument_types{([&]() -> utils::tuple_element_t<Is, argument_types> {
215 using ptyp = utils::tuple_element_t<Is, argument_types>;
216 auto typ = type{.oid = ffi_guard{::get_fn_expr_argtype}(fc->flinfo, Is)};
217 if (!OidIsValid(typ.oid)) {
218 // TODO: not very efficient to look it up every time
219 syscache<Form_pg_proc, oid> cache(fc->flinfo->fn_oid);
220 if ((*cache).proargtypes.dim1 > Is) {
221 typ = type{.oid = (*cache).proargtypes.values[Is]};
222 }
223 }
224 if (!type_traits<ptyp>().is(typ)) {
225 report(ERROR, "unexpected type in position %d, can't convert `%s` into `%.*s`", Is,
226 typ.name().data(), utils::type_name<ptyp>().length(),
227 utils::type_name<ptyp>().data());
228 }
229 accounted_for_args++;
230 return from_nullable_datum<ptyp>(nullable_datum(fc->args[Is]), typ.oid);
231 }())...};
232 }(std::make_index_sequence<utils::tuple_size_v<argument_types>>{});
233
234 if (arity != accounted_for_args) {
235 report(ERROR, "expected %d arguments, got %d instead", arity, accounted_for_args);
236 }
237
238 auto call_handle = current_postgres_function::push(fc);
239
240 if constexpr (datumable_iterator<return_type>) {
241 auto rsinfo = reinterpret_cast<::ReturnSetInfo *>(fc->resultinfo);
242 // TODO: For now, let's assume materialized model
243 using set_value_type = set_iterator_traits<return_type>::value_type;
244 if constexpr (std::same_as<set_value_type, record>) {
245
246 auto natts = rsinfo->expectedDesc == nullptr ? -1 : rsinfo->expectedDesc->natts;
247
248 rsinfo->returnMode = SFRM_Materialize;
249
250 memory_context_scope scope(memory_context(rsinfo->econtext->ecxt_per_query_memory));
251
252 ::Tuplestorestate *tupstore = ffi_guard{::tuplestore_begin_heap}(
253 (rsinfo->allowedModes & SFRM_Materialize_Random) == SFRM_Materialize_Random, false,
254 work_mem);
255 rsinfo->setResult = tupstore;
256
257 auto res = std::apply(func, t);
258
259 bool checked = false;
260 for (auto r : res) {
261 auto nargs = r.attributes();
262 if (!checked) {
263 if (rsinfo->expectedDesc != nullptr && nargs != natts) {
264 throw std::runtime_error(
265 cppgres::fmt::format("expected record with {} value{}, got {} instead", nargs,
266 nargs == 1 ? "" : "s", natts));
267 }
268 if (rsinfo->expectedDesc != nullptr &&
269 !r.get_tuple_descriptor().equal_types(
270 cppgres::tuple_descriptor(rsinfo->expectedDesc))) {
271 throw std::runtime_error("expected and returned records do not match");
272 }
273 checked = true;
274 }
275
276 ffi_guard{::tuplestore_puttuple}(tupstore, r);
277 }
278 fc->isnull = true;
279 return ::Datum(0);
280 } else {
281 constexpr auto nargs = utils::tuple_size_v<set_value_type>;
282
283 auto natts = rsinfo->expectedDesc->natts;
284
285 if (nargs != natts) {
286 throw std::runtime_error(cppgres::fmt::format("expected set with {} value{}, got {} instead",
287 nargs, nargs == 1 ? "" : "s", natts));
288 }
289
290 [&]<std::size_t... Is>(std::index_sequence<Is...>) {
291 (([&] {
292 auto oid = ffi_guard{::SPI_gettypeid}(rsinfo->expectedDesc, Is + 1);
293 auto t = type{.oid = oid};
294 using typ = utils::tuple_element_t<Is, set_value_type>;
295 if (!type_traits<typ>().is(t)) {
296 throw std::invalid_argument(
297 cppgres::fmt::format("invalid type in record's position {} ({}), got OID {}", Is,
298 utils::type_name<typ>(), oid));
299 }
300 }()),
301 ...);
302 }(std::make_index_sequence<nargs>{});
303
304 rsinfo->returnMode = SFRM_Materialize;
305
306 memory_context_scope scope(memory_context(rsinfo->econtext->ecxt_per_query_memory));
307
308 ::Tuplestorestate *tupstore = ffi_guard{::tuplestore_begin_heap}(
309 (rsinfo->allowedModes & SFRM_Materialize_Random) == SFRM_Materialize_Random, false,
310 work_mem);
311 rsinfo->setResult = tupstore;
312
313 auto result = std::apply(func, t);
314
315 for (auto it : result) {
316 CHECK_FOR_INTERRUPTS();
317 std::array<::Datum, nargs> values = std::apply(
318 [](auto &&...elems) -> std::array<::Datum, sizeof...(elems)> {
319 return {into_nullable_datum(elems)...};
320 },
321 utils::tie(it));
322 std::array<bool, nargs> isnull = std::apply(
323 [](auto &&...elems) -> std::array<bool, sizeof...(elems)> {
324 return {into_nullable_datum(elems).is_null()...};
325 },
326 utils::tie(it));
327 ffi_guard{::tuplestore_putvalues}(tupstore, rsinfo->expectedDesc, values.data(),
328 isnull.data());
329 }
330
331 fc->isnull = true;
332 return ::Datum(0);
333 }
334 } else {
335 if constexpr (std::same_as<return_type, void>) {
336 std::apply(func, t);
337 return ::Datum(0);
338 } else {
339 auto result = std::apply(func, t);
340 nullable_datum nd = into_nullable_datum(result);
341 if (nd.is_null()) {
342 fc->isnull = true;
343 return ::Datum(0);
344 }
345 return nd.operator const ::Datum &();
346 }
347 }
348 })();
349 __builtin_unreachable();
350 }
351};
352
353template <has_type_traits ret_type, has_type_traits... arg_types> struct function {
354
355 function() = delete;
356
357 function(const char *schema, const char *name)
358 : function([schema, name]() -> oid {
359 return alloc_set_memory_context()([&schema, &name]() {
360 ::List *fname = list_make2(::makeString(const_cast<char *>(schema)),
361 ::makeString(const_cast<char *>(name)));
362 std::array<::Oid, sizeof...(arg_types)> argtypes = {
363 type_traits<arg_types>().type_for().oid...};
364 return ffi_guard{::LookupFuncName}(fname, static_cast<int>(sizeof...(arg_types)),
365 argtypes.data(), false);
366 });
367 }()) {}
368 function(std::string &schema, std::string &name) : function(schema.c_str(), name.c_str()) {}
369 explicit function(const char *name)
370 : function([name]() -> oid {
371 return alloc_set_memory_context()([&name]() {
372 ::List *fname = list_make1(::makeString(const_cast<char *>(name)));
373 std::array<::Oid, sizeof...(arg_types)> argtypes = {
374 type_traits<arg_types>().type_for().oid...};
375 return ffi_guard{::LookupFuncName}(fname, static_cast<int>(sizeof...(arg_types)),
376 argtypes.data(), false);
377 });
378 }()) {}
379 function(std::string &name) : function(name.c_str()) {}
380 function(oid oid) : oid_(oid) {
381 syscache<Form_pg_proc, decltype(oid)> p(oid_);
382 // Check arguments
383 auto &argtypes = (*p).proargtypes;
384 std::array<type, sizeof...(arg_types)> types = {type_traits<arg_types>().type_for()...};
385 for (int i = 0; i < argtypes.dim1; i++) {
386 cppgres::oid arg(argtypes.values[i]);
387 if (types[i] != type{UNKNOWNOID} /* FIXME: figure out how to avoid this special case */ &&
388 arg != types[i].oid) {
389 throw std::runtime_error(cppgres::fmt::format("expected type {} for argument {}, got {}",
390 types[i].name(), i, type{.oid = arg}.name()));
391 }
392 }
393 // Check return type
394 rettype_ = (*p).prorettype;
395 if (type_traits<ret_type>().type_for().oid !=
396 UNKNOWNOID /* FIXME: figure out how to avoid this special case */
397 && rettype_ != type_traits<ret_type>().type_for().oid) {
398 throw std::runtime_error(cppgres::fmt::format("expected return type {}, got {}",
399 type_traits<ret_type>().type_for().name(),
400 type{.oid = rettype_}.name()));
401 }
402 strict_ = (*p).proisstrict;
403 }
404
405 using self = function<ret_type, arg_types...>;
406 template <typename... Args> static constexpr bool convertible_args() {
407 if constexpr (sizeof...(Args) != sizeof...(arg_types)) {
408 return false;
409 } else {
410 return []<std::size_t... I>(std::index_sequence<I...>) {
411 return (std::convertible_to<std::decay_t<Args>,
412 std::tuple_element_t<I, std::tuple<arg_types...>>> &&
413 ...);
414 }(std::make_index_sequence<sizeof...(Args)>{});
415 }
416 }
417 ret_type operator()(auto... args) requires(self::convertible_args<decltype(args)...>())
418 {
419 bool any_nulls = false;
420 auto optval = []<std::size_t I>(auto arg) -> ::Datum {
421 using nth_type = std::tuple_element_t<I, std::tuple<arg_types...>>;
422 if constexpr (std::same_as<std::nullopt_t, decltype(arg)>) {
423 return datum(0);
424 } else if constexpr (!utils::is_optional<decltype(arg)>) {
426 } else {
427 return arg.has_value() ? datum_conversion<nth_type>().into_datum(arg.value()) : datum(0);
428 }
429 return datum(0);
430 };
431 auto isnull = [&any_nulls](auto arg) {
432 if constexpr (std::same_as<std::nullopt_t, decltype(arg)>) {
433 any_nulls = true;
434 return true;
435 } else if constexpr (!utils::is_optional<decltype(arg)>) {
436 return false;
437 } else {
438 any_nulls = !arg.has_value();
439 return !arg.has_value();
440 }
441 return false;
442 };
443 return [&]<std::size_t... I>(std::index_sequence<I...>) -> ret_type {
444 LOCAL_FCINFO(fcinfo, sizeof...(args));
445 ::FmgrInfo flinfo;
446
447 ffi_guard{::fmgr_info}(oid_, &flinfo);
448
449 InitFunctionCallInfoData(*fcinfo, &flinfo, sizeof...(args), InvalidOid, nullptr, nullptr);
450
451 ((fcinfo->args[I].value = optval.template operator()<I>(args)), ...);
452 ((fcinfo->args[I].isnull = isnull(args)), ...);
453
454 if (any_nulls && strict_) {
455 if constexpr (utils::is_optional<ret_type>) {
456 return std::nullopt;
457 } else {
458 throw null_datum_exception();
459 }
460 }
461
462 nullable_datum result(ffi_guard{[&fcinfo]() { return FunctionCallInvoke(fcinfo); }}());
463 if (fcinfo->isnull) {
464 result = nullable_datum();
465 }
466
467 return datum_conversion<ret_type>().from_nullable_datum(result, rettype_);
468 }(std::make_index_sequence<sizeof...(args)>{});
469 }
470
471 const oid &function_oid() const { return oid_; }
472
473private:
474 oid oid_;
475 oid rettype_;
476 bool strict_;
477};
478
479template <has_type_traits ret, has_type_traits... Args>
480struct datum_conversion<function<ret, Args...>> : default_datum_conversion<function<ret, Args...>> {
481 static function<ret, Args...> from_datum(const datum &d, oid, std::optional<memory_context> ctx) {
482 return {oid(d)};
483 }
484
485 static datum into_datum(const function<ret, Args...> &t) {
486 return datum_conversion<oid>::into_datum(t.function_oid());
487 }
488};
489
490template <has_type_traits ret, has_type_traits... Args> struct type_traits<function<ret, Args...>> {
491 static bool is(const type &t) {
492 return t.oid == REGPROCEDUREOID || t.oid == OIDOID || t.oid == REGPROCOID;
493 }
494 static constexpr type type_for() { return type{.oid = REGPROCEDUREOID}; }
495};
496
497template <has_type_traits T> function<const char *, T> output_function() {
498 ::Oid foutoid;
499 bool typisvarlena;
500 ffi_guard{::getTypeOutputInfo}(type_traits<T>().type_for().oid, &foutoid, &typisvarlena);
501 return function<const char *, T>(foutoid);
502}
503
504template <has_type_traits T> function<const char *, T> output_function(T &&v) {
505 ::Oid foutoid;
506 bool typisvarlena;
507 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
508 return function<const char *, T>(foutoid);
509}
510
511template <has_type_traits T> function<const char *, T> output_function(T &v) {
512 ::Oid foutoid;
513 bool typisvarlena;
514 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
515 return function<const char *, T>(foutoid);
516}
517
518static function<const char *, cppgres::value> output_function(const type &t) {
519 ::Oid foutoid;
520 bool typisvarlena;
521 ffi_guard{::getTypeOutputInfo}(t.oid, &foutoid, &typisvarlena);
522 return function<const char *, cppgres::value>(foutoid);
523}
524
525} // namespace cppgres
Definition: datum.hpp:56
Function that operates on values of Postgres types.
Definition: function.hpp:39
Definition: set.hpp:15
Definition: type.hpp:49
Definition: utils.hpp:39
#define postgres_function(name, function)
Export a C++ function as a Postgres function.
Definition: cppgres.hpp:100
Definition: datum.hpp:217
Definition: memory.hpp:118
Definition: collation.hpp:8
Definition: function.hpp:103
A trait to convert from and into a cppgres::datum.
Definition: datum.hpp:114
static T from_nullable_datum(const nullable_datum &d, const oid oid, std::optional< memory_context > context=std::nullopt)=delete
Convert from a nullable datum.
static datum into_datum(const T &d)=delete
Convert datum into a type.
Definition: datum.hpp:39
Definition: datum.hpp:146
Wraps a C++ function to catch exceptions and report them as Postgres errors.
Definition: guard.hpp:64
Definition: guard.hpp:19
Definition: function.hpp:47
auto arg_types() const
argument types
Definition: function.hpp:70
auto args() const
passed arguments
Definition: function.hpp:61
auto arg_values() const
typed passed argument
Definition: function.hpp:80
type return_type() const
return type
Definition: function.hpp:95
short nargs() const
number of arguments actually passed
Definition: function.hpp:55
oid called_function_oid() const
called function OID
Definition: function.hpp:90
Definition: function.hpp:353
Definition: memory.hpp:217
Definition: memory.hpp:85
Definition: name.hpp:7
Definition: datum.hpp:60
Definition: datum.hpp:17
Postgres function implemented in C++.
Definition: function.hpp:155
auto operator()(FunctionCallInfo fc) -> ::Datum
Definition: function.hpp:169
Definition: syscache.hpp:27
Tuple descriptor operator.
Definition: record.hpp:18
Definition: type.hpp:41
Postgres type.
Definition: type.hpp:20
Definition: function_traits.hpp:37
Definition: value.hpp:8