Skip to main content

schema_parser/parser/
roxml_parser.rs

1use crate::parser::nodes::*;
2use roxmltree::{Document, Node};
3
4const NS: &str = "http://stano.com/database";
5
6pub fn parse_database_roxml(xml: &str) -> Result<DatabaseXml, String> {
7    let doc = Document::parse(xml).map_err(|e| format!("XML parse error: {e}"))?;
8    let root = doc
9        .descendants()
10        .find(|n| n.has_tag_name((NS, "database")))
11        .ok_or_else(|| "No <database> root element found".to_string())?;
12
13    parse_database_node(root)
14}
15
16fn parse_database_node(node: Node) -> Result<DatabaseXml, String> {
17    let foreign_key_mode = attr_string(node, "foreignKeyMode");
18    let boolean_mode = attr_string(node, "booleanMode");
19    let case_sensitive_text = attr_bool(node, "caseSensitiveText")?;
20
21    let mut tables = Vec::new();
22    let mut enums = Vec::new();
23    let mut views = Vec::new();
24    let mut functions = Vec::new();
25    let mut procedures = Vec::new();
26    let mut other_sql = Vec::new();
27    let mut schemas = Vec::new();
28
29    for child in node.children().filter(|n| n.is_element()) {
30        match child.tag_name().name() {
31            "table" if child.has_tag_name((NS, "table")) => tables.push(parse_table_node(child)?),
32            "enum" if child.has_tag_name((NS, "enum")) => enums.push(parse_enum_node(child)?),
33            "view" if child.has_tag_name((NS, "view")) => views.push(parse_view_node(child)?),
34            "function" if child.has_tag_name((NS, "function")) => {
35                functions.push(parse_function_node(child)?)
36            }
37            "procedure" if child.has_tag_name((NS, "procedure")) => {
38                procedures.push(parse_procedure_node(child)?)
39            }
40            "otherSql" if child.has_tag_name((NS, "otherSql")) => {
41                other_sql.push(parse_other_sql_node(child)?)
42            }
43            "schema" if child.has_tag_name((NS, "schema")) => {
44                schemas.push(parse_schema_node(child)?)
45            }
46            _ => return Err(unknown_element(child, node)),
47        }
48    }
49
50    Ok(DatabaseXml {
51        foreign_key_mode,
52        boolean_mode,
53        case_sensitive_text,
54        tables,
55        enums,
56        views,
57        functions,
58        procedures,
59        other_sql,
60        schemas,
61    })
62}
63
64fn parse_schema_node(node: Node) -> Result<SchemaXml, String> {
65    let name = attr_string_required(node, "name")?;
66    // Only <database> carries caseSensitiveText; failing here beats silently ignoring it.
67    if node.has_attribute("caseSensitiveText") {
68        return Err(format!(
69            "<schema name=\"{name}\">: caseSensitiveText is only allowed on <database>"
70        ));
71    }
72
73    let mut tables = Vec::new();
74    let mut enums = Vec::new();
75    let mut views = Vec::new();
76    let mut functions = Vec::new();
77    let mut procedures = Vec::new();
78    let mut other_sql = Vec::new();
79
80    for child in node.children().filter(|n| n.is_element()) {
81        match child.tag_name().name() {
82            "table" if child.has_tag_name((NS, "table")) => tables.push(parse_table_node(child)?),
83            "enum" if child.has_tag_name((NS, "enum")) => enums.push(parse_enum_node(child)?),
84            "view" if child.has_tag_name((NS, "view")) => views.push(parse_view_node(child)?),
85            "function" if child.has_tag_name((NS, "function")) => {
86                functions.push(parse_function_node(child)?)
87            }
88            "procedure" if child.has_tag_name((NS, "procedure")) => {
89                procedures.push(parse_procedure_node(child)?)
90            }
91            "otherSql" if child.has_tag_name((NS, "otherSql")) => {
92                other_sql.push(parse_other_sql_node(child)?)
93            }
94            _ => return Err(unknown_element(child, node)),
95        }
96    }
97
98    Ok(SchemaXml {
99        name,
100        tables,
101        enums,
102        views,
103        functions,
104        procedures,
105        other_sql,
106    })
107}
108
109fn parse_table_node(node: Node) -> Result<TableXml, String> {
110    let name = attr_string_required(node, "name")?;
111    let data_opt = attr_bool(node, "data")?;
112    let no_export = attr_bool(node, "noExport")?;
113    let export_data_column = attr_string(node, "exportDataColumn");
114    let compress = attr_bool(node, "compress")?;
115    let lock_escalation = attr_string(node, "lockEscalation");
116
117    let mut columns: Option<ColumnsXml> = None;
118    let mut keys: Option<KeysXml> = None;
119    let mut relations: Option<RelationsXml> = None;
120    let mut triggers: Option<TriggersXml> = None;
121    let mut constraints: Option<ConstraintsXml> = None;
122    let mut aggregations: Option<AggregationsXml> = None;
123    let mut initial_data: Option<InitialDataXml> = None;
124
125    for child in node.children().filter(|n| n.is_element()) {
126        if child.has_tag_name((NS, "columns")) {
127            columns = Some(parse_columns_node(child)?);
128        } else if child.has_tag_name((NS, "keys")) {
129            keys = Some(parse_keys_node(child)?);
130        } else if child.has_tag_name((NS, "relations")) {
131            relations = Some(parse_relations_node(child)?);
132        } else if child.has_tag_name((NS, "triggers")) {
133            triggers = Some(parse_triggers_node(child)?);
134        } else if child.has_tag_name((NS, "constraints")) {
135            constraints = Some(parse_constraints_node(child)?);
136        } else if child.has_tag_name((NS, "aggregations")) {
137            aggregations = Some(parse_aggregations_node(child)?);
138        } else if child.has_tag_name((NS, "initialData")) {
139            initial_data = Some(parse_initial_data_node(child)?);
140        } else {
141            return Err(unknown_element(child, node));
142        }
143    }
144
145    Ok(TableXml {
146        name,
147        data_opt,
148        no_export,
149        export_data_column,
150        compress,
151        lock_escalation,
152        columns,
153        keys,
154        relations,
155        triggers,
156        constraints,
157        aggregations,
158        initial_data,
159    })
160}
161
162fn parse_columns_node(node: Node) -> Result<ColumnsXml, String> {
163    let mut cols = Vec::new();
164    for c in node.children().filter(|n| n.is_element()) {
165        if !c.has_tag_name((NS, "column")) {
166            return Err(unknown_element(c, node));
167        }
168        cols.push(parse_column_node(c)?);
169    }
170    Ok(ColumnsXml { column: cols })
171}
172
173fn parse_column_node(node: Node) -> Result<ColumnXml, String> {
174    Ok(ColumnXml {
175        name: attr_string_required(node, "name")?,
176        r#type: attr_string_required(node, "type")?,
177        length: attr_non_negative_i32(node, "length")?,
178        scale: attr_non_negative_i32(node, "scale")?,
179        required: attr_bool(node, "required")?,
180        default_value: attr_string(node, "default"),
181        generated: attr_string(node, "generated"),
182        enum_type: attr_string(node, "enumType"),
183        element_type: attr_string(node, "elementType"),
184        min_value: attr_decimal(node, "minValue")?,
185        max_value: attr_decimal(node, "maxValue")?,
186        check: parse_check_nodes(node)?,
187    })
188}
189
190fn parse_check_nodes(column: Node) -> Result<Vec<CheckXml>, String> {
191    let mut checks = Vec::new();
192    for c in column.children().filter(|n| n.is_element()) {
193        if !c.has_tag_name((NS, "check")) {
194            return Err(unknown_element(c, column));
195        }
196        checks.push(parse_check_node(c));
197    }
198    Ok(checks)
199}
200
201fn parse_check_node(node: Node) -> CheckXml {
202    let text = collect_text(node);
203    CheckXml {
204        database_type: attr_string(node, "databaseType"),
205        value: if text.is_empty() { None } else { Some(text) },
206    }
207}
208
209fn parse_keys_node(node: Node) -> Result<KeysXml, String> {
210    let mut primary: Option<PrimaryKeyXml> = None;
211    let mut uniques: Vec<KeyColumnsXml> = Vec::new();
212    let mut indexes: Vec<IndexXml> = Vec::new();
213
214    for c in node.children().filter(|n| n.is_element()) {
215        // The XSD declares <keys> as a sequence: primary, then unique*, then index*.
216        if c.has_tag_name((NS, "primary")) {
217            if primary.is_some() {
218                return Err("<keys> may contain only one <primary>".to_string());
219            }
220            if !uniques.is_empty() || !indexes.is_empty() {
221                return Err("<primary> must come before <unique> and <index> in <keys>".to_string());
222            }
223            primary = Some(parse_primary_key_node(c)?);
224        } else if c.has_tag_name((NS, "unique")) {
225            if !indexes.is_empty() {
226                return Err("<unique> must come before <index> in <keys>".to_string());
227            }
228            uniques.push(parse_key_columns_node(c)?);
229        } else if c.has_tag_name((NS, "index")) {
230            indexes.push(parse_index_node(c)?);
231        } else {
232            return Err(unknown_element(c, node));
233        }
234    }
235
236    Ok(KeysXml {
237        primary,
238        uniques,
239        indexes,
240    })
241}
242
243fn parse_key_column_nodes(node: Node) -> Result<Vec<KeyColumnXml>, String> {
244    let mut columns = Vec::new();
245    for c in node.children().filter(|n| n.is_element()) {
246        if !c.has_tag_name((NS, "column")) {
247            return Err(unknown_element(c, node));
248        }
249        columns.push(KeyColumnXml {
250            name: attr_string_required(c, "name")?,
251        });
252    }
253    if columns.is_empty() {
254        return Err(format!(
255            "<{}> must contain at least one <column>",
256            node.tag_name().name()
257        ));
258    }
259    Ok(columns)
260}
261
262fn parse_primary_key_node(node: Node) -> Result<PrimaryKeyXml, String> {
263    if node.has_attribute("where") {
264        return Err("<primary> does not support a 'where' predicate".to_string());
265    }
266    Ok(PrimaryKeyXml {
267        columns: parse_key_column_nodes(node)?,
268        cluster: attr_bool(node, "cluster")?,
269    })
270}
271
272fn parse_key_columns_node(node: Node) -> Result<KeyColumnsXml, String> {
273    let columns = parse_key_column_nodes(node)?;
274    let cluster = attr_bool(node, "cluster")?;
275    let where_clause = attr_string(node, "where");
276    Ok(KeyColumnsXml {
277        columns,
278        cluster,
279        where_clause,
280    })
281}
282
283fn parse_index_node(node: Node) -> Result<IndexXml, String> {
284    let columns = parse_key_column_nodes(node)?;
285    Ok(IndexXml {
286        columns,
287        include: attr_string(node, "include"),
288        compress: attr_bool(node, "compress")?,
289        unique: attr_bool(node, "unique")?,
290        where_clause: attr_string(node, "where"),
291    })
292}
293
294fn parse_relations_node(node: Node) -> Result<RelationsXml, String> {
295    let mut rels = Vec::new();
296    let mut composite_rels = Vec::new();
297    for r in node.children().filter(|n| n.is_element()) {
298        if r.has_tag_name((NS, "relation")) {
299            rels.push(RelationXml {
300                src: attr_string_required(r, "src")?,
301                table: attr_string_required(r, "table")?,
302                column: attr_string_required(r, "column")?,
303                r#type: attr_string_required(r, "type")?,
304                disable_usage_checking: attr_bool(r, "disableUsageChecking")?,
305            });
306        } else if r.has_tag_name((NS, "compositeRelation")) {
307            composite_rels.push(parse_composite_relation_node(r)?);
308        } else {
309            return Err(unknown_element(r, node));
310        }
311    }
312    Ok(RelationsXml {
313        relation: rels,
314        composite_relation: composite_rels,
315    })
316}
317
318fn parse_composite_relation_node(node: Node) -> Result<CompositeRelationXml, String> {
319    let mut columns = Vec::new();
320    for c in node.children().filter(|n| n.is_element()) {
321        if !c.has_tag_name((NS, "column")) {
322            return Err(unknown_element(c, node));
323        }
324        columns.push(CompositeRelationColumnXml {
325            src: attr_string_required(c, "src")?,
326            name: attr_string_required(c, "name")?,
327        });
328    }
329    Ok(CompositeRelationXml {
330        table: attr_string_required(node, "table")?,
331        r#type: attr_string_required(node, "type")?,
332        disable_usage_checking: attr_bool(node, "disableUsageChecking")?,
333        column: columns,
334    })
335}
336
337fn parse_view_node(node: Node) -> Result<ViewXml, String> {
338    Ok(ViewXml {
339        name: attr_string_required(node, "name")?,
340        database_type: attr_string(node, "databaseType"),
341        sql: collect_text(node),
342    })
343}
344
345fn parse_function_node(node: Node) -> Result<FunctionXml, String> {
346    let name = attr_string_required(node, "name")?;
347    let mut sql = Vec::new();
348    for s in node.children().filter(|n| n.is_element()) {
349        if !s.has_tag_name((NS, "sql")) {
350            return Err(unknown_element(s, node));
351        }
352        sql.push(VendorSqlXml {
353            database_type: attr_string_required(s, "databaseType")?,
354            sql: collect_text(s),
355        });
356    }
357    Ok(FunctionXml { name, sql })
358}
359
360fn parse_procedure_node(node: Node) -> Result<ProcedureXml, String> {
361    let name = attr_string_required(node, "name")?;
362    let mut sql = Vec::new();
363    for s in node.children().filter(|n| n.is_element()) {
364        if !s.has_tag_name((NS, "sql")) {
365            return Err(unknown_element(s, node));
366        }
367        sql.push(VendorSqlXml {
368            database_type: attr_string_required(s, "databaseType")?,
369            sql: collect_text(s),
370        });
371    }
372    Ok(ProcedureXml { name, sql })
373}
374
375fn parse_other_sql_node(node: Node) -> Result<OtherSqlXml, String> {
376    let database_type = attr_string_required(node, "databaseType")?;
377    let order_text = attr_string_required(node, "order")?;
378    let order = match order_text.to_ascii_lowercase().as_str() {
379        "top" => OtherSqlOrderXml::Top,
380        "bottom" => OtherSqlOrderXml::Bottom,
381        other => {
382            return Err(format!(
383                "<otherSql> element has an unrecognized order '{}' (expected top or bottom)",
384                other
385            ));
386        }
387    };
388    Ok(OtherSqlXml {
389        database_type,
390        order,
391        sql: collect_text(node),
392    })
393}
394
395fn parse_enum_node(node: Node) -> Result<EnumXml, String> {
396    let name = attr_string_required(node, "name")?;
397    let mut value = Vec::new();
398    for v in node.children().filter(|n| n.is_element()) {
399        if !v.has_tag_name((NS, "value")) {
400            return Err(unknown_element(v, node));
401        }
402        value.push(EnumValueXml {
403            name: attr_string_required(v, "name")?,
404            code: attr_string(v, "code"),
405        });
406    }
407    Ok(EnumXml { name, value })
408}
409
410fn parse_triggers_node(node: Node) -> Result<TriggersXml, String> {
411    let mut update = Vec::new();
412    let mut delete = Vec::new();
413    for c in node.children().filter(|n| n.is_element()) {
414        if c.has_tag_name((NS, "update")) {
415            update.push(TriggerXml {
416                database_type: attr_string_required(c, "databaseType")?,
417                sql: collect_text(c),
418            });
419        } else if c.has_tag_name((NS, "delete")) {
420            delete.push(TriggerXml {
421                database_type: attr_string_required(c, "databaseType")?,
422                sql: collect_text(c),
423            });
424        } else {
425            return Err(unknown_element(c, node));
426        }
427    }
428    Ok(TriggersXml { update, delete })
429}
430
431fn parse_constraints_node(node: Node) -> Result<ConstraintsXml, String> {
432    let mut constraint = Vec::new();
433    for c in node.children().filter(|n| n.is_element()) {
434        if !c.has_tag_name((NS, "constraint")) {
435            return Err(unknown_element(c, node));
436        }
437        constraint.push(ConstraintXml {
438            name: attr_string_required(c, "name")?,
439            database_type: attr_string(c, "databaseType"),
440            sql: collect_text(c),
441        });
442    }
443    Ok(ConstraintsXml { constraint })
444}
445
446fn parse_aggregations_node(node: Node) -> Result<AggregationsXml, String> {
447    let mut aggregate = Vec::new();
448    for a in node.children().filter(|n| n.is_element()) {
449        if !a.has_tag_name((NS, "aggregate")) {
450            return Err(unknown_element(a, node));
451        }
452        aggregate.push(parse_aggregate_node(a)?);
453    }
454    Ok(AggregationsXml { aggregate })
455}
456
457fn parse_aggregate_node(node: Node) -> Result<AggregateXml, String> {
458    let mut columns = Vec::new();
459    let mut group: Option<GroupXml> = None;
460    let destination_table = attr_string_required(node, "destinationTable")?;
461
462    for c in node.children().filter(|n| n.is_element()) {
463        if c.has_tag_name((NS, "sum")) {
464            columns.push(AggregateColumnXml::Sum(SumXml {
465                source_column: attr_string_required(c, "sourceColumn")?,
466                destination_column: attr_string_required(c, "destinationColumn")?,
467            }));
468        } else if c.has_tag_name((NS, "count")) {
469            columns.push(AggregateColumnXml::Count(CountXml {
470                destination_column: attr_string_required(c, "destinationColumn")?,
471            }));
472        } else if c.has_tag_name((NS, "group")) {
473            if group.is_some() {
474                return Err(format!(
475                    "aggregate to '{destination_table}' has more than one <group>"
476                ));
477            }
478            group = Some(parse_group_node(c)?);
479        } else {
480            return Err(unknown_element(c, node));
481        }
482    }
483
484    let group =
485        group.ok_or_else(|| format!("aggregate to '{destination_table}' is missing <group>"))?;
486
487    Ok(AggregateXml {
488        columns,
489        group,
490        destination_table,
491        date_column: attr_string_required(node, "dateColumn")?,
492        timestamp_column: attr_string_required(node, "timestampColumn")?,
493        frequency: attr_string_required(node, "frequency")?,
494        criteria: attr_string(node, "criteria"),
495    })
496}
497
498fn parse_group_node(node: Node) -> Result<GroupXml, String> {
499    let mut column = Vec::new();
500    for c in node.children().filter(|n| n.is_element()) {
501        if !c.has_tag_name((NS, "column")) {
502            return Err(unknown_element(c, node));
503        }
504        column.push(GroupColumnXml {
505            source: attr_string_required(c, "source")?,
506            destination: attr_string_required(c, "destination")?,
507            source_derived_from: attr_string(c, "sourceDerivedFrom"),
508        });
509    }
510    Ok(GroupXml { column })
511}
512
513fn parse_initial_data_node(node: Node) -> Result<InitialDataXml, String> {
514    let mut sql = Vec::new();
515    for s in node.children().filter(|n| n.is_element()) {
516        if !s.has_tag_name((NS, "sql")) {
517            return Err(unknown_element(s, node));
518        }
519        sql.push(InitialSqlXml {
520            database_type: attr_string(s, "databaseType"),
521            sql: collect_text(s),
522        });
523    }
524    Ok(InitialDataXml { sql })
525}
526
527// -------- Utils --------
528/// Error for a child element the XSD does not allow here (a typo, or a stray element in the
529/// wrong place), so it is reported instead of being silently dropped from the model.
530fn unknown_element(child: Node, parent: Node) -> String {
531    format!(
532        "<{}> element is not allowed inside <{}>",
533        child.tag_name().name(),
534        parent.tag_name().name()
535    )
536}
537
538fn attr_string(node: Node, name: &str) -> Option<String> {
539    node.attribute(name).map(|s| s.to_string())
540}
541
542/// Reads a required attribute. Returns an error (naming the element and attribute)
543/// rather than silently defaulting to `""` when it's absent - a missing `name`/`type`/
544/// `table`/`column`/etc. attribute is a malformed schema definition, and nothing
545/// downstream validates against an empty name, so a silent default would otherwise let
546/// it through as a real (if oddly-named) table/column/relation.
547fn attr_string_required(node: Node, name: &str) -> Result<String, String> {
548    node.attribute(name).map(|s| s.to_string()).ok_or_else(|| {
549        format!(
550            "<{}> element is missing required attribute '{}'",
551            node.tag_name().name(),
552            name
553        )
554    })
555}
556
557/// Reads an optional boolean attribute. Unlike a missing attribute (which is a legitimate
558/// "not specified"), a *present but unparseable* value (`required="yep"`) is a malformed
559/// schema definition - silently falling back to `None`/`false` would hide a typo instead of
560/// reporting it, so this errors instead.
561fn attr_bool(node: Node, name: &str) -> Result<Option<bool>, String> {
562    match node.attribute(name) {
563        None => Ok(None),
564        Some(v) => match v.to_ascii_lowercase().as_str() {
565            "true" | "1" | "yes" | "on" => Ok(Some(true)),
566            "false" | "0" | "no" | "off" => Ok(Some(false)),
567            _ => Err(format!(
568                "<{}> attribute '{}' has invalid boolean value '{}' (expected true/false, 1/0, yes/no, or on/off)",
569                node.tag_name().name(),
570                name,
571                v
572            )),
573        },
574    }
575}
576
577/// Reads an optional integer attribute, erroring (rather than silently defaulting to `None`)
578/// when the attribute is present but not a valid `i32` - a typo like `length="1O0"` or an
579/// overflowing value like `length="99999999999"` should be reported, not turned into 0.
580fn attr_i32(node: Node, name: &str) -> Result<Option<i32>, String> {
581    match node.attribute(name) {
582        None => Ok(None),
583        Some(v) => v.parse::<i32>().map(Some).map_err(|_| {
584            format!(
585                "<{}> attribute '{}' has invalid integer value '{}'",
586                node.tag_name().name(),
587                name,
588                v
589            )
590        }),
591    }
592}
593
594/// Reads an optional `xs:nonNegativeInteger` attribute (column `length`/`scale`).
595fn attr_non_negative_i32(node: Node, name: &str) -> Result<Option<i32>, String> {
596    match attr_i32(node, name)? {
597        Some(v) if v < 0 => Err(format!(
598            "<{}> attribute '{}' must not be negative (got {})",
599            node.tag_name().name(),
600            name,
601            v
602        )),
603        other => Ok(other),
604    }
605}
606
607/// Reads an optional `xs:decimal` attribute as its original text, so precision is never lost to
608/// a float round-trip. Errors (rather than silently defaulting to `None`) when the attribute is
609/// present but not a plain decimal literal - this covers typos like `minValue="1o"` as well as
610/// `inf`/`nan`/exponent forms. The value is later emitted verbatim into SQL, so it must be
611/// validated here.
612fn attr_decimal(node: Node, name: &str) -> Result<Option<String>, String> {
613    match node.attribute(name) {
614        None => Ok(None),
615        Some(v) => match is_decimal_literal(v) {
616            true => Ok(Some(v.to_string())),
617            false => Err(format!(
618                "<{}> attribute '{}' has invalid numeric value '{}'",
619                node.tag_name().name(),
620                name,
621                v
622            )),
623        },
624    }
625}
626
627/// `[+-]? digits [. digits]?` or `[+-]? . digits`, matching the `xs:decimal` lexical space.
628fn is_decimal_literal(v: &str) -> bool {
629    let v = v.strip_prefix(['+', '-']).unwrap_or(v);
630    let (int, frac) = v.split_once('.').unwrap_or((v, ""));
631    let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
632    digits(int) && digits(frac) && !(int.is_empty() && frac.is_empty())
633}
634
635fn collect_text(node: Node) -> String {
636    let mut out = String::new();
637    for n in node.children() {
638        if n.is_text() {
639            out.push_str(n.text().unwrap_or(""));
640        }
641    }
642    out.trim().to_string()
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648    use std::fs;
649
650    #[test]
651    fn parse_with_roxmltree_sample() {
652        let xml = fs::read_to_string("tests/resources/schema-parser-test-schema.xml")
653            .expect("resource present");
654        let db = parse_database_roxml(&xml).expect("parsed");
655        assert!(!db.tables.is_empty());
656        assert!(db.schemas.is_empty() || !db.schemas[0].tables.is_empty());
657    }
658
659    #[test]
660    fn parse_check_node_joins_text_around_comments() {
661        let doc =
662            Document::parse(r#"<check xmlns="http://stano.com/database">a<!-- note -->b</check>"#)
663                .unwrap();
664        assert_eq!(
665            parse_check_node(doc.root_element()).value.as_deref(),
666            Some("ab")
667        );
668
669        let empty =
670            Document::parse(r#"<check xmlns="http://stano.com/database">  </check>"#).unwrap();
671        assert_eq!(parse_check_node(empty.root_element()).value, None);
672    }
673
674    #[test]
675    fn attr_bool_is_case_insensitive() {
676        let doc = Document::parse(
677            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE" cluster="No"/>"#,
678        )
679        .unwrap();
680        let node = doc.root_element();
681
682        assert_eq!(attr_bool(node, "required"), Ok(Some(true)));
683        assert_eq!(attr_bool(node, "cluster"), Ok(Some(false)));
684    }
685
686    #[test]
687    fn attr_bool_errors_on_unrecognized_value() {
688        let doc = Document::parse(
689            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="yep"/>"#,
690        )
691        .unwrap();
692        let node = doc.root_element();
693
694        let err = attr_bool(node, "required").unwrap_err();
695        assert!(err.contains("required"));
696        assert!(err.contains("yep"));
697    }
698
699    #[test]
700    fn attr_i32_errors_on_unparseable_value() {
701        let doc = Document::parse(
702            r#"<column xmlns="http://stano.com/database" name="x" type="varchar" length="1O0"/>"#,
703        )
704        .unwrap();
705        let node = doc.root_element();
706
707        let err = attr_i32(node, "length").unwrap_err();
708        assert!(err.contains("length"));
709        assert!(err.contains("1O0"));
710    }
711
712    #[test]
713    fn attr_decimal_errors_on_unparseable_value() {
714        let doc = Document::parse(
715            r#"<column xmlns="http://stano.com/database" name="x" type="int" minValue="1o"/>"#,
716        )
717        .unwrap();
718        let node = doc.root_element();
719
720        let err = attr_decimal(node, "minValue").unwrap_err();
721        assert!(err.contains("minValue"));
722        assert!(err.contains("1o"));
723    }
724
725    #[test]
726    fn attr_decimal_keeps_original_text() {
727        for v in ["0", "-5", "+3.14", ".5", "5.", "9007199254740993", "0.10"] {
728            let xml = format!(
729                r#"<column xmlns="http://stano.com/database" name="x" type="int" minValue="{v}"/>"#
730            );
731            let doc = Document::parse(&xml).unwrap();
732            assert_eq!(
733                attr_decimal(doc.root_element(), "minValue")
734                    .unwrap()
735                    .as_deref(),
736                Some(v)
737            );
738        }
739    }
740
741    #[test]
742    fn attr_decimal_rejects_exponent_and_bare_sign() {
743        for v in ["1e5", "-", ".", "1.2.3", ""] {
744            let xml = format!(
745                r#"<column xmlns="http://stano.com/database" name="x" type="int" minValue="{v}"/>"#
746            );
747            let doc = Document::parse(&xml).unwrap();
748            assert!(attr_decimal(doc.root_element(), "minValue").is_err(), "{v}");
749        }
750    }
751
752    #[test]
753    fn attr_decimal_errors_on_infinite_value() {
754        let doc = Document::parse(
755            r#"<column xmlns="http://stano.com/database" name="x" type="int" maxValue="inf"/>"#,
756        )
757        .unwrap();
758        let node = doc.root_element();
759
760        let err = attr_decimal(node, "maxValue").unwrap_err();
761        assert!(err.contains("maxValue"));
762        assert!(err.contains("inf"));
763    }
764
765    #[test]
766    fn parse_column_node_honors_uppercase_required_attribute() {
767        let doc = Document::parse(
768            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE"/>"#,
769        )
770        .unwrap();
771        let node = doc.root_element();
772
773        let column = parse_column_node(node).expect("parse ok");
774
775        assert_eq!(column.required, Some(true));
776    }
777
778    #[test]
779    fn missing_required_attribute_returns_error_instead_of_defaulting_to_empty_string() {
780        let doc =
781            Document::parse(r#"<column xmlns="http://stano.com/database" type="int"/>"#).unwrap();
782        let node = doc.root_element();
783
784        let err = parse_column_node(node).unwrap_err();
785        assert!(err.contains("column"));
786        assert!(err.contains("name"));
787    }
788}