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