uqa_sql/plpgsql/
runtime_diagnostics.rs1use crate::{expr::cast_value, plpgsql::condition_sqlstates, SQLError, SQLResult};
10use uqa_core::Value;
11
12pub fn unassigned_record(name: &str) -> SQLError {
13 SQLError::Diagnostic {
14 sqlstate: "55000".into(),
15 message: format!("record \"{name}\" is not assigned yet"),
16 detail: Some("The tuple structure of a not-yet-assigned record is indeterminate.".into()),
17 hint: None,
18 }
19}
20
21pub fn return_query_context_error() -> SQLError {
22 SQLError::Routine {
23 sqlstate: "42601".into(),
24 message: "cannot use RETURN QUERY in a non-SETOF function".into(),
25 }
26}
27
28pub fn result_row_values(result: &SQLResult, row: usize) -> Option<Vec<Value>> {
30 (row < result.rows.len()).then(|| {
31 (0..result.columns.len())
32 .map(|column| result.value_at(row, column).cloned().unwrap_or(Value::Null))
33 .collect()
34 })
35}
36
37pub fn result_row_count(result: &SQLResult) -> Result<i64, SQLError> {
38 let (raw_count, source) = if result.columns.is_empty() {
39 (result.affected_rows, "affected-row")
40 } else {
41 (
42 u64::try_from(result.rows.len()).map_err(|_| {
43 SQLError::Internal(format!(
44 "result row count {} cannot be represented as u64",
45 result.rows.len()
46 ))
47 })?,
48 "result-row",
49 )
50 };
51 i64::try_from(raw_count).map_err(|_| {
52 SQLError::Internal(format!(
53 "{source} count {raw_count} exceeds PL/pgSQL's signed 64-bit ROW_COUNT range"
54 ))
55 })
56}
57
58pub fn strict_into_check(row_count: i64) -> Result<(), SQLError> {
59 if row_count == 0 {
60 return Err(SQLError::Routine {
61 sqlstate: "P0002".into(),
62 message: "query returned no rows".into(),
63 });
64 }
65 if row_count > 1 {
66 return Err(SQLError::Routine {
67 sqlstate: "P0003".into(),
68 message: "query returned more than one row".into(),
69 });
70 }
71 Ok(())
72}
73
74pub fn to_i64_value(value: &Value) -> Result<i64, SQLError> {
75 match cast_value(value, "bigint")? {
76 Value::Int(v) => Ok(v),
77 other => Err(SQLError::TypeMismatch(format!(
78 "expected an integer, got {other:?}"
79 ))),
80 }
81}
82
83pub fn routine_message(error: &SQLError) -> String {
86 match error {
87 SQLError::Routine { message, .. } => message.clone(),
88 other => other.to_string(),
89 }
90}
91
92pub fn looks_like_sqlstate(text: &str) -> bool {
93 text.len() == 5 && text.bytes().all(|b| b.is_ascii_alphanumeric())
94}
95
96pub fn arm_matches(conditions: &[String], state: &str) -> Result<bool, SQLError> {
98 for condition in conditions {
99 if condition == "others" {
100 if state != "57014" && state != "P0004" {
103 return Ok(true);
104 }
105 continue;
106 }
107 let mut known_condition = false;
108 for mapped in condition_sqlstates(condition) {
109 known_condition = true;
110 if sqlstate_matches(mapped, state) {
111 return Ok(true);
112 }
113 }
114 if !known_condition {
115 if looks_like_sqlstate(condition) {
116 if sqlstate_matches(&condition.to_ascii_uppercase(), state) {
117 return Ok(true);
118 }
119 } else {
120 return Err(SQLError::Internal(format!(
121 "unrecognized PL/pgSQL exception condition `{condition}`"
122 )));
123 }
124 }
125 }
126 Ok(false)
127}
128
129pub fn sqlstate_matches(condition: &str, state: &str) -> bool {
130 condition == state || (condition.ends_with("000") && state.get(..2) == condition.get(..2))
131}
132
133pub fn format_raise_message(format: &str, args: &[Value]) -> Result<String, SQLError> {
135 let mut out = String::with_capacity(format.len() + 16);
136 let mut chars = format.chars().peekable();
137 let mut next_arg = 0usize;
138 while let Some(c) = chars.next() {
139 if c != '%' {
140 out.push(c);
141 continue;
142 }
143 if chars.peek() == Some(&'%') {
144 chars.next();
145 out.push('%');
146 continue;
147 }
148 let Some(value) = args.get(next_arg) else {
149 return Err(SQLError::Routine {
150 sqlstate: "42601".into(),
151 message: "too few parameters specified for RAISE".into(),
152 });
153 };
154 next_arg += 1;
155 out.push_str(&raise_text(value)?);
156 }
157 if next_arg < args.len() {
158 return Err(SQLError::Routine {
159 sqlstate: "42601".into(),
160 message: "too many parameters specified for RAISE".into(),
161 });
162 }
163 Ok(out)
164}
165
166pub fn raise_text(value: &Value) -> Result<String, SQLError> {
169 Ok(match value {
170 Value::Null => "<NULL>".into(),
171 Value::Datum(value) => return raise_text(&crate::expr::datums::read(value)?),
172 Value::Void => String::new(),
173 Value::Bool(b) => (if *b { "t" } else { "f" }).into(),
174 Value::Int(v) => v.to_string(),
175 Value::Float(v) => v.to_string(),
176 Value::Decimal(v) => v.to_sql_string(),
177 Value::Str(s) => s.clone(),
178 Value::FixedChar(s) => s.trim_end_matches(' ').to_string(),
179 Value::Temporal(t) => t.to_sql_string(),
180 Value::Json(text) | Value::JsonB(text) => text.clone(),
181 Value::Array(_) | Value::LegacyVector(_) => crate::expr::value_to_string(value)?,
182 Value::BitString(_) => crate::expr::value_to_string(value)?,
183 Value::Enum(value) => return Err(crate::expr::catalog_output_required(value)),
184 Value::Bytes(b) => {
185 use std::fmt::Write as _;
186 let mut out = String::with_capacity(2 + b.len() * 2);
187 out.push_str("\\x");
188 for byte in b {
189 let _ = write!(out, "{byte:02x}");
190 }
191 out
192 }
193 Value::List(items) => {
194 let inner = items
195 .iter()
196 .map(raise_text)
197 .collect::<Result<Vec<_>, _>>()?
198 .join(",");
199 format!("{{{inner}}}")
200 }
201 Value::Row(items) => {
202 let inner = items
203 .iter()
204 .map(raise_text)
205 .collect::<Result<Vec<_>, _>>()?
206 .join(",");
207 format!("({inner})")
208 }
209 Value::Record(fields) => {
210 let inner = fields
211 .iter()
212 .map(|(_, value)| raise_text(value))
213 .collect::<Result<Vec<_>, _>>()?
214 .join(",");
215 format!("({inner})")
216 }
217 Value::Map(map) => serde_json::to_string(map).unwrap_or_else(|_| format!("{map:?}")),
218 })
219}
220
221#[cfg(test)]
222mod tests;