sqlx_askama_template/v3/
template_arg.rs1use std::{cell::RefCell, ops::Deref};
2
3use sqlx_core::{Error, arguments::Arguments, database::Database, encode::Encode, types::Type};
4pub struct TemplateArg<'q, DB: Database, D> {
11 error: RefCell<Option<Error>>,
13 arguments: RefCell<Option<DB::Arguments<'q>>>,
15 encode_placeholder_fn: Option<fn(usize, &mut String)>,
16 data: &'q D,
17}
18
19impl<'q, DB: Database, D> TemplateArg<'q, DB, D> {
20 pub fn new(d: &'q D) -> Self {
25 TemplateArg {
26 error: RefCell::new(None),
27 arguments: RefCell::new(None),
28 encode_placeholder_fn: None,
29 data: d,
30 }
31 }
32 pub fn set_encode_placeholder_fn(&mut self, f: fn(usize, &mut String)) {
37 self.encode_placeholder_fn = Some(f);
38 }
39
40 pub fn e<ImplEncode>(&self, t: ImplEncode) -> String
53 where
54 ImplEncode: Encode<'q, DB> + Type<DB> + 'q,
55 {
56 let mut arguments = self.arguments.borrow_mut().take().unwrap_or_default();
57 let mut err = self.error.borrow_mut();
58
59 if let Err(encode_err) = arguments.add(t) {
60 if err.is_none() {
61 *err = Some(Error::Encode(encode_err));
62 }
63 }
64
65 let mut placeholder = String::new();
66 if let Some(encode_placeholder_fn) = &self.encode_placeholder_fn {
67 encode_placeholder_fn(arguments.len(), &mut placeholder);
68 } else if let Err(e) = arguments.format_placeholder(&mut placeholder) {
69 *err = Some(Error::Encode(Box::new(e)));
70 }
71 *self.arguments.borrow_mut() = Some(arguments);
72 placeholder
73 }
74 pub fn el<ImplEncode>(&self, args: impl ::std::iter::IntoIterator<Item = ImplEncode>) -> String
87 where
88 ImplEncode: Encode<'q, DB> + Type<DB> + 'q,
89 {
90 let mut placeholder = String::new();
91 placeholder.push('(');
92
93 for arg in args {
94 placeholder.push_str(&self.e(arg));
95
96 placeholder.push(',');
97 }
98
99 if placeholder.ends_with(",") {
100 placeholder.pop();
101 }
102 placeholder.push(')');
103
104 placeholder
105 }
106 pub fn et<ImplEncode>(&self, t: &ImplEncode) -> ::std::string::String
111 where
112 ImplEncode: Encode<'q, DB> + Type<DB> + ::std::clone::Clone + 'q,
113 {
114 self.e(t.clone())
115 }
116 pub fn etl<'arg_b, ImplEncode>(
121 &self,
122 args: impl ::std::iter::IntoIterator<Item = &'arg_b ImplEncode>,
123 ) -> ::std::string::String
124 where
125 'q: 'arg_b,
126 ImplEncode: Encode<'q, DB> + Type<DB> + ::std::clone::Clone + 'q,
127 {
128 let args = args.into_iter().cloned();
129 self.el(args)
130 }
131
132 pub fn get_err(&self) -> Option<Error> {
134 self.error.borrow_mut().take()
135 }
136
137 pub fn get_arguments(&self) -> Option<DB::Arguments<'q>> {
139 self.arguments.borrow_mut().take()
140 }
141}
142
143impl<'q, DB: Database, D> Deref for TemplateArg<'q, DB, D> {
144 type Target = &'q D;
145 fn deref(&self) -> &Self::Target {
146 &self.data
147 }
148}