Skip to main content

chdb_rust/
arg.rs

1//! Query argument definitions for chDB.
2//!
3//! This module provides types for specifying query arguments such as output format,
4//! log level, and custom command-line arguments.
5
6use std::borrow::Cow;
7use std::fmt::Display;
8
9use crate::format::OutputFormat;
10use crate::log_level::LogLevel;
11
12/// Query arguments that can be passed when executing queries.
13///
14/// `Arg` represents various command-line arguments that can be used to configure
15/// query execution. Most commonly, you'll use `OutputFormat` to specify the
16/// desired output format.
17///
18/// # Examples
19///
20/// ```no_run
21/// use chdb_rust::arg::Arg;
22/// use chdb_rust::format::OutputFormat;
23/// use chdb_rust::log_level::LogLevel;
24///
25/// // Specify output format
26/// let args = &[Arg::OutputFormat(OutputFormat::JSONEachRow)];
27///
28/// // Specify log level
29/// let args = &[Arg::LogLevel(LogLevel::Debug)];
30///
31/// // Use custom arguments
32/// let args = &[Arg::Custom("path".into(), Some("/tmp/db".into()))];
33/// ```
34#[derive(Debug)]
35pub enum Arg<'a> {
36    /// `--config-file=<value>`
37    ///
38    /// Can be used to specify a custom configuration
39    /// file for the session, allowing one to configure various aspects of the
40    /// session's behavior (e.g., SSL settings to use with the `remoteSecure`
41    /// function).
42    ///
43    /// An example SSL configuration file (`chdb_ssl.xml`) might look like this:
44    /// ```xml
45    /// <clickhouse>
46    ///   <openSSL>
47    ///     <client>
48    ///       <caConfig>path_to_server_ca_cert.pem</caConfig>
49    ///     </client>
50    ///   </openSSL>
51    /// </clickhouse>
52    /// ```
53    /// where `path_to_server_ca_cert.pem` is the path to the CA certificate
54    /// of the remote server.
55    ConfigFilePath(Cow<'a, str>),
56    /// `--log-level=<value>`
57    LogLevel(LogLevel),
58    /// `--output-format=<value>`
59    OutputFormat(OutputFormat),
60    /// --multiquery
61    /// Emitted as `-n` (short for `--multiquery`).
62    MultiQuery,
63    /// Custom argument.
64    ///
65    /// "--path=/tmp/chdb" translates into one of the following:
66    /// 1. Arg::Custom("path".to_string().into(), Some("/tmp/chdb".to_string().into())).
67    /// 2. Arg::Custom("path".into(), Some("/tmp/chdb".into())).
68    ///
69    /// "--multiline" translates into one of the following:
70    /// 1. Arg::Custom("multiline".to_string().into(), None).
71    /// 2. Arg::Custom("multiline".into(), None).
72    ///
73    /// Officially supported arguments can be found by running
74    /// `clickhouse-client --help` in the terminal.
75    Custom(Cow<'a, str>, Option<Cow<'a, str>>),
76}
77
78impl<'a> Arg<'a> {
79    /// Extract `OutputFormat` from an `Arg` if it is an `OutputFormat` variant.
80    ///
81    /// This is a helper method used internally to extract output format information
82    /// from query arguments.
83    pub(crate) fn as_output_format(&self) -> Option<OutputFormat> {
84        match self {
85            Self::OutputFormat(f) => Some(*f),
86            _ => None,
87        }
88    }
89}
90
91impl Display for Arg<'_> {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        match self {
94            Self::ConfigFilePath(v) => write!(f, "--config-file={v}"),
95            Self::LogLevel(v) => write!(f, "--log-level={}", v.as_str()),
96            Self::OutputFormat(v) => write!(f, "--output-format={}", v.as_str()),
97            Self::MultiQuery => write!(f, "-n"),
98            Self::Custom(k, v) => match v {
99                None => write!(f, "--{}", k.as_ref()),
100                Some(v) => write!(f, "--{k}={v}"),
101            },
102        }
103    }
104}
105
106/// Extract `OutputFormat` from a slice of `Arg`s.
107///
108/// This function searches through the provided arguments and returns the first
109/// `OutputFormat` found, or the default `TabSeparated` format if none is found.
110///
111/// # Arguments
112///
113/// * `args` - Optional slice of query arguments
114///
115/// # Returns
116///
117/// Returns the first `OutputFormat` found, or `OutputFormat::TabSeparated` as default.
118pub(crate) fn extract_output_format(args: Option<&[Arg]>, default: OutputFormat) -> OutputFormat {
119    args.and_then(|args| args.iter().find_map(|a| a.as_output_format()))
120        .unwrap_or(default)
121}
122
123#[cfg(test)]
124mod test {
125    use super::*;
126
127    #[test]
128    fn test_arg_display_config_file_path() {
129        assert_eq!(
130            Arg::ConfigFilePath(Cow::from("my.xml")).to_string(),
131            "--config-file=my.xml"
132        );
133    }
134
135    #[test]
136    fn test_arg_display_log_level() {
137        assert_eq!(
138            Arg::LogLevel(LogLevel::Trace).to_string(),
139            "--log-level=trace"
140        );
141        assert_eq!(
142            Arg::LogLevel(LogLevel::Debug).to_string(),
143            "--log-level=debug"
144        );
145        assert_eq!(
146            Arg::LogLevel(LogLevel::Info).to_string(),
147            "--log-level=information"
148        );
149        assert_eq!(
150            Arg::LogLevel(LogLevel::Warn).to_string(),
151            "--log-level=warning"
152        );
153        assert_eq!(
154            Arg::LogLevel(LogLevel::Error).to_string(),
155            "--log-level=error"
156        );
157    }
158
159    #[test]
160    fn test_arg_display_output_format() {
161        assert_eq!(
162            Arg::OutputFormat(OutputFormat::JSONEachRow).to_string(),
163            "--output-format=JSONEachRow"
164        );
165    }
166
167    #[test]
168    fn test_arg_display_multi_query() {
169        assert_eq!(Arg::MultiQuery.to_string(), "-n");
170    }
171
172    #[test]
173    fn test_arg_display_custom_key_only() {
174        assert_eq!(
175            Arg::Custom("multiline".into(), None).to_string(),
176            "--multiline"
177        );
178    }
179
180    #[test]
181    fn test_arg_display_custom_key_value() {
182        assert_eq!(
183            Arg::Custom("priority".into(), Some("1".into())).to_string(),
184            "--priority=1"
185        );
186    }
187}