Skip to main content

pgrx_sql_entity_graph/
extern_args.rs

1//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
2//LICENSE
3//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
4//LICENSE
5//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
6//LICENSE
7//LICENSE All rights reserved.
8//LICENSE
9//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
10use crate::PositioningRef;
11use proc_macro2::{Ident, Span, TokenStream, TokenTree};
12use quote::{ToTokens, TokenStreamExt, format_ident, quote};
13use std::collections::HashSet;
14
15#[derive(Debug, Hash, Eq, PartialEq, Clone, PartialOrd, Ord)]
16pub enum ExternArgs {
17    CreateOrReplace,
18    Immutable,
19    Strict,
20    Stable,
21    Volatile,
22    Raw,
23    NoGuard,
24    SecurityDefiner,
25    SecurityInvoker,
26    ParallelSafe,
27    ParallelUnsafe,
28    ParallelRestricted,
29    ShouldPanic(String),
30    Schema(String),
31    Support(PositioningRef),
32    Name(String),
33    Cost(String),
34    Requires(Vec<PositioningRef>),
35}
36
37impl core::fmt::Display for ExternArgs {
38    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39        match self {
40            Self::CreateOrReplace => write!(f, "CREATE OR REPLACE"),
41            Self::Immutable => write!(f, "IMMUTABLE"),
42            Self::Strict => write!(f, "STRICT"),
43            Self::Stable => write!(f, "STABLE"),
44            Self::Volatile => write!(f, "VOLATILE"),
45            Self::Raw => Ok(()),
46            Self::ParallelSafe => write!(f, "PARALLEL SAFE"),
47            Self::ParallelUnsafe => write!(f, "PARALLEL UNSAFE"),
48            Self::SecurityDefiner => write!(f, "SECURITY DEFINER"),
49            Self::SecurityInvoker => write!(f, "SECURITY INVOKER"),
50            Self::ParallelRestricted => write!(f, "PARALLEL RESTRICTED"),
51            Self::Support(item) => write!(f, "{item}"),
52            Self::ShouldPanic(_) => Ok(()),
53            Self::NoGuard => Ok(()),
54            Self::Schema(_) => Ok(()),
55            Self::Name(_) => Ok(()),
56            Self::Cost(cost) => write!(f, "COST {cost}"),
57            Self::Requires(_) => Ok(()),
58        }
59    }
60}
61
62impl ExternArgs {
63    pub fn section_len_tokens(&self) -> TokenStream {
64        match self {
65            Self::CreateOrReplace
66            | Self::Immutable
67            | Self::Strict
68            | Self::Stable
69            | Self::Volatile
70            | Self::Raw
71            | Self::NoGuard
72            | Self::SecurityDefiner
73            | Self::SecurityInvoker
74            | Self::ParallelSafe
75            | Self::ParallelUnsafe
76            | Self::ParallelRestricted => {
77                quote! { ::pgrx::pgrx_sql_entity_graph::section::u8_len() }
78            }
79            Self::ShouldPanic(value)
80            | Self::Schema(value)
81            | Self::Name(value)
82            | Self::Cost(value) => quote! {
83                ::pgrx::pgrx_sql_entity_graph::section::u8_len()
84                    + ::pgrx::pgrx_sql_entity_graph::section::str_len(#value)
85            },
86            Self::Support(item) => {
87                let item_len = item.section_len_tokens();
88                quote! {
89                    ::pgrx::pgrx_sql_entity_graph::section::u8_len() + (#item_len)
90                }
91            }
92            Self::Requires(items) => {
93                let item_lens = items.iter().map(PositioningRef::section_len_tokens);
94                quote! {
95                    ::pgrx::pgrx_sql_entity_graph::section::u8_len()
96                        + ::pgrx::pgrx_sql_entity_graph::section::list_len(&[
97                            #( #item_lens ),*
98                        ])
99                }
100            }
101        }
102    }
103
104    pub fn section_writer_tokens(&self, writer: TokenStream) -> TokenStream {
105        match self {
106            Self::CreateOrReplace => {
107                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_CREATE_OR_REPLACE) }
108            }
109            Self::Immutable => {
110                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_IMMUTABLE) }
111            }
112            Self::Strict => {
113                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_STRICT) }
114            }
115            Self::Stable => {
116                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_STABLE) }
117            }
118            Self::Volatile => {
119                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_VOLATILE) }
120            }
121            Self::Raw => {
122                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_RAW) }
123            }
124            Self::NoGuard => {
125                quote! { #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_NO_GUARD) }
126            }
127            Self::SecurityDefiner => quote! {
128                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_SECURITY_DEFINER)
129            },
130            Self::SecurityInvoker => quote! {
131                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_SECURITY_INVOKER)
132            },
133            Self::ParallelSafe => quote! {
134                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_PARALLEL_SAFE)
135            },
136            Self::ParallelUnsafe => quote! {
137                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_PARALLEL_UNSAFE)
138            },
139            Self::ParallelRestricted => quote! {
140                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_PARALLEL_RESTRICTED)
141            },
142            Self::ShouldPanic(value) => quote! {
143                #writer
144                    .u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_SHOULD_PANIC)
145                    .str(#value)
146            },
147            Self::Schema(value) => quote! {
148                #writer
149                    .u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_SCHEMA)
150                    .str(#value)
151            },
152            Self::Support(item) => item.section_writer_tokens(quote! {
153                #writer.u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_SUPPORT)
154            }),
155            Self::Name(value) => quote! {
156                #writer
157                    .u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_NAME)
158                    .str(#value)
159            },
160            Self::Cost(value) => quote! {
161                #writer
162                    .u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_COST)
163                    .str(#value)
164            },
165            Self::Requires(items) => {
166                let writer_ident = Ident::new("__pgrx_schema_writer", Span::mixed_site());
167                let item_writers =
168                    items.iter().map(|item| item.section_writer_tokens(quote! { #writer_ident }));
169                let count = items.len();
170                quote! {
171                    {
172                        let #writer_ident = #writer
173                            .u8(::pgrx::pgrx_sql_entity_graph::section::EXTERN_ARG_REQUIRES)
174                            .u32(#count as u32);
175                        #( let #writer_ident = { #item_writers }; )*
176                        #writer_ident
177                    }
178                }
179            }
180        }
181    }
182}
183
184impl ToTokens for ExternArgs {
185    fn to_tokens(&self, tokens: &mut TokenStream) {
186        match self {
187            Self::CreateOrReplace => tokens.append(format_ident!("CreateOrReplace")),
188            Self::Immutable => tokens.append(format_ident!("Immutable")),
189            Self::Strict => tokens.append(format_ident!("Strict")),
190            Self::Stable => tokens.append(format_ident!("Stable")),
191            Self::Volatile => tokens.append(format_ident!("Volatile")),
192            Self::Raw => tokens.append(format_ident!("Raw")),
193            Self::NoGuard => tokens.append(format_ident!("NoGuard")),
194            Self::SecurityDefiner => tokens.append(format_ident!("SecurityDefiner")),
195            Self::SecurityInvoker => tokens.append(format_ident!("SecurityInvoker")),
196            Self::ParallelSafe => tokens.append(format_ident!("ParallelSafe")),
197            Self::ParallelUnsafe => tokens.append(format_ident!("ParallelUnsafe")),
198            Self::ParallelRestricted => tokens.append(format_ident!("ParallelRestricted")),
199            Self::ShouldPanic(_s) => tokens.append_all(quote! { Error(String::from("#_s")) }),
200            Self::Schema(_s) => tokens.append_all(quote! { Schema(String::from("#_s")) }),
201            Self::Support(item) => tokens.append_all(quote! { Support(#item) }),
202            Self::Name(_s) => tokens.append_all(quote! { Name(String::from("#_s")) }),
203            Self::Cost(_s) => tokens.append_all(quote! { Cost(String::from("#_s")) }),
204            Self::Requires(items) => tokens.append_all(quote! { Requires(vec![#(#items),*]) }),
205        }
206    }
207}
208
209// This horror-story should be returning result
210#[track_caller]
211pub fn parse_extern_attributes(attr: TokenStream) -> HashSet<ExternArgs> {
212    let mut args = HashSet::<ExternArgs>::new();
213    let mut itr = attr.into_iter();
214    while let Some(t) = itr.next() {
215        match t {
216            TokenTree::Group(g) => {
217                for arg in parse_extern_attributes(g.stream()).into_iter() {
218                    args.insert(arg);
219                }
220            }
221            TokenTree::Ident(i) => {
222                let name = i.to_string();
223                match name.as_str() {
224                    "create_or_replace" => args.insert(ExternArgs::CreateOrReplace),
225                    "immutable" => args.insert(ExternArgs::Immutable),
226                    "strict" => args.insert(ExternArgs::Strict),
227                    "stable" => args.insert(ExternArgs::Stable),
228                    "volatile" => args.insert(ExternArgs::Volatile),
229                    "raw" => args.insert(ExternArgs::Raw),
230                    "no_guard" => args.insert(ExternArgs::NoGuard),
231                    "security_invoker" => args.insert(ExternArgs::SecurityInvoker),
232                    "security_definer" => args.insert(ExternArgs::SecurityDefiner),
233                    "parallel_safe" => args.insert(ExternArgs::ParallelSafe),
234                    "parallel_unsafe" => args.insert(ExternArgs::ParallelUnsafe),
235                    "parallel_restricted" => args.insert(ExternArgs::ParallelRestricted),
236                    "error" | "expected" => {
237                        let _punc = itr.next().unwrap();
238                        let literal = itr.next().unwrap();
239                        let message = literal.to_string();
240                        let message = unescape::unescape(&message).expect("failed to unescape");
241
242                        // trim leading/trailing quotes around the literal
243                        let message = message[1..message.len() - 1].to_string();
244                        args.insert(ExternArgs::ShouldPanic(message.to_string()))
245                    }
246                    "schema" => {
247                        let _punc = itr.next().unwrap();
248                        let literal = itr.next().unwrap();
249                        let schema = literal.to_string();
250                        let schema = unescape::unescape(&schema).expect("failed to unescape");
251
252                        // trim leading/trailing quotes around the literal
253                        let schema = schema[1..schema.len() - 1].to_string();
254                        args.insert(ExternArgs::Schema(schema.to_string()))
255                    }
256                    "name" => {
257                        let _punc = itr.next().unwrap();
258                        let literal = itr.next().unwrap();
259                        let name = literal.to_string();
260                        let name = unescape::unescape(&name).expect("failed to unescape");
261
262                        // trim leading/trailing quotes around the literal
263                        let name = name[1..name.len() - 1].to_string();
264                        args.insert(ExternArgs::Name(name.to_string()))
265                    }
266                    // Recognized, but not handled as an extern argument
267                    "sql" => {
268                        let _punc = itr.next().unwrap();
269                        let _value = itr.next().unwrap();
270                        false
271                    }
272                    _ => false,
273                };
274            }
275            TokenTree::Punct(_) => {}
276            TokenTree::Literal(_) => {}
277        }
278    }
279    args
280}
281
282#[cfg(test)]
283mod tests {
284    use std::str::FromStr;
285
286    use crate::{ExternArgs, parse_extern_attributes};
287
288    #[test]
289    fn parse_args() {
290        let s = "error = \"syntax error at or near \\\"THIS\\\"\"";
291        let ts = proc_macro2::TokenStream::from_str(s).unwrap();
292
293        let args = parse_extern_attributes(ts);
294        assert!(
295            args.contains(&ExternArgs::ShouldPanic("syntax error at or near \"THIS\"".to_string()))
296        );
297    }
298}