Skip to main content

pgdo/cluster/
config.rs

1use std::{borrow::Cow, fmt, str::FromStr};
2
3use postgres_protocol::escape::{escape_identifier, escape_literal};
4
5use super::{client::Row, Cluster, ClusterError};
6
7trait AsSql {
8    fn as_sql(&self) -> Cow<'_, str>;
9}
10
11/// Error understanding a configuration setting.
12#[derive(thiserror::Error, Debug)]
13pub enum ConfigError {
14    #[error("could not understand setting: {0}")]
15    SettingError(String),
16}
17
18/// Reload configuration using `pg_reload_conf`. Equivalent to `SIGHUP` or
19/// `pg_ctl reload`.
20pub fn reload(cluster: &Cluster) -> Result<(), ClusterError> {
21    cluster.connect(None)?.execute("SELECT pg_reload_conf()")?;
22    Ok(())
23}
24
25pub enum AlterSystem<'a> {
26    Set(&'a Parameter<'a>, &'a Value),
27    Reset(&'a Parameter<'a>),
28    ResetAll,
29}
30
31impl AlterSystem<'_> {
32    /// Alter the system. Changes made by `ALTER SYSTEM` may require a reload or
33    /// even a full restart to take effect.
34    pub fn apply(&self, cluster: &Cluster) -> Result<(), ClusterError> {
35        cluster.connect(None)?.execute(&self.as_sql())?;
36        Ok(())
37    }
38}
39
40impl AsSql for AlterSystem<'_> {
41    /// Return the SQL to apply this change.
42    fn as_sql(&self) -> Cow<'_, str> {
43        use AlterSystem::*;
44        match self {
45            Set(p, v) => format!("ALTER SYSTEM SET {} TO {}", p.as_sql(), v.as_sql()).into(),
46            Reset(p) => format!("ALTER SYSTEM RESET {}", p.as_sql()).into(),
47            ResetAll => "ALTER SYSTEM RESET ALL".into(),
48        }
49    }
50}
51
52/// A setting as defined in `pg_catalog.pg_settings`.
53///
54/// This is fairly stringly-typed and mostly informational. For getting and
55/// setting values, [`Parameter`] and [`Value`] may be more convenient.
56///
57/// See the [documentation for
58/// `pg_settings`](https://www.postgresql.org/docs/current/view-pg-settings.html).
59#[derive(Debug, Clone)]
60pub struct Setting {
61    pub name: String,
62    pub setting: String,
63    pub unit: Option<String>,
64    pub category: String,
65    pub short_desc: String,
66    pub extra_desc: Option<String>,
67    pub context: String,
68    pub vartype: String,
69    pub source: String,
70    pub min_val: Option<String>,
71    pub max_val: Option<String>,
72    pub enumvals: Option<Vec<String>>,
73    pub boot_val: Option<String>,
74    pub reset_val: Option<String>,
75    pub sourcefile: Option<String>,
76    pub sourceline: Option<i32>,
77    pub pending_restart: bool,
78}
79
80/// Separates elements of `enumvals` in [`SETTINGS_QUERY`]. pgdo's client
81/// receives all values as text; joining with a control character avoids having
82/// to parse PostgreSQL's array syntax.
83const ENUMVALS_SEPARATOR: char = '\x1f';
84
85/// Query for [`Setting`]s. Columns must be in the order that
86/// [`Setting::try_from`] expects.
87const SETTINGS_QUERY: &str = r"
88    SELECT
89        name,
90        setting,
91        unit,
92        category,
93        short_desc,
94        extra_desc,
95        context,
96        vartype,
97        source,
98        min_val,
99        max_val,
100        array_to_string(enumvals, chr(31)),
101        boot_val,
102        reset_val,
103        sourcefile,
104        sourceline,
105        pending_restart
106    FROM
107        pg_catalog.pg_settings
108";
109
110impl TryFrom<&Row> for Setting {
111    type Error = ConfigError;
112
113    fn try_from(row: &Row) -> Result<Self, Self::Error> {
114        let optional = |column: usize| row.get(column).map(str::to_owned);
115        let required = |column: usize| {
116            optional(column).ok_or_else(|| {
117                ConfigError::SettingError(format!("unexpected NULL in column {column}: {row:?}"))
118            })
119        };
120        Ok(Self {
121            name: required(0)?,
122            setting: required(1)?,
123            unit: optional(2),
124            category: required(3)?,
125            short_desc: required(4)?,
126            extra_desc: optional(5),
127            context: required(6)?,
128            vartype: required(7)?,
129            source: required(8)?,
130            min_val: optional(9),
131            max_val: optional(10),
132            enumvals: row.get(11).map(|enumvals| {
133                enumvals
134                    .split(ENUMVALS_SEPARATOR)
135                    .filter(|value| !value.is_empty())
136                    .map(str::to_owned)
137                    .collect()
138            }),
139            boot_val: optional(12),
140            reset_val: optional(13),
141            sourcefile: optional(14),
142            sourceline: row
143                .get(15)
144                .map(|line| {
145                    line.parse().map_err(|_| {
146                        ConfigError::SettingError(format!("invalid sourceline: {row:?}"))
147                    })
148                })
149                .transpose()?,
150            pending_restart: match row.get(16) {
151                Some("t") => true,
152                Some("f") => false,
153                _ => Err(ConfigError::SettingError(format!(
154                    "invalid pending_restart: {row:?}"
155                )))?,
156            },
157        })
158    }
159}
160
161impl Setting {
162    pub fn list(cluster: &Cluster) -> Result<Vec<Self>, ClusterError> {
163        let rows = cluster.connect(None)?.query(SETTINGS_QUERY)?;
164        Ok(rows.iter().map(Self::try_from).collect::<Result<_, _>>()?)
165    }
166
167    pub fn get<N: AsRef<str>>(name: N, cluster: &Cluster) -> Result<Option<Self>, ClusterError> {
168        let query = format!(
169            "{SETTINGS_QUERY} WHERE name = {}",
170            escape_literal(name.as_ref())
171        );
172        let rows = cluster.connect(None)?.query(&query)?;
173        Ok(rows.first().map(Self::try_from).transpose()?)
174    }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
178pub struct Parameter<'a>(pub &'a str);
179
180impl Parameter<'_> {
181    /// Get the current [`Value`] for this parameter.
182    ///
183    /// If you want the full/raw [`Setting`], use [`Setting::get`] instead.
184    pub fn get(&self, cluster: &Cluster) -> Result<Option<Value>, ClusterError> {
185        Ok(Setting::get(self.0, cluster)?
186            .map(|setting| Value::try_from(&setting).map_err(ConfigError::SettingError))
187            .transpose()?)
188    }
189
190    /// Set the current value for this parameter.
191    pub fn set<V: Into<Value>>(&self, cluster: &Cluster, value: V) -> Result<(), ClusterError> {
192        let value = value.into();
193        AlterSystem::Set(self, &value).apply(cluster)
194    }
195
196    /// Reset the value for this parameter.
197    pub fn reset(&self, cluster: &Cluster) -> Result<(), ClusterError> {
198        AlterSystem::Reset(self).apply(cluster)
199    }
200}
201
202impl AsSql for Parameter<'_> {
203    /// Return this parameter name escaped as an SQL identifier.
204    fn as_sql(&self) -> Cow<'_, str> {
205        escape_identifier(self.0).into()
206    }
207}
208
209impl fmt::Display for Parameter<'_> {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        write!(f, "{}", self.0)
212    }
213}
214
215impl AsRef<str> for Parameter<'_> {
216    fn as_ref(&self) -> &str {
217        self.0
218    }
219}
220
221impl<'a> From<&'a str> for Parameter<'a> {
222    fn from(name: &'a str) -> Self {
223        Self(name)
224    }
225}
226
227impl<'a> From<&'a Setting> for Parameter<'a> {
228    fn from(setting: &'a Setting) -> Self {
229        Self(&setting.name)
230    }
231}
232
233#[derive(Debug, PartialEq)]
234pub enum Value {
235    Boolean(bool),
236    String(String), // Or enumerated.
237    Number(String),
238    Memory(String, MemoryUnit),
239    Time(String, TimeUnit),
240}
241
242impl AsSql for Value {
243    /// Return this parameter value escaped as an SQL literal.
244    fn as_sql(&self) -> Cow<'_, str> {
245        match self {
246            Value::Boolean(true) => "true".into(),
247            Value::Boolean(false) => "false".into(),
248            Value::String(value) => escape_literal(value).into(),
249            Value::Number(value) => value.into(),
250            Value::Memory(value, unit) => escape_literal(&format!("{value}{unit}")).into(),
251            Value::Time(value, unit) => escape_literal(&format!("{value}{unit}")).into(),
252        }
253    }
254}
255
256impl fmt::Display for Value {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        match self {
259            Value::Boolean(value) => write!(f, "{value}"),
260            Value::String(value) => write!(f, "{value}"),
261            Value::Number(value) => write!(f, "{value}"),
262            Value::Memory(value, unit) => write!(f, "{value}{unit}"),
263            Value::Time(value, unit) => write!(f, "{value}{unit}"),
264        }
265    }
266}
267
268impl From<bool> for Value {
269    fn from(value: bool) -> Self {
270        Value::Boolean(value)
271    }
272}
273
274impl From<&str> for Value {
275    fn from(value: &str) -> Self {
276        Value::String(value.to_owned())
277    }
278}
279
280impl From<String> for Value {
281    fn from(value: String) -> Self {
282        Value::String(value)
283    }
284}
285
286impl From<&String> for Value {
287    fn from(value: &String) -> Self {
288        Value::String(value.clone())
289    }
290}
291
292macro_rules! value_number_from {
293    ($($from_type:ty),*) => {
294        $(
295            impl From<$from_type> for Value {
296                fn from(number: $from_type) -> Self {
297                    Value::Number(number.to_string())
298                }
299            }
300        )*
301    }
302}
303
304value_number_from!(i8, i16, i32, i64, i128);
305value_number_from!(u8, u16, u32, u64, u128);
306value_number_from!(f32, f64);
307value_number_from!(usize, isize);
308
309macro_rules! value_memory_from {
310    ($($from_type:ty),*) => {
311        $(
312            impl From<($from_type, MemoryUnit)> for Value {
313                fn from((number, unit): ($from_type, MemoryUnit)) -> Self {
314                    Value::Memory(number.to_string(), unit)
315                }
316            }
317        )*
318    }
319}
320
321value_memory_from!(i8, i16, i32, i64, i128);
322value_memory_from!(u8, u16, u32, u64, u128);
323value_memory_from!(f32, f64);
324value_memory_from!(usize, isize);
325
326macro_rules! value_time_from {
327    ($($from_type:ty),*) => {
328        $(
329            impl From<($from_type, TimeUnit)> for Value {
330                fn from((number, unit): ($from_type, TimeUnit)) -> Self {
331                    Value::Time(number.to_string(), unit)
332                }
333            }
334        )*
335    }
336}
337
338value_time_from!(i8, i16, i32, i64, i128);
339value_time_from!(u8, u16, u32, u64, u128);
340value_time_from!(f32, f64);
341value_time_from!(usize, isize);
342
343impl TryFrom<&Setting> for Value {
344    type Error = String;
345
346    fn try_from(setting: &Setting) -> Result<Self, Self::Error> {
347        Ok(match setting.vartype.as_ref() {
348            "bool" => match setting.setting.as_ref() {
349                "on" | "true" | "tru" | "tr" | "t" => Self::Boolean(true),
350                "yes" | "ye" | "y" | "1" => Self::Boolean(true),
351                "off" | "of" | "false" | "fals" | "fal" | "fa" | "f" => Self::Boolean(false),
352                "no" | "n" | "0" => Self::Boolean(false),
353                _ => return Err(format!("invalid boolean value: {setting:?}")),
354            },
355            "integer" | "real" => match setting.unit.as_deref() {
356                None => Self::Number(setting.setting.clone()),
357                Some("8kB" | "16MB") => Self::Number(setting.setting.clone()), // Special cases 🤷
358                Some(unit) => {
359                    if let Ok(unit) = unit.parse::<MemoryUnit>() {
360                        Self::Memory(setting.setting.clone(), unit)
361                    } else if let Ok(unit) = unit.parse::<TimeUnit>() {
362                        Self::Time(setting.setting.clone(), unit)
363                    } else {
364                        return Err(format!("invalid numeric value: {setting:?}"));
365                    }
366                }
367            },
368            "string" => Self::String(setting.setting.clone()),
369            "enum" => Self::String(setting.setting.clone()),
370            _ => return Err(format!("unrecognised value type: {setting:?}")),
371        })
372    }
373}
374
375/// Memory units recognised in PostgreSQL parameter values.
376/// <https://www.postgresql.org/docs/16/config-setting.html#CONFIG-SETTING-NAMES-VALUES>
377#[derive(Debug, Clone, Copy, PartialEq)]
378pub enum MemoryUnit {
379    Bytes,
380    Kibibytes,
381    Mebibytes,
382    Gibibytes,
383    Tebibytes,
384}
385
386impl fmt::Display for MemoryUnit {
387    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388        match self {
389            MemoryUnit::Bytes => write!(f, "B"),
390            MemoryUnit::Kibibytes => write!(f, "kB"),
391            MemoryUnit::Mebibytes => write!(f, "MB"),
392            MemoryUnit::Gibibytes => write!(f, "GB"),
393            MemoryUnit::Tebibytes => write!(f, "TB"),
394        }
395    }
396}
397
398impl FromStr for MemoryUnit {
399    type Err = String;
400
401    fn from_str(s: &str) -> Result<Self, Self::Err> {
402        match s {
403            "B" => Ok(MemoryUnit::Bytes),
404            "kB" => Ok(MemoryUnit::Kibibytes),
405            "MB" => Ok(MemoryUnit::Mebibytes),
406            "GB" => Ok(MemoryUnit::Gibibytes),
407            "TB" => Ok(MemoryUnit::Tebibytes),
408            _ => Err(format!("invalid memory unit: {s:?}")),
409        }
410    }
411}
412
413/// Time units recognised in PostgreSQL parameter values.
414/// <https://www.postgresql.org/docs/16/config-setting.html#CONFIG-SETTING-NAMES-VALUES>
415#[derive(Debug, Clone, Copy, PartialEq)]
416pub enum TimeUnit {
417    Microseconds,
418    Milliseconds,
419    Seconds,
420    Minutes,
421    Hours,
422    Days,
423}
424
425impl fmt::Display for TimeUnit {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        match self {
428            TimeUnit::Microseconds => write!(f, "us"),
429            TimeUnit::Milliseconds => write!(f, "ms"),
430            TimeUnit::Seconds => write!(f, "s"),
431            TimeUnit::Minutes => write!(f, "min"),
432            TimeUnit::Hours => write!(f, "h"),
433            TimeUnit::Days => write!(f, "d"),
434        }
435    }
436}
437
438impl FromStr for TimeUnit {
439    type Err = String;
440
441    fn from_str(s: &str) -> Result<Self, Self::Err> {
442        match s {
443            "us" => Ok(TimeUnit::Microseconds),
444            "ms" => Ok(TimeUnit::Milliseconds),
445            "s" => Ok(TimeUnit::Seconds),
446            "min" => Ok(TimeUnit::Minutes),
447            "h" => Ok(TimeUnit::Hours),
448            "d" => Ok(TimeUnit::Days),
449            _ => Err(format!("invalid time unit: {s:?}")),
450        }
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use pastey::paste;
457
458    use super::{
459        AsSql,
460        MemoryUnit::{self, *},
461        Parameter,
462        TimeUnit::{self, *},
463        Value,
464    };
465
466    #[test]
467    fn test_parameter_as_sql() {
468        assert_eq!(Parameter("foo").as_sql(), "\"foo\"");
469        assert_eq!(Parameter("foo \\bar").as_sql(), "\"foo \\bar\"");
470        assert_eq!(Parameter("foo\"bar").as_sql(), "\"foo\"\"bar\"");
471    }
472
473    #[test]
474    fn test_value_as_sql_bool() {
475        assert_eq!(Value::Boolean(false).as_sql(), "false");
476        assert_eq!(Value::Boolean(true).as_sql(), "true");
477    }
478
479    #[test]
480    fn test_value_as_sql_string() {
481        assert_eq!(Value::from("foo").as_sql(), "'foo'");
482        assert_eq!(Value::from("foo \\bar").as_sql(), " E'foo \\\\bar'");
483        assert_eq!(Value::from("foo'\"'bar").as_sql(), "'foo''\"''bar'");
484    }
485
486    #[test]
487    fn test_value_as_sql_number() {
488        // Numbers are represented as strings, and displayed verbatim, with no
489        // escaping. Not ideal. An alternative would be to have signed/unsigned
490        // integers (as i128/u128) and floating points (as f64) separately. But
491        // PostgreSQL also has arbitrary precision numbers. For now, we'll live
492        // with this.
493        assert_eq!(Value::Number("123".into()).as_sql(), "123");
494        assert_eq!(Value::Number("123.456".into()).as_sql(), "123.456");
495    }
496
497    #[test]
498    fn test_value_as_sql_memory() {
499        assert_eq!(
500            Value::Memory("123.4".into(), Gibibytes).as_sql(),
501            "'123.4GB'",
502        );
503    }
504
505    #[test]
506    fn test_value_as_sql_time() {
507        assert_eq!(Value::Time("123.4".into(), Hours).as_sql(), "'123.4h'",);
508    }
509
510    macro_rules! test_value_number_from {
511        ($($from_type:ty),*) => {
512            $(
513                paste! {
514                    #[test]
515                    #[allow(clippy::cast_precision_loss, clippy::cast_lossless)]
516                    fn [< test_value_number_from_ $from_type >]() {
517                        assert_eq!(Value::from(42 as $from_type), Value::Number("42".into()));
518                    }
519                }
520            )*
521        }
522    }
523
524    test_value_number_from!(i8, i16, i32, i64, i128);
525    test_value_number_from!(u8, u16, u32, u64, u128);
526    test_value_number_from!(f32, f64);
527    test_value_number_from!(usize, isize);
528
529    #[test]
530    fn test_memory_unit_roundtrip() {
531        let units = &[Bytes, Kibibytes, Mebibytes, Gibibytes, Tebibytes];
532        for unit in units {
533            assert_eq!(format!("{unit}").parse::<MemoryUnit>(), Ok(*unit));
534        }
535    }
536
537    #[test]
538    fn test_time_unit_roundtrip() {
539        let units = &[Microseconds, Milliseconds, Seconds, Minutes, Hours, Days];
540        for unit in units {
541            assert_eq!(format!("{unit}").parse::<TimeUnit>(), Ok(*unit));
542        }
543    }
544}