pgrx_sql_entity_graph/pg_extern/
mod.rs1mod argument;
19pub mod attribute;
20mod cast;
21pub mod entity;
22mod operator;
23mod returning;
24mod search_path;
25
26pub use argument::PgExternArgument;
27pub(crate) use attribute::Attribute;
28pub use cast::PgCast;
29pub use operator::PgOperator;
30pub use returning::NameMacro;
31use syn::token::Comma;
32
33use self::returning::Returning;
34use crate::ExternArgs;
35use crate::ToSqlConfig;
36use crate::enrich::{CodeEnrichment, ToEntityGraphTokens, ToRustCodeTokens};
37use crate::finfo::{finfo_v1_extern_c, finfo_v1_tokens};
38use crate::fmt::ErrHarder;
39use operator::{PgrxOperatorAttributeWithIdent, PgrxOperatorOpName};
40use search_path::SearchPathList;
41
42use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
43use quote::quote;
44use syn::parse::{Parse, ParseStream, Parser};
45use syn::punctuated::Punctuated;
46use syn::spanned::Spanned;
47use syn::{Meta, Token};
48
49macro_rules! quote_spanned {
50 ($span:expr=> $($expansion:tt)*) => {
51 {
52 let synthetic = Span::mixed_site();
53 let synthetic = synthetic.located_at($span);
54 quote::quote_spanned! {synthetic=> $($expansion)* }
55 }
56 };
57}
58
59macro_rules! format_ident {
60 ($s:literal, $e:expr) => {{
61 let mut synthetic = $e.clone();
62 synthetic.set_span(Span::call_site().located_at($e.span()));
63 quote::format_ident!($s, synthetic)
64 }};
65}
66
67#[derive(Debug, Clone)]
90pub struct PgExtern {
91 attrs: Vec<Attribute>,
92 func: syn::ItemFn,
93 to_sql_config: ToSqlConfig,
94 operator: Option<PgOperator>,
95 cast: Option<PgCast>,
96 search_path: Option<SearchPathList>,
97 inputs: Vec<PgExternArgument>,
98 returns: Returning,
99}
100
101impl PgExtern {
102 #[track_caller]
103 pub fn new(attr: TokenStream2, item: TokenStream2) -> Result<CodeEnrichment<Self>, syn::Error> {
104 let mut attrs = Vec::new();
105 let mut to_sql_config: Option<ToSqlConfig> = None;
106
107 let parser = Punctuated::<Attribute, Token![,]>::parse_terminated;
108 let attr_ts = attr.clone();
109 let punctuated_attrs = parser
110 .parse2(attr)
111 .more_error(lazy_err!(attr_ts, "failed parsing pg_extern arguments"))?;
112 for pair in punctuated_attrs.into_pairs() {
113 match pair.into_value() {
114 Attribute::Sql(config) => to_sql_config = to_sql_config.or(Some(config)),
115 attr => attrs.push(attr),
116 }
117 }
118
119 let mut to_sql_config = to_sql_config.unwrap_or_default();
120
121 let func = syn::parse2::<syn::ItemFn>(item)?;
122
123 if let Some(ref mut content) = to_sql_config.content {
124 let value = content.value();
125 let span = content.span();
127 let updated_value =
128 value.replace("@FUNCTION_NAME@", &(func.sig.ident.to_string() + "_wrapper")) + "\n";
129 *content = syn::LitStr::new(&updated_value, span);
130 }
131
132 if !to_sql_config.overrides_default() {
133 crate::ident_is_acceptable_to_postgres(&func.sig.ident)?;
134 }
135 let operator = Self::operator(&func)?;
136 let search_path = Self::search_path(&func)?;
137 let inputs = Self::inputs(&func)?;
138 let returns = Returning::try_from(&func.sig.output)?;
139 Ok(CodeEnrichment(Self {
140 attrs,
141 func,
142 to_sql_config,
143 operator,
144 cast: None,
145 search_path,
146 inputs,
147 returns,
148 }))
149 }
150
151 pub fn as_cast(&self, pg_cast: PgCast) -> Self {
153 let mut result = self.clone();
154 result.cast = Some(pg_cast);
155 result
156 }
157
158 fn name(&self) -> String {
159 self.attrs
160 .iter()
161 .find_map(|a| match a {
162 Attribute::Name(name) => Some(name.value()),
163 _ => None,
164 })
165 .unwrap_or_else(|| self.func.sig.ident.to_string())
166 }
167
168 fn schema(&self) -> Option<String> {
169 self.attrs.iter().find_map(|a| match a {
170 Attribute::Schema(name) => Some(name.value()),
171 _ => None,
172 })
173 }
174
175 pub fn extern_attrs(&self) -> &[Attribute] {
176 self.attrs.as_slice()
177 }
178
179 #[track_caller]
180 fn overridden(&self) -> Option<syn::LitStr> {
181 let mut span = None;
182 let mut retval = None;
183 let mut in_commented_sql_block = false;
184 for meta in self.func.attrs.iter().filter_map(|attr| {
185 if attr.meta.path().is_ident("doc") { Some(attr.meta.clone()) } else { None }
186 }) {
187 let Meta::NameValue(syn::MetaNameValue { ref value, .. }) = meta else { continue };
188 let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(inner), .. }) = value else {
189 continue;
190 };
191 span.get_or_insert(value.span());
192 if !in_commented_sql_block && inner.value().trim() == "```pgrxsql" {
193 in_commented_sql_block = true;
194 } else if in_commented_sql_block && inner.value().trim() == "```" {
195 in_commented_sql_block = false;
196 } else if in_commented_sql_block {
197 let line = inner
198 .value()
199 .trim_start()
200 .replace("@FUNCTION_NAME@", &(self.func.sig.ident.to_string() + "_wrapper"))
201 + "\n";
202 retval.get_or_insert_with(String::default).push_str(&line);
203 }
204 }
205 retval.map(|s| syn::LitStr::new(s.as_ref(), span.unwrap()))
206 }
207
208 #[track_caller]
209 fn operator(func: &syn::ItemFn) -> syn::Result<Option<PgOperator>> {
210 let mut skel = Option::<PgOperator>::default();
211 for attr in &func.attrs {
212 let last_segment = attr.path().segments.last().unwrap();
213 match last_segment.ident.to_string().as_str() {
214 s @ "opname" => {
215 let attr = attr
217 .parse_args::<PgrxOperatorOpName>()
218 .more_error(lazy_err!(attr.clone(), "bad parse of {s}?"))?;
219 skel.get_or_insert_with(Default::default).opname.get_or_insert(attr);
220 }
221 s @ "commutator" => {
222 let attr: PgrxOperatorAttributeWithIdent = attr
223 .parse_args()
224 .more_error(lazy_err!(attr.clone(), "bad parse of {s}?"))?;
225
226 skel.get_or_insert_with(Default::default).commutator.get_or_insert(attr);
227 }
228 s @ "negator" => {
229 let attr: PgrxOperatorAttributeWithIdent = attr
230 .parse_args()
231 .more_error(lazy_err!(attr.clone(), "bad parse of {s}?"))?;
232 skel.get_or_insert_with(Default::default).negator.get_or_insert(attr);
233 }
234 s @ "join" => {
235 let attr: PgrxOperatorAttributeWithIdent = attr
236 .parse_args()
237 .more_error(lazy_err!(attr.clone(), "bad parse of {s}?"))?;
238
239 skel.get_or_insert_with(Default::default).join.get_or_insert(attr);
240 }
241 s @ "restrict" => {
242 let attr: PgrxOperatorAttributeWithIdent = attr
243 .parse_args()
244 .more_error(lazy_err!(attr.clone(), "bad parse of {s}?"))?;
245
246 skel.get_or_insert_with(Default::default).restrict.get_or_insert(attr);
247 }
248 "hashes" => {
249 skel.get_or_insert_with(Default::default).hashes = true;
250 }
251 "merges" => {
252 skel.get_or_insert_with(Default::default).merges = true;
253 }
254 _ => (),
255 }
256 }
257 Ok(skel)
258 }
259
260 fn search_path(func: &syn::ItemFn) -> syn::Result<Option<SearchPathList>> {
261 func.attrs
262 .iter()
263 .find(|f| {
264 f.path()
265 .segments
266 .first()
267 .map(|f| f.ident == Ident::new("search_path", func.span()))
269 .unwrap_or_default()
270 })
271 .map(|attr| attr.parse_args::<SearchPathList>())
272 .transpose()
273 }
274
275 fn inputs(func: &syn::ItemFn) -> syn::Result<Vec<PgExternArgument>> {
276 let mut args = Vec::default();
277 for input in &func.sig.inputs {
278 let arg = PgExternArgument::build(input.clone())?;
279 args.push(arg);
280 }
281 Ok(args)
282 }
283
284 fn entity_tokens(&self) -> TokenStream2 {
285 let ident = &self.func.sig.ident;
286 let name = self.name();
287 let schema = self.schema();
288 let inputs = &self.inputs;
289 let returns = &self.returns;
290 let to_sql_config = match self.overridden() {
291 None => self.to_sql_config.clone(),
292 Some(content) => ToSqlConfig { content: Some(content), ..self.to_sql_config.clone() },
293 };
294 let sql_graph_entity_fn_name = format_ident!("__pgrx_schema_fn_{}", ident);
295 let input_count = self.inputs.len();
296 let extern_args: Vec<ExternArgs> =
297 self.attrs.iter().filter_map(Attribute::as_extern_arg).collect();
298 let extern_attr_count = extern_args.len();
299 let args_len = inputs.iter().map(PgExternArgument::section_len_tokens);
300 let return_len = returns.section_len_tokens();
301 let schema_len = schema
302 .as_ref()
303 .map(|schema| {
304 quote! {
305 ::pgrx::pgrx_sql_entity_graph::section::bool_len()
306 + ::pgrx::pgrx_sql_entity_graph::section::str_len(#schema)
307 }
308 })
309 .unwrap_or_else(|| quote! { ::pgrx::pgrx_sql_entity_graph::section::bool_len() });
310 let extern_attr_lens = extern_args.iter().map(ExternArgs::section_len_tokens);
311 let search_path_len = self
312 .search_path
313 .as_ref()
314 .map(SearchPathList::section_len_tokens)
315 .unwrap_or_else(|| quote! { ::pgrx::pgrx_sql_entity_graph::section::bool_len() });
316 let operator_len = self
317 .operator
318 .as_ref()
319 .map(|operator| {
320 let inner = operator.section_len_tokens();
321 quote! {
322 ::pgrx::pgrx_sql_entity_graph::section::bool_len() + (#inner)
323 }
324 })
325 .unwrap_or_else(|| quote! { ::pgrx::pgrx_sql_entity_graph::section::bool_len() });
326 let cast_len = self
327 .cast
328 .as_ref()
329 .map(|cast| {
330 let inner = cast.section_len_tokens();
331 quote! {
332 ::pgrx::pgrx_sql_entity_graph::section::bool_len() + (#inner)
333 }
334 })
335 .unwrap_or_else(|| quote! { ::pgrx::pgrx_sql_entity_graph::section::bool_len() });
336 let to_sql_config_len = to_sql_config.section_len_tokens();
337 let payload_len = quote! {
338 ::pgrx::pgrx_sql_entity_graph::section::u8_len()
339 + ::pgrx::pgrx_sql_entity_graph::section::str_len(#name)
340 + ::pgrx::pgrx_sql_entity_graph::section::str_len(stringify!(#ident))
341 + ::pgrx::pgrx_sql_entity_graph::section::str_len(core::module_path!())
342 + ::pgrx::pgrx_sql_entity_graph::section::str_len(concat!(core::module_path!(), "::", stringify!(#ident)))
343 + ::pgrx::pgrx_sql_entity_graph::section::list_len(&[
344 #( #args_len ),*
345 ])
346 + (#return_len)
347 + (#schema_len)
348 + ::pgrx::pgrx_sql_entity_graph::section::str_len(file!())
349 + ::pgrx::pgrx_sql_entity_graph::section::u32_len()
350 + ::pgrx::pgrx_sql_entity_graph::section::list_len(&[
351 #( #extern_attr_lens ),*
352 ])
353 + (#search_path_len)
354 + (#operator_len)
355 + (#cast_len)
356 + (#to_sql_config_len)
357 };
358 let total_len = quote! {
359 ::pgrx::pgrx_sql_entity_graph::section::u32_len() + (#payload_len)
360 };
361 let writer_ident =
362 Ident::new("__pgrx_schema_writer", Span::mixed_site().located_at(ident.span()));
363 let arg_writers =
364 inputs.iter().map(|arg| arg.section_writer_tokens(quote! { #writer_ident }));
365 let return_writer = returns.section_writer_tokens(quote! { #writer_ident });
366 let schema_writer = schema
367 .as_ref()
368 .map(|schema| quote! { .bool(true).str(#schema) })
369 .unwrap_or_else(|| quote! { .bool(false) });
370 let extern_attr_writers = extern_args
371 .iter()
372 .map(|extern_arg| extern_arg.section_writer_tokens(quote! { #writer_ident }));
373 let search_path_writer = self
374 .search_path
375 .as_ref()
376 .map(|search_path| search_path.section_writer_tokens(quote! { #writer_ident }))
377 .unwrap_or_else(|| quote! { #writer_ident.bool(false) });
378 let operator_writer = self
379 .operator
380 .as_ref()
381 .map(|operator| operator.section_writer_tokens(quote! { #writer_ident.bool(true) }))
382 .unwrap_or_else(|| quote! { #writer_ident.bool(false) });
383 let cast_writer = self
384 .cast
385 .as_ref()
386 .map(|cast| cast.section_writer_tokens(quote! { #writer_ident.bool(true) }))
387 .unwrap_or_else(|| quote! { #writer_ident.bool(false) });
388 let to_sql_config_writer = to_sql_config.section_writer_tokens(quote! { #writer_ident });
389 quote_spanned! { self.func.sig.span() =>
390 ::pgrx::pgrx_sql_entity_graph::__pgrx_schema_entry!(
391 #sql_graph_entity_fn_name,
392 #total_len,
393 {
394 let #writer_ident = ::pgrx::pgrx_sql_entity_graph::section::EntryWriter::<{ #total_len }>::new()
395 .u32((#payload_len) as u32)
396 .u8(::pgrx::pgrx_sql_entity_graph::section::ENTITY_FUNCTION)
397 .str(#name)
398 .str(stringify!(#ident))
399 .str(core::module_path!())
400 .str(concat!(core::module_path!(), "::", stringify!(#ident)))
401 .u32(#input_count as u32);
402 #( let #writer_ident = { #arg_writers }; )*
403 let #writer_ident = { #return_writer };
404 let #writer_ident = #writer_ident
405 #schema_writer
406 .str(file!())
407 .u32(line!())
408 .u32(#extern_attr_count as u32);
409 #( let #writer_ident = { #extern_attr_writers }; )*
410 let #writer_ident = { #search_path_writer };
411 let #writer_ident = { #operator_writer };
412 let #writer_ident = { #cast_writer };
413 let #writer_ident = { #to_sql_config_writer };
414 #writer_ident.finish()
415 }
416 );
417 }
418 }
419
420 pub fn wrapper_func(&self) -> Result<syn::ItemFn, syn::Error> {
421 let signature = &self.func.sig;
422 let func_name = &signature.ident;
423 let synthetic_ident_span = Span::mixed_site().located_at(signature.ident.span());
425 let fcinfo_ident = syn::Ident::new("fcinfo", synthetic_ident_span);
426 let mut lifetimes = signature
427 .generics
428 .lifetimes()
429 .cloned()
430 .collect::<syn::punctuated::Punctuated<_, Comma>>();
431 let fc_lt = lifetimes
434 .first()
435 .map(|lt_p| lt_p.lifetime.clone())
436 .filter(|lt| lt.ident != "static")
437 .unwrap_or(syn::Lifetime::new("'fcx", Span::mixed_site()));
438 let fc_ltparam = syn::LifetimeParam::new(fc_lt.clone());
440 if lifetimes.first() != Some(&fc_ltparam) {
441 lifetimes.insert(0, fc_ltparam)
442 }
443
444 let args = &self.inputs;
445 let arg_pats = args.iter().map(|v| format_ident!("{}_", &v.pat)).collect::<Vec<_>>();
447 let args_ident = proc_macro2::Ident::new("_args", Span::call_site());
448 let arg_fetches = arg_pats.iter().map(|pat| {
449 quote_spanned!{ pat.span() =>
450 let #pat = #args_ident.next_arg_unchecked().unwrap_or_else(|| panic!("unboxing {} argument failed", stringify!(#pat)));
451 }
452 }
453 );
454
455 match &self.returns {
456 Returning::None
457 | Returning::Type(_)
458 | Returning::SetOf { .. }
459 | Returning::Iterated { .. } => {
460 let ret_ty = match &signature.output {
461 syn::ReturnType::Default => syn::parse_quote! { () },
462 syn::ReturnType::Type(_, ret_ty) => ret_ty.clone(),
463 };
464 let wrapper_code = quote_spanned! { self.func.block.span() =>
465 fn _internal_wrapper<#lifetimes>(fcinfo: &mut ::pgrx::callconv::FcInfo<#fc_lt>) -> ::pgrx::datum::Datum<#fc_lt> {
466 #[allow(unused_unsafe)]
467 unsafe {
468 let call_flow = <#ret_ty as ::pgrx::callconv::RetAbi>::check_and_prepare(fcinfo);
469 let result = match call_flow {
470 ::pgrx::callconv::CallCx::WrappedFn(mcx) => {
471 let mut mcx = ::pgrx::PgMemoryContexts::For(mcx);
472 let #args_ident = &mut fcinfo.args();
473 let call_result = mcx.switch_to(|_| {
474 #(#arg_fetches)*
475 #func_name( #(#arg_pats),* )
476 });
477 ::pgrx::callconv::RetAbi::to_ret(call_result)
478 }
479 ::pgrx::callconv::CallCx::RestoreCx => <#ret_ty as ::pgrx::callconv::RetAbi>::ret_from_fcx(fcinfo),
480 };
481 unsafe { <#ret_ty as ::pgrx::callconv::RetAbi>::box_ret_in(fcinfo, result) }
482 }
483 }
484 let datum = unsafe {
486 ::pgrx::pg_sys::submodules::panic::pgrx_extern_c_guard(|| {
487 let mut fcinfo = ::pgrx::callconv::FcInfo::from_ptr(#fcinfo_ident);
488 _internal_wrapper(&mut fcinfo)
489 })
490 };
491 datum.sans_lifetime()
492 };
493 finfo_v1_extern_c(&self.func, fcinfo_ident, wrapper_code)
494 }
495 }
496 }
497}
498
499trait LastIdent {
500 fn filter_last_ident(&self, id: &str) -> Option<&syn::PathSegment>;
501 #[inline]
502 fn last_ident_is(&self, id: &str) -> bool {
503 self.filter_last_ident(id).is_some()
504 }
505}
506
507impl LastIdent for syn::Type {
508 #[inline]
509 fn filter_last_ident(&self, id: &str) -> Option<&syn::PathSegment> {
510 let Self::Path(syn::TypePath { path, .. }) = self else { return None };
511 path.filter_last_ident(id)
512 }
513}
514impl LastIdent for syn::TypePath {
515 #[inline]
516 fn filter_last_ident(&self, id: &str) -> Option<&syn::PathSegment> {
517 self.path.filter_last_ident(id)
518 }
519}
520impl LastIdent for syn::Path {
521 #[inline]
522 fn filter_last_ident(&self, id: &str) -> Option<&syn::PathSegment> {
523 self.segments.filter_last_ident(id)
524 }
525}
526impl<P> LastIdent for Punctuated<syn::PathSegment, P> {
527 #[inline]
528 fn filter_last_ident(&self, id: &str) -> Option<&syn::PathSegment> {
529 self.last().filter(|segment| segment.ident == id)
530 }
531}
532
533impl ToEntityGraphTokens for PgExtern {
534 fn to_entity_graph_tokens(&self) -> TokenStream2 {
535 self.entity_tokens()
536 }
537}
538
539impl ToRustCodeTokens for PgExtern {
540 fn to_rust_code_tokens(&self) -> TokenStream2 {
541 let original_func = &self.func;
542 let wrapper_func = self.wrapper_func().unwrap();
543 let finfo_tokens = finfo_v1_tokens(wrapper_func.sig.ident.clone()).unwrap();
544
545 quote_spanned! { self.func.sig.span() =>
546 #original_func
547 #wrapper_func
548 #finfo_tokens
549 }
550 }
551}
552
553impl Parse for CodeEnrichment<PgExtern> {
554 fn parse(input: ParseStream) -> Result<Self, syn::Error> {
555 let parser = Punctuated::<Attribute, Token![,]>::parse_terminated;
556 let punctuated_attrs = input.call(parser).ok().unwrap_or_default();
557 let attrs = punctuated_attrs.into_pairs().map(|pair| pair.into_value());
558 PgExtern::new(quote! {#(#attrs)*}, input.parse()?)
559 }
560}