1use std::borrow::Cow;
16use std::ffi::c_char;
17
18use crate::error::Result;
19
20#[derive(Debug, Default, Clone)]
46pub struct QueryParams {
47 pairs: Vec<(String, QueryParam)>,
48}
49
50impl QueryParams {
51 pub fn new() -> Self {
57 Self::default()
58 }
59
60 pub fn bind(mut self, name: impl AsRef<str>, value: impl Into<QueryParam>) -> Self {
65 self.pairs.push((name.as_ref().to_owned(), value.into()));
66 self
67 }
68}
69
70impl<K, V, const N: usize> From<[(K, V); N]> for QueryParams
75where
76 K: AsRef<str>,
77 V: Into<QueryParam>,
78{
79 fn from(pairs: [(K, V); N]) -> Self {
80 let mut params = Self::new();
81 for (name, value) in pairs {
82 params = params.bind(name, value);
83 }
84 params
85 }
86}
87
88impl<K, V> From<Vec<(K, V)>> for QueryParams
90where
91 K: AsRef<str>,
92 V: Into<QueryParam>,
93{
94 fn from(pairs: Vec<(K, V)>) -> Self {
95 let mut params = Self::new();
96 for (name, value) in pairs {
97 params = params.bind(name, value);
98 }
99 params
100 }
101}
102
103impl IntoIterator for QueryParams {
104 type Item = (String, QueryParam);
105 type IntoIter = std::vec::IntoIter<(String, QueryParam)>;
106
107 fn into_iter(self) -> Self::IntoIter {
108 self.pairs.into_iter()
109 }
110}
111
112impl<'a> IntoIterator for &'a QueryParams {
113 type Item = (&'a str, &'a QueryParam);
114 type IntoIter = std::iter::Map<
115 std::slice::Iter<'a, (String, QueryParam)>,
116 fn(&'a (String, QueryParam)) -> (&'a str, &'a QueryParam),
117 >;
118
119 fn into_iter(self) -> Self::IntoIter {
120 self.pairs
121 .iter()
122 .map(|(name, value)| (name.as_str(), value))
123 }
124}
125
126#[derive(Debug, Clone, PartialEq)]
133pub enum QueryParam {
134 Null,
136 Bool(bool),
138 Int64(i64),
140 UInt64(u64),
142 Float64(f64),
144 Text(String),
146 Raw(String),
148 Array(Vec<QueryParam>),
150}
151
152impl QueryParam {
153 pub fn raw(value: impl Into<String>) -> Self {
158 Self::Raw(value.into())
159 }
160
161 pub fn encode(&self) -> Result<Cow<'_, str>> {
166 Ok(match self {
167 Self::Null => Cow::Borrowed("\\N"),
168 Self::Bool(true) => Cow::Borrowed("true"),
169 Self::Bool(false) => Cow::Borrowed("false"),
170 Self::Int64(value) => Cow::Owned(value.to_string()),
171 Self::UInt64(value) => Cow::Owned(value.to_string()),
172 Self::Float64(value) => Cow::Owned(value.to_string()),
173 Self::Text(value) => Self::encode_text(value),
174 Self::Raw(value) => Cow::Borrowed(value),
175 Self::Array(values) => Cow::Owned(Self::encode_array(values)?),
176 })
177 }
178
179 fn encode_text(value: &str) -> Cow<'_, str> {
181 let mut encoded = None;
182 let mut last = 0;
183
184 for (i, ch) in value.char_indices() {
185 let esc = match ch {
186 '\\' => r"\\",
187 '\t' => r"\t",
188 '\n' => r"\n",
189 _ => continue,
190 };
191 let buf = encoded.get_or_insert_with(|| String::with_capacity(value.len()));
192 buf.push_str(&value[last..i]);
193 buf.push_str(esc);
194 last = i + ch.len_utf8();
195 }
196
197 match encoded {
198 None => Cow::Borrowed(value),
199 Some(mut buf) => {
200 buf.push_str(&value[last..]);
201 Cow::Owned(buf)
202 }
203 }
204 }
205
206 fn encode_array(values: &[QueryParam]) -> Result<String> {
207 let mut out = String::with_capacity(2 + values.len() * 8);
209 Self::write_array(values, &mut out)?;
210 Ok(out)
211 }
212
213 fn write_array(values: &[QueryParam], out: &mut String) -> Result<()> {
216 out.push('[');
217 for (i, value) in values.iter().enumerate() {
218 if i > 0 {
219 out.push_str(", ");
220 }
221 value.write_nested(out)?;
222 }
223 out.push(']');
224 Ok(())
225 }
226
227 fn write_nested(&self, out: &mut String) -> Result<()> {
229 use std::fmt::Write as _;
230 match self {
232 Self::Null => out.push_str("NULL"),
233 Self::Bool(true) => out.push_str("true"),
234 Self::Bool(false) => out.push_str("false"),
235 Self::Int64(value) => write!(out, "{value}").expect("writing to a String"),
236 Self::UInt64(value) => write!(out, "{value}").expect("writing to a String"),
237 Self::Float64(value) => write!(out, "{value}").expect("writing to a String"),
238 Self::Text(value) => Self::write_quoted(value, out),
239 Self::Raw(value) => out.push_str(value),
240 Self::Array(values) => Self::write_array(values, out)?,
241 }
242 Ok(())
243 }
244
245 fn write_quoted(value: &str, out: &mut String) {
247 out.reserve(value.len() + 2);
248 out.push('\'');
249 for ch in value.chars() {
250 match ch {
251 '\\' => out.push_str(r"\\"),
252 '\t' => out.push_str(r"\t"),
253 '\n' => out.push_str(r"\n"),
254 '\'' => out.push_str(r"\'"),
255 other => out.push(other),
256 }
257 }
258 out.push('\'');
259 }
260
261 fn into_encoded(self) -> Result<String> {
264 match self {
265 Self::Text(value) => match Self::encode_text(&value) {
266 Cow::Borrowed(_) => Ok(value),
267 Cow::Owned(escaped) => Ok(escaped),
268 },
269 Self::Raw(value) => Ok(value),
270 other => Ok(other.encode()?.into_owned()),
271 }
272 }
273}
274
275pub(crate) struct EncodedParams {
284 _name_bufs: Vec<Vec<u8>>,
285 _value_bufs: Vec<Vec<u8>>,
286 name_ptrs: Vec<*const c_char>,
287 value_ptrs: Vec<*const c_char>,
288 name_lens: Vec<usize>,
289 value_lens: Vec<usize>,
290}
291
292impl EncodedParams {
293 pub(crate) fn encode(params: impl Into<QueryParams>) -> Result<Self> {
294 let params = params.into().into_iter();
295 let n = params.len();
296 let mut name_bufs = Vec::with_capacity(n);
297 let mut value_bufs = Vec::with_capacity(n);
298
299 for (name, param) in params {
302 name_bufs.push(name.into_bytes());
303 value_bufs.push(param.into_encoded()?.into_bytes());
304 }
305
306 let name_lens = name_bufs.iter().map(Vec::len).collect();
307 let value_lens = value_bufs.iter().map(Vec::len).collect();
308 let name_ptrs = name_bufs
309 .iter()
310 .map(|b| b.as_ptr() as *const c_char)
311 .collect();
312 let value_ptrs = value_bufs
313 .iter()
314 .map(|b| b.as_ptr() as *const c_char)
315 .collect();
316
317 Ok(Self {
318 _name_bufs: name_bufs,
319 _value_bufs: value_bufs,
320 name_ptrs,
321 value_ptrs,
322 name_lens,
323 value_lens,
324 })
325 }
326
327 pub(crate) fn len(&self) -> usize {
328 self.name_ptrs.len()
329 }
330
331 pub(crate) fn names_ptr(&self) -> *const *const c_char {
333 if self.name_ptrs.is_empty() {
334 std::ptr::null()
335 } else {
336 self.name_ptrs.as_ptr()
337 }
338 }
339
340 pub(crate) fn values_ptr(&self) -> *const *const c_char {
342 if self.value_ptrs.is_empty() {
343 std::ptr::null()
344 } else {
345 self.value_ptrs.as_ptr()
346 }
347 }
348
349 pub(crate) fn name_lens_ptr(&self) -> *const usize {
351 if self.name_lens.is_empty() {
352 std::ptr::null()
353 } else {
354 self.name_lens.as_ptr()
355 }
356 }
357
358 pub(crate) fn value_lens_ptr(&self) -> *const usize {
360 if self.value_lens.is_empty() {
361 std::ptr::null()
362 } else {
363 self.value_lens.as_ptr()
364 }
365 }
366}
367
368impl From<bool> for QueryParam {
369 fn from(value: bool) -> Self {
370 Self::Bool(value)
371 }
372}
373
374impl From<i8> for QueryParam {
375 fn from(value: i8) -> Self {
376 Self::Int64(i64::from(value))
377 }
378}
379
380impl From<i16> for QueryParam {
381 fn from(value: i16) -> Self {
382 Self::Int64(i64::from(value))
383 }
384}
385
386impl From<i32> for QueryParam {
387 fn from(value: i32) -> Self {
388 Self::Int64(i64::from(value))
389 }
390}
391
392impl From<i64> for QueryParam {
393 fn from(value: i64) -> Self {
394 Self::Int64(value)
395 }
396}
397
398impl From<u8> for QueryParam {
399 fn from(value: u8) -> Self {
400 Self::UInt64(u64::from(value))
401 }
402}
403
404impl From<u16> for QueryParam {
405 fn from(value: u16) -> Self {
406 Self::UInt64(u64::from(value))
407 }
408}
409
410impl From<u32> for QueryParam {
411 fn from(value: u32) -> Self {
412 Self::UInt64(u64::from(value))
413 }
414}
415
416impl From<u64> for QueryParam {
417 fn from(value: u64) -> Self {
418 Self::UInt64(value)
419 }
420}
421
422impl From<f32> for QueryParam {
423 fn from(value: f32) -> Self {
424 Self::Float64(f64::from(value))
425 }
426}
427
428impl From<f64> for QueryParam {
429 fn from(value: f64) -> Self {
430 Self::Float64(value)
431 }
432}
433
434impl From<String> for QueryParam {
435 fn from(value: String) -> Self {
436 Self::Text(value)
437 }
438}
439
440impl From<&str> for QueryParam {
441 fn from(value: &str) -> Self {
442 Self::Text(value.to_owned())
443 }
444}
445
446impl From<&QueryParam> for QueryParam {
447 fn from(value: &QueryParam) -> Self {
448 value.clone()
449 }
450}
451
452impl<T> From<Option<T>> for QueryParam
453where
454 T: Into<QueryParam>,
455{
456 fn from(value: Option<T>) -> Self {
457 match value {
458 None => Self::Null,
459 Some(value) => value.into(),
460 }
461 }
462}
463
464impl<T> From<Vec<T>> for QueryParam
465where
466 T: Into<QueryParam>,
467{
468 fn from(values: Vec<T>) -> Self {
469 Self::Array(values.into_iter().map(Into::into).collect())
470 }
471}
472
473impl<T> From<&[T]> for QueryParam
474where
475 T: Into<QueryParam> + Clone,
476{
477 fn from(values: &[T]) -> Self {
478 Self::from(values.to_vec())
479 }
480}
481
482#[cfg(test)]
483mod tests {
484
485 #[test]
486 fn plain_text_and_raw_values_are_moved_not_copied() -> Result<()> {
487 let text = String::from("no escaping needed here");
488 let ptr = text.as_ptr();
489 let encoded = QueryParam::Text(text).into_encoded()?;
490 assert_eq!(encoded.as_ptr(), ptr);
491
492 let raw = String::from("(7, 'x')");
493 let ptr = raw.as_ptr();
494 let encoded = QueryParam::Raw(raw).into_encoded()?;
495 assert_eq!(encoded.as_ptr(), ptr);
496
497 assert_eq!(QueryParam::Text("a\tb".into()).into_encoded()?, r"a\tb");
499 Ok(())
500 }
501
502 use super::*;
503
504 #[test]
505 fn encode_root_covers_every_variant() -> Result<()> {
506 assert_eq!(QueryParam::Null.encode()?, "\\N");
507 assert_eq!(QueryParam::Bool(true).encode()?, "true");
508 assert_eq!(QueryParam::Bool(false).encode()?, "false");
509 assert_eq!(QueryParam::Int64(-42).encode()?, "-42");
510 assert_eq!(QueryParam::UInt64(42).encode()?, "42");
511 assert_eq!(QueryParam::Float64(1.5).encode()?, "1.5");
512 assert_eq!(QueryParam::Text(String::new()).encode()?, "");
513 assert_eq!(QueryParam::Text("hello".into()).encode()?, "hello");
514 assert_eq!(QueryParam::Text("it's".into()).encode()?, "it's");
515 assert_eq!(QueryParam::Text(r"a\b".into()).encode()?, r"a\\b");
516 assert_eq!(QueryParam::raw("").encode()?, "");
517 assert_eq!(QueryParam::raw("(7,'x')").encode()?, "(7,'x')");
518 assert_eq!(QueryParam::raw("[1, 2, 3]").encode()?, "[1, 2, 3]");
519 assert_eq!(QueryParam::Array(vec![]).encode()?, "[]");
520 assert_eq!(
521 QueryParam::Array(vec![QueryParam::Int64(1), QueryParam::Int64(2)]).encode()?,
522 "[1, 2]"
523 );
524 Ok(())
525 }
526
527 #[test]
528 fn encode_text_escapes_sequences_so_chdb_sees_a_literal() -> Result<()> {
529 assert_eq!(QueryParam::Text(r"C:\temp".into()).encode()?, r"C:\\temp");
530 assert_eq!(QueryParam::Text(r"\".into()).encode()?, r"\\");
531 assert_eq!(QueryParam::Text(r"\\".into()).encode()?, r"\\\\");
532 assert_eq!(QueryParam::Text("a\tb".into()).encode()?, r"a\tb");
533 assert_eq!(QueryParam::Text("a\nb".into()).encode()?, r"a\nb");
534 assert_eq!(QueryParam::Text("it's".into()).encode()?, "it's");
535 assert_eq!(QueryParam::Text("a\rb".into()).encode()?, "a\rb");
536 assert_eq!(QueryParam::Text("a\u{08}b".into()).encode()?, "a\u{08}b");
537 assert_eq!(QueryParam::Text("a\u{0c}b".into()).encode()?, "a\u{0c}b");
538 assert_eq!(QueryParam::Text("a\0b".into()).encode()?, "a\0b");
539 assert_eq!(QueryParam::Text("hello".into()).encode()?, "hello");
540 Ok(())
541 }
542
543 #[test]
544 fn encode_raw_passes_escape_sequences_through_unchanged() -> Result<()> {
545 assert_eq!(QueryParam::raw(r"C:\temp").encode()?, r"C:\temp");
546 assert_eq!(QueryParam::raw("a\tb").encode()?, "a\tb");
547 assert_eq!(QueryParam::raw(r"it\'s").encode()?, r"it\'s");
548 Ok(())
549 }
550
551 #[test]
552 fn encode_nested_covers_every_variant_via_array() -> Result<()> {
553 assert_eq!(
554 QueryParam::Array(vec![QueryParam::Null]).encode()?,
555 "[NULL]"
556 );
557 assert_eq!(
558 QueryParam::Array(vec![QueryParam::Bool(true), QueryParam::Bool(false)]).encode()?,
559 "[true, false]"
560 );
561 assert_eq!(
562 QueryParam::Array(vec![QueryParam::Int64(-1), QueryParam::UInt64(2)]).encode()?,
563 "[-1, 2]"
564 );
565 assert_eq!(
566 QueryParam::Array(vec![QueryParam::Float64(1.5)]).encode()?,
567 "[1.5]"
568 );
569 assert_eq!(
570 QueryParam::Array(vec![QueryParam::Text(String::new())]).encode()?,
571 "['']"
572 );
573 assert_eq!(
574 QueryParam::Array(vec![QueryParam::Text("hello".into())]).encode()?,
575 "['hello']"
576 );
577 assert_eq!(
578 QueryParam::Array(vec![QueryParam::raw("(7,'x')")]).encode()?,
579 "[(7,'x')]"
580 );
581 assert_eq!(
582 QueryParam::Array(vec![QueryParam::Array(vec![
583 QueryParam::Int64(1),
584 QueryParam::Int64(2),
585 ])])
586 .encode()?,
587 "[[1, 2]]"
588 );
589 Ok(())
590 }
591
592 #[test]
593 fn encode_nested_escapes_quotes_and_backslashes_in_text() -> Result<()> {
594 assert_eq!(
595 QueryParam::Array(vec![QueryParam::Text("'".into())]).encode()?,
596 r"['\'']"
597 );
598 assert_eq!(
599 QueryParam::Array(vec![QueryParam::Text(r"\".into())]).encode()?,
600 r"['\\']"
601 );
602 assert_eq!(
603 QueryParam::Array(vec![QueryParam::Text("it's".into())]).encode()?,
604 r"['it\'s']"
605 );
606 assert_eq!(
607 QueryParam::Array(vec![QueryParam::Text(r"a\b".into())]).encode()?,
608 r"['a\\b']"
609 );
610 assert_eq!(
611 QueryParam::Array(vec![QueryParam::Text(r"'\".into())]).encode()?,
612 r"['\'\\']"
613 );
614 assert_eq!(
615 QueryParam::Array(vec![QueryParam::Text(r"C:\temp".into())]).encode()?,
616 r"['C:\\temp']"
617 );
618 assert_eq!(
619 QueryParam::Array(vec![QueryParam::Text("a\tb".into())]).encode()?,
620 r"['a\tb']"
621 );
622 assert_eq!(
623 QueryParam::Array(vec![QueryParam::Text("a\nb".into())]).encode()?,
624 r"['a\nb']"
625 );
626 assert_eq!(
627 QueryParam::Array(vec![
628 QueryParam::Text("a".into()),
629 QueryParam::Text("b".into()),
630 ])
631 .encode()?,
632 "['a', 'b']"
633 );
634 Ok(())
635 }
636
637 #[test]
638 fn encode_array_mixed_and_nested_shapes() -> Result<()> {
639 assert_eq!(
640 QueryParam::Array(vec![
641 QueryParam::Int64(1),
642 QueryParam::Null,
643 QueryParam::Text("x".into()),
644 QueryParam::Bool(true),
645 ])
646 .encode()?,
647 "[1, NULL, 'x', true]"
648 );
649 assert_eq!(
650 QueryParam::Array(vec![
651 QueryParam::Array(vec![QueryParam::Int64(1), QueryParam::Int64(2)]),
652 QueryParam::Array(vec![QueryParam::Int64(3), QueryParam::Int64(4)]),
653 ])
654 .encode()?,
655 "[[1, 2], [3, 4]]"
656 );
657 assert_eq!(
658 QueryParam::Array(vec![QueryParam::Array(vec![QueryParam::Text(
659 "it's".into()
660 )])])
661 .encode()?,
662 r"[['it\'s']]"
663 );
664 Ok(())
665 }
666
667 #[test]
668 fn from_option_none_encodes_as_root_null() -> Result<()> {
669 let value: Option<i64> = None;
670 assert_eq!(QueryParam::from(value).encode()?, "\\N");
671 Ok(())
672 }
673
674 #[test]
675 fn from_vec_and_slice_encode_as_arrays() -> Result<()> {
676 assert_eq!(QueryParam::from(Vec::<u64>::new()).encode()?, "[]");
677 assert_eq!(QueryParam::from(vec![1_u64, 2, 3]).encode()?, "[1, 2, 3]");
678 assert_eq!(QueryParam::from(vec![1_i32, 2, 3]).encode()?, "[1, 2, 3]");
679 assert_eq!(
680 QueryParam::from([4_i64, 5, 6].as_slice()).encode()?,
681 "[4, 5, 6]"
682 );
683 assert_eq!(
684 QueryParam::from(vec!["a".to_owned(), "b".to_owned()]).encode()?,
685 "['a', 'b']"
686 );
687 let values: Vec<Option<i64>> = vec![Some(1), None, Some(3)];
688 assert_eq!(QueryParam::from(values).encode()?, "[1, NULL, 3]");
689 assert_eq!(
690 QueryParam::from(vec![vec![1_u64, 2], vec![3, 4]]).encode()?,
691 "[[1, 2], [3, 4]]"
692 );
693 Ok(())
694 }
695
696 #[test]
697 fn from_vec_builds_array_variant() {
698 assert_eq!(
699 QueryParam::from(vec![1_i64, 2]),
700 QueryParam::Array(vec![QueryParam::Int64(1), QueryParam::Int64(2)])
701 );
702 }
703
704 #[test]
705 fn query_params_builder_collects_mixed_types() {
706 let params = QueryParams::new().bind("x", 5_u64).bind("label", "ok");
707 let collected: Vec<_> = params.into_iter().collect();
708 assert_eq!(collected.len(), 2);
709 assert_eq!(collected[0].0, "x");
710 assert_eq!(collected[0].1, QueryParam::UInt64(5));
711 assert_eq!(collected[1].0, "label");
712 assert_eq!(collected[1].1, QueryParam::Text("ok".into()));
713 }
714
715 #[test]
716 fn encoded_params_empty_exposes_null_name_and_value_ptrs() -> Result<()> {
717 let encoded = EncodedParams::encode(QueryParams::new())?;
718
719 assert_eq!(encoded.len(), 0);
720 assert!(encoded.names_ptr().is_null());
721 assert!(encoded.values_ptr().is_null());
722 assert!(encoded.name_lens_ptr().is_null());
723 assert!(encoded.value_lens_ptr().is_null());
724 Ok(())
725 }
726
727 #[test]
728 fn encoded_params_exposes_parallel_name_and_value_ptrs() -> Result<()> {
729 let encoded = EncodedParams::encode([
730 ("x", QueryParam::from(5_u64)),
731 ("label", QueryParam::from("ok")),
732 ])?;
733
734 assert_eq!(encoded.len(), 2);
735 assert!(!encoded.names_ptr().is_null());
736 assert!(!encoded.values_ptr().is_null());
737 assert!(!encoded.name_lens_ptr().is_null());
738 assert!(!encoded.value_lens_ptr().is_null());
739
740 unsafe {
741 let names = encoded.names_ptr();
742 let name_lens = encoded.name_lens_ptr();
743 let values = encoded.values_ptr();
744 let value_lens = encoded.value_lens_ptr();
745
746 assert_eq!(*name_lens, 1);
747 assert_eq!(
748 std::slice::from_raw_parts(*names as *const u8, *name_lens),
749 b"x"
750 );
751 assert_eq!(*name_lens.add(1), 5);
752 assert_eq!(
753 std::slice::from_raw_parts(*names.add(1) as *const u8, *name_lens.add(1)),
754 b"label"
755 );
756
757 assert_eq!(*value_lens, 1);
758 assert_eq!(
759 std::slice::from_raw_parts(*values as *const u8, *value_lens),
760 b"5"
761 );
762 assert_eq!(*value_lens.add(1), 2);
763 assert_eq!(
764 std::slice::from_raw_parts(*values.add(1) as *const u8, *value_lens.add(1)),
765 b"ok"
766 );
767 }
768 Ok(())
769 }
770}