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... Arg> struct function {
354
355 template <std::size_t... I>
356 static auto make_arg_tuple(std::index_sequence<I...>)
357 -> std::tuple<std::tuple_element_t<I, std::tuple<Arg...>>...>;
358
359 using arg_types = decltype(make_arg_tuple(std::make_index_sequence<sizeof...(Arg) - 1>{}));
360 using ret_type = std::tuple_element_t<sizeof...(Arg) - 1, std::tuple<Arg...>>;
361
362 function() = delete;
363
364 function(const char *schema, const char *name)
365 : function([schema, name]() -> oid {
366 return alloc_set_memory_context()([&schema, &name]() {
367 ::List *fname = list_make2(::makeString(const_cast<char *>(schema)),
368 ::makeString(const_cast<char *>(name)));
369 std::array<::Oid, sizeof...(Arg)> argtypes = {type_traits<Arg>().type_for().oid...};
370 return ffi_guard{::LookupFuncName}(fname, static_cast<int>(sizeof...(Arg) - 1),
371 argtypes.data(), false);
372 });
373 }()) {}
374 function(std::string &schema, std::string &name) : function(schema.c_str(), name.c_str()) {}
375 explicit function(const char *name)
376 : function([name]() -> oid {
377 return alloc_set_memory_context()([&name]() {
378 ::List *fname = list_make1(::makeString(const_cast<char *>(name)));
379 std::array<::Oid, sizeof...(Arg)> argtypes = {type_traits<Arg>().type_for().oid...};
380 return ffi_guard{::LookupFuncName}(fname, static_cast<int>(sizeof...(Arg) - 1),
381 argtypes.data(), false);
382 });
383 }()) {}
384 function(std::string &name) : function(name.c_str()) {}
385 function(oid oid) : oid_(oid) {
386 syscache<Form_pg_proc, decltype(oid)> p(oid_);
387 // Check arguments
388 auto &argtypes = (*p).proargtypes;
389 std::array<type, sizeof...(Arg)> types = {type_traits<Arg>().type_for()...};
390 for (int i = 0; i < argtypes.dim1; i++) {
391 cppgres::oid arg(argtypes.values[i]);
392 if (types[i] != type{UNKNOWNOID} /* FIXME: figure out how to avoid this special case */ &&
393 arg != types[i].oid) {
394 throw std::runtime_error(cppgres::fmt::format("expected type {} for argument {}, got {}",
395 types[i].name(), i, type{.oid = arg}.name()));
396 }
397 }
398 // Check return type
399 rettype_ = (*p).prorettype;
400 if (type_traits<ret_type>().type_for().oid !=
401 UNKNOWNOID /* FIXME: figure out how to avoid this special case */
402 && rettype_ != type_traits<ret_type>().type_for().oid) {
403 throw std::runtime_error(cppgres::fmt::format("expected return type {}, got {}",
404 type_traits<ret_type>().type_for().name(),
405 type{.oid = rettype_}.name()));
406 }
407 strict_ = (*p).proisstrict;
408 }
409
410 using self = function<Arg...>;
411 template <typename... Args> static constexpr bool convertible_args() {
412 if constexpr (sizeof...(Args) != sizeof...(Arg) - 1) {
413 return false;
414 } else {
415 return []<std::size_t... I>(std::index_sequence<I...>) {
416 return (
417 std::convertible_to<std::decay_t<Args>, std::tuple_element_t<I, std::tuple<Arg...>>> &&
418 ...);
419 }(std::make_index_sequence<sizeof...(Args)>{});
420 }
421 }
422 ret_type operator()(auto... args) requires(self::convertible_args<decltype(args)...>())
423 {
424 bool any_nulls = false;
425 auto optval = []<std::size_t I>(auto arg) -> ::Datum {
426 using nth_type = std::tuple_element_t<I, std::tuple<Arg...>>;
427 if constexpr (std::same_as<std::nullopt_t, decltype(arg)>) {
428 return datum(0);
429 } else if constexpr (!utils::is_optional<decltype(arg)>) {
431 } else {
432 return arg.has_value() ? datum_conversion<nth_type>().into_datum(arg.value()) : datum(0);
433 }
434 return datum(0);
435 };
436 auto isnull = [&any_nulls](auto arg) {
437 if constexpr (std::same_as<std::nullopt_t, decltype(arg)>) {
438 any_nulls = true;
439 return true;
440 } else if constexpr (!utils::is_optional<decltype(arg)>) {
441 return false;
442 } else {
443 any_nulls = !arg.has_value();
444 return !arg.has_value();
445 }
446 return false;
447 };
448 return [&]<std::size_t... I>(std::index_sequence<I...>) -> ret_type {
449 LOCAL_FCINFO(fcinfo, sizeof...(args));
450 ::FmgrInfo flinfo;
451
452 ffi_guard{::fmgr_info}(oid_, &flinfo);
453
454 InitFunctionCallInfoData(*fcinfo, &flinfo, sizeof...(args), InvalidOid, NULL, NULL);
455
456 ((fcinfo->args[I].value = optval.template operator()<I>(args)), ...);
457 ((fcinfo->args[I].isnull = isnull(args)), ...);
458
459 if (any_nulls && strict_) {
460 if constexpr (utils::is_optional<ret_type>) {
461 return std::nullopt;
462 } else {
463 throw null_datum_exception();
464 }
465 }
466
467 nullable_datum result(ffi_guard{[&fcinfo]() { return FunctionCallInvoke(fcinfo); }}());
468 if (fcinfo->isnull) {
469 result = nullable_datum();
470 }
471
472 return datum_conversion<ret_type>().from_nullable_datum(result, rettype_);
473 }(std::make_index_sequence<sizeof...(Arg) - 1>{});
474 }
475
476 const oid &function_oid() const { return oid_; }
477
478private:
479 oid oid_;
480 oid rettype_;
481 bool strict_;
482};
483
484template <has_type_traits... Args>
485struct datum_conversion<function<Args...>> : default_datum_conversion<function<Args...>> {
486 static function<Args...> from_datum(const datum &d, oid, std::optional<memory_context> ctx) {
487 return {oid(d)};
488 }
489
490 static datum into_datum(const function<Args...> &t) {
491 return datum_conversion<oid>::into_datum(t.function_oid());
492 }
493};
494
495template <has_type_traits... Args> struct type_traits<function<Args...>> {
496 static bool is(const type &t) {
497 return t.oid == REGPROCEDUREOID || t.oid == OIDOID || t.oid == REGPROCOID;
498 }
499 static constexpr type type_for() { return type{.oid = REGPROCEDUREOID}; }
500};
501
502template <has_type_traits T> function<T, const char *> output_function() {
503 ::Oid foutoid;
504 bool typisvarlena;
505 ffi_guard{::getTypeOutputInfo}(type_traits<T>().type_for().oid, &foutoid, &typisvarlena);
506 return function<T, const char *>(foutoid);
507}
508
509template <has_type_traits T> function<T, const char *> output_function(T &&v) {
510 ::Oid foutoid;
511 bool typisvarlena;
512 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
513 return function<T, const char *>(foutoid);
514}
515
516template <has_type_traits T> function<T, const char *> output_function(T &v) {
517 ::Oid foutoid;
518 bool typisvarlena;
519 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
520 return function<T, const char *>(foutoid);
521}
522
523static function<cppgres::value, const char *> output_function(const type &t) {
524 ::Oid foutoid;
525 bool typisvarlena;
526 ffi_guard{::getTypeOutputInfo}(t.oid, &foutoid, &typisvarlena);
527 return function<cppgres::value, const char *>(foutoid);
528}
529
530} // 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