11#include "syscache.hpp"
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;
50 operator FunctionCallInfo()
const {
return info_; }
55 short nargs()
const {
return info_->nargs; }
62 return std::views::iota(0,
nargs()) | std::views::transform([
this](
int i) ->
nullable_datum {
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)};
81 return std::views::iota(0,
nargs()) | std::views::transform([
this](
int i) ->
value {
83 {.oid = ffi_guard{::get_fn_expr_argtype}(info_->flinfo, i)});
100 ::FunctionCallInfo info_;
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;
116 static std::optional<function_call_info> call_info() {
117 if (!calls.empty()) {
128 ~handle() { calls.pop(); }
136 static handle push(::FunctionCallInfo fcinfo) {
140 static void pop() { calls.pop(); }
142 static inline std::stack<::FunctionCallInfo> calls;
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;
173 auto rettype =
type{.oid =
ffi_guard{::get_fn_expr_rettype}(fc->flinfo)};
174 auto retset = fc->flinfo->fn_retset;
178 auto rsinfo =
reinterpret_cast<::ReturnSetInfo *
>(fc->resultinfo);
179 if (rsinfo ==
nullptr) {
180 report(ERROR,
"caller is not expecting a set");
184 if (!OidIsValid(rettype.oid)) {
187 rettype =
type{.oid = (*cache).prorettype};
188 retset = (*cache).proretset;
193 using set_value_type = set_iterator_traits<return_type>::value_type;
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());
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());
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());
212 if (fc->nargs < arity) {
213 report(ERROR,
"expected %d arguments, got %d instead", arity, fc->nargs);
215 short accounted_for_args = 0;
216 auto t = [&]<std::size_t... Is>(std::index_sequence<Is...>) {
217 return argument_types{([&]() -> utils::tuple_element_t<Is, argument_types> {
218 using ptyp = utils::tuple_element_t<Is, argument_types>;
219 auto typ =
type{.oid =
ffi_guard{::get_fn_expr_argtype}(fc->flinfo, Is)};
220 if (!OidIsValid(typ.oid)) {
223 if ((*cache).proargtypes.dim1 > Is) {
224 typ =
type{.oid = (*cache).proargtypes.values[Is]};
228 report(ERROR,
"unexpected type in position %d, can't convert `%s` into `%.*s`", Is,
229 typ.name().data(), utils::type_name<ptyp>().length(),
230 utils::type_name<ptyp>().data());
232 accounted_for_args++;
233 return from_nullable_datum<ptyp>(
nullable_datum(fc->args[Is]), typ.oid);
235 }(std::make_index_sequence<utils::tuple_size_v<argument_types>>{});
237 if (arity != accounted_for_args) {
238 report(ERROR,
"expected %d arguments, got %d instead", arity, accounted_for_args);
241 auto call_handle = current_postgres_function::push(fc);
244 auto rsinfo =
reinterpret_cast<::ReturnSetInfo *
>(fc->resultinfo);
246 using set_value_type = set_iterator_traits<return_type>::value_type;
247 if constexpr (std::same_as<set_value_type, record>) {
249 auto natts = rsinfo->expectedDesc ==
nullptr ? -1 : rsinfo->expectedDesc->natts;
251 rsinfo->returnMode = SFRM_Materialize;
255 ::Tuplestorestate *tupstore =
ffi_guard{::tuplestore_begin_heap}(
256 (rsinfo->allowedModes & SFRM_Materialize_Random) == SFRM_Materialize_Random,
false,
258 rsinfo->setResult = tupstore;
260 auto res = std::apply(func, t);
262 bool checked =
false;
264 auto nargs = r.attributes();
266 if (rsinfo->expectedDesc !=
nullptr && nargs != natts) {
267 throw std::runtime_error(
268 cppgres::fmt::format(
"expected record with {} value{}, got {} instead", nargs,
269 nargs == 1 ?
"" :
"s", natts));
271 if (rsinfo->expectedDesc !=
nullptr &&
272 !r.get_tuple_descriptor().equal_types(
274 throw std::runtime_error(
"expected and returned records do not match");
279 ffi_guard{::tuplestore_puttuple}(tupstore, r);
284 constexpr auto nargs = utils::tuple_size_v<set_value_type>;
286 auto natts = rsinfo->expectedDesc->natts;
288 if (nargs != natts) {
289 throw std::runtime_error(cppgres::fmt::format(
"expected set with {} value{}, got {} instead",
290 nargs, nargs == 1 ?
"" :
"s", natts));
293 [&]<std::size_t... Is>(std::index_sequence<Is...>) {
295 auto oid =
ffi_guard{::SPI_gettypeid}(rsinfo->expectedDesc, Is + 1);
297 using typ = utils::tuple_element_t<Is, set_value_type>;
299 throw std::invalid_argument(
300 cppgres::fmt::format(
"invalid type in record's position {} ({}), got OID {}", Is,
301 utils::type_name<typ>(),
oid));
305 }(std::make_index_sequence<nargs>{});
307 rsinfo->returnMode = SFRM_Materialize;
311 ::Tuplestorestate *tupstore =
ffi_guard{::tuplestore_begin_heap}(
312 (rsinfo->allowedModes & SFRM_Materialize_Random) == SFRM_Materialize_Random,
false,
314 rsinfo->setResult = tupstore;
316 auto result = std::apply(func, t);
318 for (
auto it : result) {
319 CHECK_FOR_INTERRUPTS();
320 std::array<::Datum, nargs> values = std::apply(
321 [](
auto &&...elems) -> std::array<::Datum,
sizeof...(elems)> {
322 return {into_nullable_datum(elems)...};
325 std::array<bool, nargs> isnull = std::apply(
326 [](
auto &&...elems) -> std::array<
bool,
sizeof...(elems)> {
327 return {into_nullable_datum(elems).is_null()...};
330 ffi_guard{::tuplestore_putvalues}(tupstore, rsinfo->expectedDesc, values.data(),
338 if constexpr (std::same_as<return_type, void>) {
342 auto result = std::apply(func, t);
348 return nd.operator const ::Datum &();
352 __builtin_unreachable();
363 ::List *fname = list_make2(::makeString(
const_cast<char *
>(schema)),
364 ::makeString(
const_cast<char *
>(
name)));
365 std::array<::Oid,
sizeof...(arg_types)> argtypes = {
367 return ffi_guard{::LookupFuncName}(fname,
static_cast<int>(
sizeof...(arg_types)),
368 argtypes.data(),
false);
375 ::List *fname = list_make1(::makeString(
const_cast<char *
>(
name)));
376 std::array<::Oid,
sizeof...(arg_types)> argtypes = {
378 return ffi_guard{::LookupFuncName}(fname,
static_cast<int>(
sizeof...(arg_types)),
379 argtypes.data(),
false);
386 auto &argtypes = (*p).proargtypes;
388 if (argtypes.dim1 !=
sizeof...(arg_types)) {
389 throw std::runtime_error(cppgres::fmt::format(
"expected {} argument{}, got {} instead",
390 sizeof...(arg_types),
391 sizeof...(arg_types) == 1 ?
"" :
"s",
394 for (
int i = 0; i < argtypes.dim1; i++) {
396 if (types[i] !=
type{UNKNOWNOID} &&
397 arg != types[i].oid) {
398 throw std::runtime_error(cppgres::fmt::format(
"expected type {} for argument {}, got {}",
399 types[i].
name(), i,
type{.oid = arg}.name()));
403 rettype_ = (*p).prorettype;
407 throw std::runtime_error(cppgres::fmt::format(
"expected return type {}, got {}",
409 type{.oid = rettype_}.name()));
411 strict_ = (*p).proisstrict;
415 template <
typename... Args>
static constexpr bool convertible_args() {
416 if constexpr (
sizeof...(Args) !=
sizeof...(arg_types)) {
419 return []<std::size_t... I>(std::index_sequence<I...>) {
420 return (std::convertible_to<std::decay_t<Args>,
421 std::tuple_element_t<I, std::tuple<arg_types...>>> &&
423 }(std::make_index_sequence<
sizeof...(Args)>{});
426 ret_type operator()(
auto... args)
requires(self::convertible_args<
decltype(args)...>())
428 bool any_nulls =
false;
429 auto optval = []<std::size_t I>(
auto arg) -> ::Datum {
430 using nth_type = std::tuple_element_t<I, std::tuple<arg_types...>>;
431 if constexpr (std::same_as<std::nullopt_t,
decltype(arg)>) {
440 auto isnull = [&any_nulls](
auto arg) {
441 if constexpr (std::same_as<std::nullopt_t,
decltype(arg)>) {
447 any_nulls = any_nulls || !arg.has_value();
448 return !arg.has_value();
452 return [&]<std::size_t... I>(std::index_sequence<I...>) -> ret_type {
453 LOCAL_FCINFO(fcinfo,
sizeof...(args));
458 InitFunctionCallInfoData(*fcinfo, &flinfo,
sizeof...(args), InvalidOid,
nullptr,
nullptr);
460 ((fcinfo->args[I].value = optval.template operator()<I>(args)), ...);
461 ((fcinfo->args[I].isnull = isnull(args)), ...);
463 if (any_nulls && strict_) {
472 if (fcinfo->isnull) {
477 }(std::make_index_sequence<
sizeof...(args)>{});
480 const oid &function_oid()
const {
return oid_; }
490 static function<ret, Args...> from_datum(
const datum &d,
oid, std::optional<memory_context> ctx) {
500 static bool is(
const type &t) {
501 return t.oid == REGPROCEDUREOID || t.oid == OIDOID || t.oid == REGPROCOID;
503 static constexpr type type_for() {
return type{.oid = REGPROCEDUREOID}; }
509 ffi_guard{::getTypeOutputInfo}(type_traits<T>().type_for().oid, &foutoid, &typisvarlena);
510 return function<const char *, T>(foutoid);
513template <has_type_traits T> function<const char *, T> output_function(T &&v) {
516 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
517 return function<const char *, T>(foutoid);
520template <has_type_traits T> function<const char *, T> output_function(T &v) {
523 ffi_guard{::getTypeOutputInfo}(type_traits<T>(v).type_for().oid, &foutoid, &typisvarlena);
524 return function<const char *, T>(foutoid);
527static function<const char *, cppgres::value> output_function(
const type &t) {
530 ffi_guard{::getTypeOutputInfo}(t.oid, &foutoid, &typisvarlena);
531 return function<const char *, cppgres::value>(foutoid);
Definition: function.hpp:27
Definition: datum.hpp:213
Function that operates on values of Postgres types.
Definition: function.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:136
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:146
Wraps a C++ function to catch exceptions and report them as Postgres errors.
Definition: guard.hpp:64
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:356
Definition: memory.hpp:240
Definition: memory.hpp:103
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:21
Postgres type.
Definition: type.hpp:21
Definition: function_traits.hpp:37