1use libduckdb_sys::{
37 duckdb_destroy_expression, duckdb_expression, duckdb_expression_fold,
38 duckdb_expression_is_foldable, duckdb_expression_return_type, duckdb_value,
39};
40
41use crate::client_context::ClientContext;
42use crate::error_data::{DuckDbErrorType, ErrorData};
43use crate::types::LogicalType;
44use crate::value::Value;
45
46pub struct Expression {
50 raw: duckdb_expression,
51}
52
53impl Expression {
54 #[inline]
62 #[must_use]
63 pub const unsafe fn from_raw(raw: duckdb_expression) -> Self {
64 Self { raw }
65 }
66
67 #[inline]
69 #[must_use]
70 pub const fn as_raw(&self) -> duckdb_expression {
71 self.raw
72 }
73
74 #[inline]
76 #[must_use]
77 pub const fn is_null(&self) -> bool {
78 self.raw.is_null()
79 }
80
81 #[must_use]
84 pub fn return_type(&self) -> Option<LogicalType> {
85 if self.raw.is_null() {
86 return None;
87 }
88 let raw = unsafe { duckdb_expression_return_type(self.raw) };
91 if raw.is_null() {
92 return None;
93 }
94 Some(unsafe { LogicalType::from_raw(raw) })
96 }
97
98 #[must_use]
102 pub fn is_foldable(&self) -> bool {
103 if self.raw.is_null() {
104 return false;
105 }
106 unsafe { duckdb_expression_is_foldable(self.raw) }
108 }
109
110 pub fn fold(&self, context: &ClientContext) -> Result<Value, ErrorData> {
136 let mut out_value: duckdb_value = std::ptr::null_mut();
137 let err_raw =
140 unsafe { duckdb_expression_fold(context.as_raw(), self.raw, &raw mut out_value) };
141 let err = unsafe { ErrorData::from_raw(err_raw) };
143 if err.has_error() {
144 if !out_value.is_null() {
146 drop(unsafe { Value::from_raw(out_value) });
149 }
150 return Err(unpack_exception_json(err));
151 }
152 if out_value.is_null() {
153 return Err(ErrorData::new(
156 DuckDbErrorType::InvalidInput,
157 "Expression::fold: the expression is not foldable (it is not constant)",
158 ));
159 }
160 Ok(unsafe { Value::from_raw(out_value) })
163 }
164}
165
166fn unpack_exception_json(err: ErrorData) -> ErrorData {
170 let Some(raw) = err.message() else {
171 return err;
172 };
173 let Some((type_name, message)) = parse_exception_json(&raw) else {
174 return err;
175 };
176 ErrorData::new(error_type_from_name(&type_name), &message)
177}
178
179fn error_type_from_name(name: &str) -> DuckDbErrorType {
183 use DuckDbErrorType as T;
184 match name {
185 "Out of Range" => T::OutOfRange,
186 "Conversion" => T::Conversion,
187 "Unknown Type" => T::UnknownType,
188 "Decimal" => T::Decimal,
189 "Mismatch Type" => T::MismatchType,
190 "Divide by Zero" => T::DivideByZero,
191 "Object Size" => T::ObjectSize,
192 "Invalid type" => T::InvalidType,
193 "Serialization" => T::Serialization,
194 "TransactionContext" => T::Transaction,
195 "Not implemented" => T::NotImplemented,
196 "Expression" => T::Expression,
197 "Catalog" => T::Catalog,
198 "Parser" => T::Parser,
199 "Binder" => T::Binder,
200 "Planner" => T::Planner,
201 "Scheduler" => T::Scheduler,
202 "Executor" => T::Executor,
203 "Constraint" => T::Constraint,
204 "Index" => T::Index,
205 "Stat" => T::Stat,
206 "Connection" => T::Connection,
207 "Syntax" => T::Syntax,
208 "Settings" => T::Settings,
209 "Optimizer" => T::Optimizer,
210 "NullPointer" => T::NullPointer,
211 "IO" => T::Io,
212 "INTERRUPT" => T::Interrupt,
213 "FATAL" => T::Fatal,
214 "INTERNAL" => T::Internal,
215 "Invalid Input" => T::InvalidInput,
216 "Out of Memory" => T::OutOfMemory,
217 "Permission" => T::Permission,
218 "Parameter Not Resolved" => T::ParameterNotResolved,
219 "Parameter Not Allowed" => T::ParameterNotAllowed,
220 "Dependency" => T::Dependency,
221 "Missing Extension" => T::MissingExtension,
222 "HTTP" => T::Http,
223 "Extension Autoloading" => T::Autoload,
224 "Sequence" => T::Sequence,
225 "Invalid Configuration" => T::InvalidConfiguration,
226 "Data Corruption" => T::DataCorruption,
227 "Resource In Use" => T::ResourceInUse,
228 _ => T::Invalid,
229 }
230}
231
232fn parse_exception_json(raw: &str) -> Option<(String, String)> {
239 let mut chars = raw.trim().chars().peekable();
240 let mut exception_type = None;
241 let mut exception_message = None;
242 let skip_ws = |chars: &mut std::iter::Peekable<std::str::Chars<'_>>| {
243 while chars.peek().is_some_and(char::is_ascii_whitespace) {
244 chars.next();
245 }
246 };
247 if chars.next()? != '{' {
248 return None;
249 }
250 skip_ws(&mut chars);
251 if chars.peek() == Some(&'}') {
252 return None;
253 }
254 loop {
255 skip_ws(&mut chars);
256 let key = parse_json_string(&mut chars)?;
257 skip_ws(&mut chars);
258 if chars.next()? != ':' {
259 return None;
260 }
261 skip_ws(&mut chars);
262 let value = parse_json_string(&mut chars)?;
263 match key.as_str() {
264 "exception_type" => exception_type = Some(value),
265 "exception_message" => exception_message = Some(value),
266 _ => {}
267 }
268 skip_ws(&mut chars);
269 match chars.next()? {
270 ',' => {}
271 '}' => break,
272 _ => return None,
273 }
274 }
275 skip_ws(&mut chars);
276 if chars.next().is_some() {
277 return None;
278 }
279 Some((exception_type?, exception_message?))
280}
281
282fn parse_json_string(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Option<String> {
285 if chars.next()? != '"' {
286 return None;
287 }
288 let mut out = String::new();
289 loop {
290 match chars.next()? {
291 '"' => return Some(out),
292 '\\' => match chars.next()? {
293 '"' => out.push('"'),
294 '\\' => out.push('\\'),
295 '/' => out.push('/'),
296 'b' => out.push('\u{8}'),
297 'f' => out.push('\u{c}'),
298 'n' => out.push('\n'),
299 'r' => out.push('\r'),
300 't' => out.push('\t'),
301 'u' => {
302 let high = parse_hex4(chars)?;
303 let code = if (0xD800..0xDC00).contains(&high) {
304 if chars.next()? != '\\' || chars.next()? != 'u' {
305 return None;
306 }
307 let low = parse_hex4(chars)?;
308 if !(0xDC00..0xE000).contains(&low) {
309 return None;
310 }
311 0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)
312 } else {
313 high
314 };
315 out.push(char::from_u32(code)?);
316 }
317 _ => return None,
318 },
319 c => out.push(c),
320 }
321 }
322}
323
324fn parse_hex4(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Option<u32> {
326 let mut code = 0;
327 for _ in 0..4 {
328 code = code * 16 + chars.next()?.to_digit(16)?;
329 }
330 Some(code)
331}
332
333impl Drop for Expression {
334 fn drop(&mut self) {
335 if !self.raw.is_null() {
336 unsafe { duckdb_destroy_expression(&raw mut self.raw) };
338 }
339 }
340}
341
342crate::debug_repr::impl_handle_debug!(Expression.raw);
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 #[test]
349 fn null_expression_is_null() {
350 let expr = unsafe { Expression::from_raw(std::ptr::null_mut()) };
351 assert!(expr.is_null());
352 assert!(!expr.is_foldable());
353 assert!(expr.return_type().is_none());
354 }
355
356 #[test]
357 fn exception_json_is_unpacked_into_type_and_message() {
358 let raw = r#"{"exception_type":"Conversion","exception_message":"Could not convert string 'abc' to INT64","position":"20"}"#;
359 assert_eq!(
360 parse_exception_json(raw),
361 Some((
362 "Conversion".to_owned(),
363 "Could not convert string 'abc' to INT64".to_owned()
364 ))
365 );
366 assert_eq!(
367 error_type_from_name("Out of Range"),
368 DuckDbErrorType::OutOfRange
369 );
370 assert_eq!(
371 error_type_from_name("Conversion"),
372 DuckDbErrorType::Conversion
373 );
374 assert_eq!(
375 error_type_from_name("no such type"),
376 DuckDbErrorType::Invalid
377 );
378 }
379
380 #[test]
381 fn exception_json_escapes_are_decoded() {
382 let raw = r#"{ "exception_message" : "a\"b\\c\n\u00e9\ud83e\udd86\/" , "exception_type" : "IO" }"#;
383 assert_eq!(
384 parse_exception_json(raw),
385 Some(("IO".to_owned(), "a\"b\\c\n\u{e9}\u{1f986}/".to_owned()))
386 );
387 }
388
389 #[test]
390 fn text_that_is_not_exception_json_is_not_parsed() {
391 for raw in [
392 "plain text",
393 "",
394 "{}",
395 r#"{"exception_type":"IO"}"#,
396 r#"{"exception_type":"IO","exception_message":"m","n":1}"#,
397 r#"{"exception_type":"IO","exception_message":"m"} trailing"#,
398 r#"{"exception_type":"IO","exception_message":"unterminated}"#,
399 r#"{"exception_type":"IO","exception_message":"\ud800"}"#,
400 ] {
401 assert_eq!(parse_exception_json(raw), None, "{raw}");
402 }
403 }
404
405 #[test]
411 fn every_exception_type_name_maps_to_the_error_type_with_its_code() {
412 for (code, name) in [
413 (0, "Invalid"),
414 (1, "Out of Range"),
415 (2, "Conversion"),
416 (3, "Unknown Type"),
417 (4, "Decimal"),
418 (5, "Mismatch Type"),
419 (6, "Divide by Zero"),
420 (7, "Object Size"),
421 (8, "Invalid type"),
422 (9, "Serialization"),
423 (10, "TransactionContext"),
424 (11, "Not implemented"),
425 (12, "Expression"),
426 (13, "Catalog"),
427 (14, "Parser"),
428 (24, "Binder"),
429 (15, "Planner"),
430 (16, "Scheduler"),
431 (17, "Executor"),
432 (18, "Constraint"),
433 (19, "Index"),
434 (20, "Stat"),
435 (21, "Connection"),
436 (22, "Syntax"),
437 (23, "Settings"),
438 (26, "Optimizer"),
439 (27, "NullPointer"),
440 (28, "IO"),
441 (29, "INTERRUPT"),
442 (30, "FATAL"),
443 (31, "INTERNAL"),
444 (32, "Invalid Input"),
445 (33, "Out of Memory"),
446 (34, "Permission"),
447 (35, "Parameter Not Resolved"),
448 (36, "Parameter Not Allowed"),
449 (37, "Dependency"),
450 (39, "Missing Extension"),
451 (38, "HTTP"),
452 (40, "Extension Autoloading"),
453 (41, "Sequence"),
454 (42, "Invalid Configuration"),
455 (43, "Data Corruption"),
456 (44, "Resource In Use"),
457 ] {
458 let mapped = error_type_from_name(name);
459 assert_eq!(u64::from(mapped.to_raw()), code, "{name}");
460 assert_eq!(mapped, DuckDbErrorType::from_raw(mapped.to_raw()), "{name}");
461 }
462 }
463
464 #[test]
465 fn every_single_character_json_escape_is_decoded() {
466 let raw = r#"{"exception_type":"IO","exception_message":"\"\\\/\b\f\n\r\t"}"#;
467 assert_eq!(
468 parse_exception_json(raw),
469 Some(("IO".to_owned(), "\"\\/\u{8}\u{c}\n\r\t".to_owned()))
470 );
471 assert_eq!(
472 parse_exception_json(r#"{"exception_type":"IO","exception_message":"\q"}"#),
473 None
474 );
475 }
476
477 #[test]
478 fn size_of_expression_is_one_pointer() {
479 assert_eq!(
480 std::mem::size_of::<Expression>(),
481 std::mem::size_of::<usize>()
482 );
483 }
484}