1use std::collections::{BTreeMap, HashMap};
16use std::ops::ControlFlow;
17
18use common_base::secrets::{ExposeSecret, ExposeSecretMut, SecretString};
19use either::Either;
20use serde::Serialize;
21use sqlparser::ast::{Visit, VisitMut, Visitor, VisitorMut};
22use table::requests::{REDACTED_OPTION_VALUE, is_credential_option};
23
24use crate::util::OptionValue;
25
26#[derive(Clone, Debug, Default, Serialize)]
28pub struct OptionMap {
29 options: BTreeMap<String, OptionValue>,
30 #[serde(skip_serializing)]
31 secrets: BTreeMap<String, SecretString>,
32}
33
34impl OptionMap {
35 pub fn new<I: IntoIterator<Item = (String, OptionValue)>>(options: I) -> Self {
36 let (secrets, options): (Vec<_>, Vec<_>) = options
37 .into_iter()
38 .partition(|(k, _)| is_credential_option(k));
39 Self {
40 options: options.into_iter().collect(),
41 secrets: secrets
42 .into_iter()
43 .filter_map(|(k, v)| {
44 v.as_string()
45 .map(|v| (k, SecretString::new(Box::new(v.to_string()))))
46 })
47 .collect(),
48 }
49 }
50
51 pub fn from_filtered_string_map(
52 options: &HashMap<String, String>,
53 hidden_keys: &[&str],
54 ) -> Self {
55 Self::from(
56 options
57 .iter()
58 .filter(|(key, _)| !hidden_keys.contains(&key.as_str()))
59 .map(|(key, value)| (key.clone(), value.clone())),
60 )
61 }
62
63 pub fn insert(&mut self, k: String, v: String) {
64 if is_credential_option(&k) {
65 self.secrets.insert(k, SecretString::new(Box::new(v)));
66 } else {
67 self.options.insert(k, v.into());
68 }
69 }
70
71 pub fn insert_options(&mut self, key: &str, value: OptionValue) {
72 if is_credential_option(key) {
73 self.secrets.insert(
74 key.to_string(),
75 SecretString::new(Box::new(value.to_string())),
76 );
77 } else {
78 self.options.insert(key.to_string(), value);
79 }
80 }
81
82 pub fn get(&self, k: &str) -> Option<&str> {
83 if let Some(value) = self.options.get(k) {
84 value.as_string()
85 } else if let Some(value) = self.secrets.get(k) {
86 Some(value.expose_secret())
87 } else {
88 None
89 }
90 }
91
92 pub fn value(&self, k: &str) -> Option<&OptionValue> {
93 self.options.get(k)
94 }
95
96 pub fn is_empty(&self) -> bool {
97 self.options.is_empty() && self.secrets.is_empty()
98 }
99
100 pub fn len(&self) -> usize {
101 self.options.len() + self.secrets.len()
102 }
103
104 pub fn to_str_map(&self) -> HashMap<&str, &str> {
108 let mut map = HashMap::with_capacity(self.len());
109 map.extend(
110 self.options
111 .iter()
112 .filter_map(|(k, v)| v.as_string().map(|v| (k.as_str(), v))),
113 );
114 map.extend(
115 self.secrets
116 .iter()
117 .map(|(k, v)| (k.as_str(), v.expose_secret().as_str())),
118 );
119 map
120 }
121
122 pub fn into_map(self) -> HashMap<String, String> {
126 let mut map = HashMap::with_capacity(self.len());
127 map.extend(
128 self.options
129 .into_iter()
130 .filter_map(|(k, v)| v.as_string().map(|v| (k, v.to_string()))),
131 );
132 map.extend(
133 self.secrets
134 .into_iter()
135 .map(|(k, v)| (k, v.expose_secret().clone())),
136 );
137 map
138 }
139
140 pub fn kv_pairs(&self) -> Vec<String> {
141 self.sql_pairs(false).map(|pair| pair.to_string()).collect()
142 }
143
144 pub(crate) fn write_sql(
146 &self,
147 f: &mut dyn std::fmt::Write,
148 separator: &str,
149 prefix: &str,
150 complete: bool,
151 ) -> std::fmt::Result {
152 for (index, pair) in self.sql_pairs(complete).enumerate() {
153 if index > 0 {
154 f.write_str(separator)?;
155 }
156 write!(f, "{prefix}{pair}")?;
157 }
158 Ok(())
159 }
160
161 fn sql_pairs(&self, complete: bool) -> impl Iterator<Item = SqlPair<'_>> {
162 let options = self.options.iter().filter_map(move |(key, value)| {
163 let value = match value.as_string() {
164 Some(value) => Either::Right(value),
165 None if complete => Either::Left(value),
166 None => return None,
167 };
168 Some(SqlPair { key, value })
169 });
170 let secrets = self.secrets.iter().map(move |(key, value)| SqlPair {
171 key,
172 value: Either::Right(if complete {
173 value.expose_secret()
174 } else {
175 REDACTED_OPTION_VALUE
176 }),
177 });
178 options.chain(secrets)
179 }
180
181 pub fn entries(&self) -> impl Iterator<Item = (&str, Either<&OptionValue, &str>)> {
182 let options = self
183 .options
184 .iter()
185 .map(|(k, v)| (k.as_str(), Either::Left(v)));
186 let secrets = self
187 .secrets
188 .keys()
189 .map(|k| (k.as_str(), Either::Right(REDACTED_OPTION_VALUE)));
190 std::iter::chain(options, secrets)
191 }
192}
193
194struct SqlPair<'a> {
195 key: &'a str,
196 value: Either<&'a OptionValue, &'a str>,
197}
198
199impl std::fmt::Display for SqlPair<'_> {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 if self.key.contains('.') {
202 write!(f, "'{}'", self.key)?;
203 } else {
204 f.write_str(self.key)?;
205 }
206 match self.value {
207 Either::Left(value) => write!(f, " = {value}"),
208 Either::Right(value) => write!(f, " = '{}'", value.escape_debug()),
209 }
210 }
211}
212
213impl<I: IntoIterator<Item = (String, String)>> From<I> for OptionMap {
214 fn from(value: I) -> Self {
215 let mut result = OptionMap::default();
216 for (k, v) in value {
217 result.insert(k, v);
218 }
219 result
220 }
221}
222
223impl PartialEq for OptionMap {
224 fn eq(&self, other: &Self) -> bool {
225 if self.options.ne(&other.options) {
226 return false;
227 }
228
229 if self.secrets.len() != other.secrets.len() {
230 return false;
231 }
232
233 self.secrets.iter().all(|(key, value)| {
234 other
235 .secrets
236 .get(key)
237 .is_some_and(|v| value.expose_secret() == v.expose_secret())
238 })
239 }
240}
241
242impl Eq for OptionMap {}
243
244impl Visit for OptionMap {
245 fn visit<V: Visitor>(&self, visitor: &mut V) -> ControlFlow<V::Break> {
246 for (k, v) in &self.options {
247 k.visit(visitor)?;
248 v.visit(visitor)?;
249 }
250 for (k, v) in &self.secrets {
251 k.visit(visitor)?;
252 v.expose_secret().visit(visitor)?;
253 }
254 ControlFlow::Continue(())
255 }
256}
257
258impl VisitMut for OptionMap {
259 fn visit<V: VisitorMut>(&mut self, visitor: &mut V) -> ControlFlow<V::Break> {
260 for v in self.options.values_mut() {
261 v.visit(visitor)?;
262 }
263 for v in self.secrets.values_mut() {
264 v.expose_secret_mut().visit(visitor)?;
265 }
266 ControlFlow::Continue(())
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use std::collections::HashMap;
273
274 use crate::statements::OptionMap;
275
276 #[test]
277 fn test_format() {
278 let mut map = OptionMap::default();
279 map.insert("comment".to_string(), "中文comment".to_string());
280 assert_eq!("comment = '中文comment'", map.kv_pairs()[0]);
281
282 let mut map = OptionMap::default();
283 map.insert("a.b".to_string(), "中文comment".to_string());
284 assert_eq!("'a.b' = '中文comment'", map.kv_pairs()[0]);
285
286 let mut map = OptionMap::default();
287 map.insert("a.b".to_string(), "中文comment\n".to_string());
288 assert_eq!("'a.b' = '中文comment\\n'", map.kv_pairs()[0]);
289 }
290
291 #[test]
292 fn test_from_filtered_string_map() {
293 let map = OptionMap::from_filtered_string_map(
294 &HashMap::from([
295 ("visible".to_string(), "1".to_string()),
296 ("hidden".to_string(), "2".to_string()),
297 ]),
298 &["hidden"],
299 );
300
301 assert_eq!(map.get("visible"), Some("1"));
302 assert_eq!(map.get("hidden"), None);
303 }
304
305 #[test]
306 fn test_connection_option_is_redacted() {
307 let mut map = OptionMap::default();
308 map.insert(
309 "connection".to_string(),
310 "mysql://user:secret@127.0.0.1:3306/db".to_string(),
311 );
312 map.insert("remote_table".to_string(), "sample".to_string());
313
314 let pairs = map.kv_pairs();
315 assert!(pairs.contains(&"connection = '******'".to_string()));
317 assert!(pairs.contains(&"remote_table = 'sample'".to_string()));
319 assert_eq!(
321 map.get("connection"),
322 Some("mysql://user:secret@127.0.0.1:3306/db")
323 );
324 }
325}