Skip to main content

uqa_sql/
xml.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Native XML input validation and declaration-aware result output.
8
9use crate::SQLError;
10use uqa_core::memory::{Produced, ProductionControl, ProductionString};
11
12mod declaration;
13#[allow(unsafe_code)]
14mod parser;
15
16/// SQL/XML input mode selected by the invoking session's `xmloption`.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum XmlOption {
19    Content,
20    Document,
21}
22
23/// Validate a UTF-8 XML datum without rewriting its stored spelling. Parser contexts own their error and external-resource handlers; no process-global callbacks are replaced.
24pub fn validate(input: &str, option: XmlOption) -> Result<(), SQLError> {
25    validate_with_notices(input, option, |_| {})
26}
27
28/// Validate with the invoking operation's notice sink. Notices are forwarded after the native parser has released its context, including when input ultimately fails.
29pub fn validate_with_notices(
30    input: &str,
31    option: XmlOption,
32    notice: impl FnMut(crate::SQLNotice),
33) -> Result<(), SQLError> {
34    validate_with_control(input, option, &ProductionControl::uncontrolled(), notice)
35}
36
37/// Validate while charging native parser allocations and checking both cancellation owners between bounded input reads and allocations.
38pub fn validate_with_control(
39    input: &str,
40    option: XmlOption,
41    control: &ProductionControl<'_>,
42    notice: impl FnMut(crate::SQLNotice),
43) -> Result<(), SQLError> {
44    control.check()?;
45    let declaration = if option == XmlOption::Content {
46        declaration::parse(input, control).map_err(|failure| match failure {
47            declaration::Failure::Invalid(detail) => error(option, true, Some(detail.into())),
48            declaration::Failure::Control(error) => error.into(),
49        })?
50    } else {
51        declaration::Declaration::default()
52    };
53    let body = &input[declaration.length..];
54    let document = option == XmlOption::Document || declaration::has_doctype(body, control)?;
55    parser::validate(
56        if document { input } else { body },
57        document,
58        declaration.version.unwrap_or("1.0"),
59        control,
60        notice,
61    )
62    .map_err(|failure| match failure {
63        parser::Failure::Invalid(detail) => error(option, false, detail),
64        parser::Failure::Memory => SQLError::Routine {
65            sqlstate: "53200".into(),
66            message: "out of memory while parsing XML".into(),
67        },
68        parser::Failure::Limit => SQLError::Routine {
69            sqlstate: "54000".into(),
70            message: "XML input is too large".into(),
71        },
72        parser::Failure::Control(error) => error.into(),
73    })
74}
75
76fn error(option: XmlOption, declaration: bool, detail: Option<String>) -> SQLError {
77    let (sqlstate, message) = match (option, declaration) {
78        (XmlOption::Content, true) => ("2200N", "invalid XML content: invalid XML declaration"),
79        (XmlOption::Content, false) => ("2200N", "invalid XML content"),
80        (XmlOption::Document, _) => ("2200M", "invalid XML document"),
81    };
82    SQLError::Diagnostic {
83        sqlstate: sqlstate.into(),
84        message: message.into(),
85        detail,
86        hint: None,
87    }
88}
89
90/// Serialize an admitted XML value for UTF-8 text results. XML-to-text casts retain the stored bytes instead; serialization removes encoding and an unnecessary default declaration.
91pub fn output_with_control(
92    input: &str,
93    control: &ProductionControl<'_>,
94) -> Result<Produced<String>, SQLError> {
95    control.check()?;
96    let declaration = declaration::parse(input, control).map_err(|failure| match failure {
97        declaration::Failure::Invalid(detail) => {
98            SQLError::Internal(format!("invalid stored XML declaration: {detail}"))
99        }
100        declaration::Failure::Control(error) => error.into(),
101    })?;
102    let mut output = ProductionString::new(*control);
103    let version = declaration.version.unwrap_or("1.0");
104    let mut body = &input[declaration.length..];
105    if version != "1.0" || declaration.standalone.is_some() {
106        output.push_str("<?xml version=\"")?;
107        output.push_str(version)?;
108        output.push_str("\"")?;
109        if let Some(standalone) = declaration.standalone {
110            output.push_str(if standalone {
111                " standalone=\"yes\""
112            } else {
113                " standalone=\"no\""
114            })?;
115        }
116        output.push_str("?>")?;
117    } else {
118        body = body.strip_prefix('\n').unwrap_or(body);
119    }
120    output.push_str(body)?;
121    Ok(output.finish()?)
122}
123
124#[cfg(test)]
125mod tests;