Skip to main content

uqa_sql/semantics/parameters/
value.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Parameter values read and shown as `PostgreSQL`'s `parse_and_validate_value` and `ShowGUCOption` do. A setting is kept as the text `pg_settings.setting` reports: an integer in base units, `on` or `off`, the canonical name of an enumerated value, or the string itself.
8
9use super::definition::{EnumOption, ParameterDefinition, ParameterFlags, ParameterKind};
10use super::units::{parse_integer, show_integer_with_control};
11use crate::SQLError;
12use uqa_core::memory::{Produced, ProductionControl};
13
14/// The longest identifier, `NAMEDATALEN - 1` bytes, to which a `GUC_IS_NAME` string is truncated.
15const MAX_IDENTIFIER_BYTES: usize = 63;
16
17/// Read `raw` as a value of `definition` and return the setting it stands for, or the error `SET` reports for it.
18pub fn parse_setting(definition: &ParameterDefinition, raw: &str) -> Result<String, SQLError> {
19    parse_setting_with_context(
20        definition,
21        raw,
22        &definition.boot_setting(),
23        &definition.boot_setting(),
24    )
25}
26
27/// Read a setting with the session's current and reset values for partial assignments.
28pub fn parse_setting_with_context(
29    definition: &ParameterDefinition,
30    raw: &str,
31    current: &str,
32    reset: &str,
33) -> Result<String, SQLError> {
34    if definition.name == "DateStyle" {
35        return super::datestyle::parse_setting(definition, raw, current, reset);
36    }
37    if definition.name == "TimeZone" {
38        return super::timezone::parse_setting(definition, raw);
39    }
40    match definition.kind {
41        ParameterKind::Bool { .. } => parse_bool(raw)
42            .map(|value| if value { "on" } else { "off" }.to_string())
43            .ok_or_else(|| SQLError::Routine {
44                sqlstate: "22023".into(),
45                message: format!("parameter \"{}\" requires a Boolean value", definition.name),
46            }),
47        ParameterKind::Integer { min, max, unit, .. } => {
48            let value = parse_integer(raw, unit).map_err(|hint| SQLError::Diagnostic {
49                sqlstate: "22023".into(),
50                message: invalid_value_message(definition, raw),
51                detail: None,
52                hint: hint.map(str::to_string),
53            })?;
54            if value < min || value > max {
55                let unit = unit.map_or(String::new(), |unit| format!(" {}", unit.name()));
56                return Err(SQLError::Routine {
57                    sqlstate: "22023".into(),
58                    message: format!(
59                        "{value}{unit} is outside the valid range for parameter \"{}\" ({min}{unit} .. {max}{unit})",
60                        definition.name
61                    ),
62                });
63            }
64            Ok(value.to_string())
65        }
66        ParameterKind::Enum { options, .. } => options
67            .iter()
68            .find(|option| option.name.eq_ignore_ascii_case(raw))
69            .map(|option| enum_display(options, option.value).to_string())
70            .ok_or_else(|| SQLError::Diagnostic {
71                sqlstate: "22023".into(),
72                message: invalid_value_message(definition, raw),
73                detail: None,
74                hint: Some(format!(
75                    "Available values: {}.",
76                    listed_enum_values(options).join(", ")
77                )),
78            }),
79        ParameterKind::String { .. } => Ok(if definition.has_flag(ParameterFlags::IS_NAME) {
80            truncate_identifier(raw).to_string()
81        } else {
82            raw.to_string()
83        }),
84    }
85}
86
87/// The notice `PostgreSQL` raises before it truncates a `GUC_IS_NAME` string that is longer than an identifier.
88pub fn name_truncation_notice(definition: &ParameterDefinition, raw: &str) -> Option<String> {
89    let truncated = truncate_identifier(raw);
90    (matches!(definition.kind, ParameterKind::String { .. })
91        && definition.has_flag(ParameterFlags::IS_NAME)
92        && truncated.len() < raw.len())
93    .then(|| format!("identifier \"{raw}\" will be truncated to \"{truncated}\""))
94}
95
96/// `invalid value for parameter "name": "value"`, the message of a value that does not parse or that a check rejects.
97pub fn invalid_value_message(definition: &ParameterDefinition, raw: &str) -> String {
98    format!(
99        "invalid value for parameter \"{}\": \"{raw}\"",
100        definition.name
101    )
102}
103
104/// Show `setting` as `SHOW` and `current_setting` report it: an integer in the greatest unit that divides it.
105pub fn show_setting(definition: &ParameterDefinition, setting: &str) -> String {
106    show_setting_with_control(definition, setting, &ProductionControl::uncontrolled())
107        .expect("ordinary setting formatting")
108        .into_uncontrolled()
109        .expect("ordinary setting")
110}
111
112pub fn show_setting_with_control(
113    definition: &ParameterDefinition,
114    setting: &str,
115    control: &ProductionControl<'_>,
116) -> Result<Produced<String>, SQLError> {
117    if let ParameterKind::Integer { unit, .. } = definition.kind {
118        if let Ok(value) = setting.parse::<i64>() {
119            return show_integer_with_control(value, unit, control);
120        }
121    }
122    Ok(control.copy_text(setting)?)
123}
124
125/// The names of an enumerated parameter's values that `pg_settings.enumvals` lists.
126pub fn listed_enum_values(options: &[EnumOption]) -> Vec<&'static str> {
127    options
128        .iter()
129        .filter(|option| !option.hidden)
130        .map(|option| option.name)
131        .collect()
132}
133
134/// The name an enumerated value displays as: the first option with that value.
135pub(super) fn enum_display(options: &[EnumOption], value: u8) -> &'static str {
136    options
137        .iter()
138        .find(|option| option.value == value)
139        .map(|option| option.name)
140        .expect("enumerated value has a name")
141}
142
143/// `parse_bool`: a prefix of `true`, `false`, `yes` or `no`, at least two letters of `on` or `off`, or `1` or `0`, in any case.
144fn parse_bool(raw: &str) -> Option<bool> {
145    let lower = raw.to_ascii_lowercase();
146    let prefix_of = |word: &str| !lower.is_empty() && word.starts_with(lower.as_str());
147    match lower.as_bytes().first()? {
148        b't' if prefix_of("true") => Some(true),
149        b'f' if prefix_of("false") => Some(false),
150        b'y' if prefix_of("yes") => Some(true),
151        b'n' if prefix_of("no") => Some(false),
152        b'o' if lower.len() >= 2 && prefix_of("on") => Some(true),
153        b'o' if lower.len() >= 2 && prefix_of("off") => Some(false),
154        b'1' if lower.len() == 1 => Some(true),
155        b'0' if lower.len() == 1 => Some(false),
156        _ => None,
157    }
158}
159
160/// `truncate_identifier`: the longest prefix of at most `NAMEDATALEN - 1` bytes that ends on a character boundary.
161fn truncate_identifier(raw: &str) -> &str {
162    if raw.len() <= MAX_IDENTIFIER_BYTES {
163        return raw;
164    }
165    let mut end = MAX_IDENTIFIER_BYTES;
166    while !raw.is_char_boundary(end) {
167        end -= 1;
168    }
169    &raw[..end]
170}
171
172#[cfg(test)]
173mod tests;