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")) => functions.push(parse_function_node(child)?),
35            "procedure" if child.has_tag_name((NS, "procedure")) => procedures.push(parse_procedure_node(child)?),
36            "otherSql" if child.has_tag_name((NS, "otherSql")) => other_sql.push(parse_other_sql_node(child)?),
37            "schema" if child.has_tag_name((NS, "schema")) => schemas.push(parse_schema_node(child)?),
38            _ => {}
39        }
40    }
41
42    Ok(DatabaseXml {
43        foreign_key_mode,
44        boolean_mode,
45        case_sensitive_text,
46        tables,
47        enums,
48        views,
49        functions,
50        procedures,
51        other_sql,
52        schemas,
53    })
54}
55
56fn parse_schema_node(node: Node) -> Result<SchemaXml, String> {
57    let name = attr_string_required(node, "name")?;
58    let case_sensitive_text = attr_bool(node, "caseSensitiveText")?;
59
60    let mut tables = Vec::new();
61    let mut enums = Vec::new();
62    let mut views = Vec::new();
63    let mut functions = Vec::new();
64    let mut procedures = Vec::new();
65    let mut other_sql = Vec::new();
66
67    for child in node.children().filter(|n| n.is_element()) {
68        match child.tag_name().name() {
69            "table" if child.has_tag_name((NS, "table")) => tables.push(parse_table_node(child)?),
70            "enum" if child.has_tag_name((NS, "enum")) => enums.push(parse_enum_node(child)?),
71            "view" if child.has_tag_name((NS, "view")) => views.push(parse_view_node(child)?),
72            "function" if child.has_tag_name((NS, "function")) => functions.push(parse_function_node(child)?),
73            "procedure" if child.has_tag_name((NS, "procedure")) => procedures.push(parse_procedure_node(child)?),
74            "otherSql" if child.has_tag_name((NS, "otherSql")) => other_sql.push(parse_other_sql_node(child)?),
75            _ => {}
76        }
77    }
78
79    Ok(SchemaXml { name, case_sensitive_text, tables, enums, views, functions, procedures, other_sql })
80}
81
82fn parse_table_node(node: Node) -> Result<TableXml, String> {
83    let name = attr_string_required(node, "name")?;
84    let data_opt = attr_bool(node, "data")?;
85    let no_export = attr_bool(node, "noExport")?;
86    let export_data_column = attr_string(node, "exportDataColumn");
87    let compress = attr_bool(node, "compress")?;
88    let lock_escalation = attr_string(node, "lockEscalation");
89
90    let mut columns: Option<ColumnsXml> = None;
91    let mut keys: Option<KeysXml> = None;
92    let mut relations: Option<RelationsXml> = None;
93    let mut triggers: Option<TriggersXml> = None;
94    let mut constraints: Option<ConstraintsXml> = None;
95    let mut aggregations: Option<AggregationsXml> = None;
96    let mut initial_data: Option<InitialDataXml> = None;
97
98    for child in node.children().filter(|n| n.is_element()) {
99        if child.has_tag_name((NS, "columns")) {
100            columns = Some(parse_columns_node(child)?);
101        } else if child.has_tag_name((NS, "keys")) {
102            keys = Some(parse_keys_node(child)?);
103        } else if child.has_tag_name((NS, "relations")) {
104            relations = Some(parse_relations_node(child)?);
105        } else if child.has_tag_name((NS, "triggers")) {
106            triggers = Some(parse_triggers_node(child)?);
107        } else if child.has_tag_name((NS, "constraints")) {
108            constraints = Some(parse_constraints_node(child)?);
109        } else if child.has_tag_name((NS, "aggregations")) {
110            aggregations = Some(parse_aggregations_node(child)?);
111        } else if child.has_tag_name((NS, "initialData")) {
112            initial_data = Some(parse_initial_data_node(child));
113        }
114    }
115
116    Ok(TableXml {
117        name,
118        data_opt,
119        no_export,
120        export_data_column,
121        compress,
122        lock_escalation,
123        columns,
124        keys,
125        relations,
126        triggers,
127        constraints,
128        aggregations,
129        initial_data,
130    })
131}
132
133fn parse_columns_node(node: Node) -> Result<ColumnsXml, String> {
134    let mut cols = Vec::new();
135    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
136        cols.push(parse_column_node(c)?);
137    }
138    Ok(ColumnsXml { column: cols })
139}
140
141fn parse_column_node(node: Node) -> Result<ColumnXml, String> {
142    Ok(ColumnXml {
143        name: attr_string_required(node, "name")?,
144        r#type: attr_string_required(node, "type")?,
145        length: attr_i32(node, "length")?,
146        scale: attr_i32(node, "scale")?,
147        required: attr_bool(node, "required")?,
148        default_value: attr_string(node, "default"),
149        generated: attr_string(node, "generated"),
150        enum_type: attr_string(node, "enumType"),
151        element_type: attr_string(node, "elementType"),
152        min_value: attr_f64(node, "minValue")?,
153        max_value: attr_f64(node, "maxValue")?,
154        check: node
155            .children()
156            .find(|n| n.has_tag_name((NS, "check")))
157            .map(parse_check_node),
158    })
159}
160
161fn parse_check_node(node: Node) -> CheckXml {
162    let text = node.text().map(|s| s.trim()).filter(|s| !s.is_empty());
163    CheckXml { value: text.map(|s| s.to_string()) }
164}
165
166fn parse_keys_node(node: Node) -> Result<KeysXml, String> {
167    let mut primary: Option<KeyColumnsXml> = None;
168    let mut uniques: Vec<KeyColumnsXml> = Vec::new();
169    let mut indexes: Vec<IndexXml> = Vec::new();
170
171    for c in node.children().filter(|n| n.is_element()) {
172        if c.has_tag_name((NS, "primary")) {
173            primary = Some(parse_key_columns_node(c)?);
174        } else if c.has_tag_name((NS, "unique")) {
175            uniques.push(parse_key_columns_node(c)?);
176        } else if c.has_tag_name((NS, "index")) {
177            indexes.push(parse_index_node(c)?);
178        }
179    }
180
181    Ok(KeysXml { primary, uniques, indexes })
182}
183
184fn parse_key_columns_node(node: Node) -> Result<KeyColumnsXml, String> {
185    let mut columns = Vec::new();
186    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
187        columns.push(KeyColumnXml {
188            name: attr_string_required(c, "name")?,
189        });
190    }
191    let cluster = attr_bool(node, "cluster")?;
192    Ok(KeyColumnsXml { columns, cluster })
193}
194
195fn parse_index_node(node: Node) -> Result<IndexXml, String> {
196    let mut columns = Vec::new();
197    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
198        columns.push(KeyColumnXml { name: attr_string_required(c, "name")? });
199    }
200    Ok(IndexXml {
201        columns,
202        include: attr_string(node, "include"),
203        compress: attr_bool(node, "compress")?,
204        unique: attr_bool(node, "unique")?,
205    })
206}
207
208fn parse_relations_node(node: Node) -> Result<RelationsXml, String> {
209    let mut rels = Vec::new();
210    let mut composite_rels = Vec::new();
211    for r in node.children().filter(|n| n.is_element()) {
212        if r.has_tag_name((NS, "relation")) {
213            rels.push(RelationXml {
214                src: attr_string_required(r, "src")?,
215                table: attr_string_required(r, "table")?,
216                column: attr_string_required(r, "column")?,
217                r#type: attr_string_required(r, "type")?,
218                disable_usage_checking: attr_bool(r, "disableUsageChecking")?,
219            });
220        } else if r.has_tag_name((NS, "compositeRelation")) {
221            composite_rels.push(parse_composite_relation_node(r)?);
222        }
223    }
224    Ok(RelationsXml { relation: rels, composite_relation: composite_rels })
225}
226
227fn parse_composite_relation_node(node: Node) -> Result<CompositeRelationXml, String> {
228    let mut columns = Vec::new();
229    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
230        columns.push(CompositeRelationColumnXml {
231            src: attr_string_required(c, "src")?,
232            name: attr_string_required(c, "name")?,
233        });
234    }
235    Ok(CompositeRelationXml {
236        table: attr_string_required(node, "table")?,
237        r#type: attr_string_required(node, "type")?,
238        disable_usage_checking: attr_bool(node, "disableUsageChecking")?,
239        column: columns,
240    })
241}
242
243fn parse_view_node(node: Node) -> Result<ViewXml, String> {
244    Ok(ViewXml {
245        name: attr_string_required(node, "name")?,
246        database_type: attr_string(node, "databaseType"),
247        sql: collect_text(node),
248    })
249}
250
251fn parse_function_node(node: Node) -> Result<FunctionXml, String> {
252    let name = attr_string_required(node, "name")?;
253    let mut sql = Vec::new();
254    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
255        sql.push(VendorSqlXml {
256            database_type: attr_string_required(s, "databaseType")?,
257            sql: collect_text(s),
258        });
259    }
260    Ok(FunctionXml { name, sql })
261}
262
263fn parse_procedure_node(node: Node) -> Result<ProcedureXml, String> {
264    let name = attr_string_required(node, "name")?;
265    let mut sql = Vec::new();
266    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
267        sql.push(VendorSqlXml {
268            database_type: attr_string_required(s, "databaseType")?,
269            sql: collect_text(s),
270        });
271    }
272    Ok(ProcedureXml { name, sql })
273}
274
275fn parse_other_sql_node(node: Node) -> Result<OtherSqlXml, String> {
276    let database_type = attr_string_required(node, "databaseType")?;
277    let order_text = attr_string_required(node, "order")?;
278    let order = match order_text.to_ascii_lowercase().as_str() {
279        "top" => OtherSqlOrderXml::Top,
280        "bottom" => OtherSqlOrderXml::Bottom,
281        other => {
282            return Err(format!(
283                "<otherSql> element has an unrecognized order '{}' (expected top or bottom)",
284                other
285            ));
286        }
287    };
288    Ok(OtherSqlXml { database_type, order, sql: collect_text(node) })
289}
290
291fn parse_enum_node(node: Node) -> Result<EnumXml, String> {
292    let name = attr_string_required(node, "name")?;
293    let mut value = Vec::new();
294    for v in node.children().filter(|n| n.has_tag_name((NS, "value"))) {
295        value.push(EnumValueXml { name: attr_string_required(v, "name")?, code: attr_string(v, "code") });
296    }
297    Ok(EnumXml { name, value })
298}
299
300fn parse_triggers_node(node: Node) -> Result<TriggersXml, String> {
301    let mut update = Vec::new();
302    let mut delete = Vec::new();
303    for c in node.children().filter(|n| n.is_element()) {
304        if c.has_tag_name((NS, "update")) {
305            update.push(TriggerXml { database_type: attr_string_required(c, "databaseType")?, sql: collect_text(c) });
306        } else if c.has_tag_name((NS, "delete")) {
307            delete.push(TriggerXml { database_type: attr_string_required(c, "databaseType")?, sql: collect_text(c) });
308        }
309    }
310    Ok(TriggersXml { update, delete })
311}
312
313fn parse_constraints_node(node: Node) -> Result<ConstraintsXml, String> {
314    let mut constraint = Vec::new();
315    for c in node.children().filter(|n| n.has_tag_name((NS, "constraint"))) {
316        constraint.push(ConstraintXml {
317            name: attr_string_required(c, "name")?,
318            database_type: attr_string(c, "databaseType"),
319            sql: collect_text(c),
320        });
321    }
322    Ok(ConstraintsXml { constraint })
323}
324
325fn parse_aggregations_node(node: Node) -> Result<AggregationsXml, String> {
326    let mut aggregate = Vec::new();
327    for a in node.children().filter(|n| n.has_tag_name((NS, "aggregate"))) {
328        aggregate.push(parse_aggregate_node(a)?);
329    }
330    Ok(AggregationsXml { aggregate })
331}
332
333fn parse_aggregate_node(node: Node) -> Result<AggregateXml, String> {
334    let mut sum = Vec::new();
335    let mut count = Vec::new();
336    let mut group: Option<GroupXml> = None;
337
338    for c in node.children().filter(|n| n.is_element()) {
339        if c.has_tag_name((NS, "sum")) {
340            sum.push(SumXml {
341                source_column: attr_string_required(c, "sourceColumn")?,
342                destination_column: attr_string_required(c, "destinationColumn")?,
343            });
344        } else if c.has_tag_name((NS, "count")) {
345            count.push(CountXml { destination_column: attr_string_required(c, "destinationColumn")? });
346        } else if c.has_tag_name((NS, "group")) {
347            group = Some(parse_group_node(c)?);
348        }
349    }
350
351    Ok(AggregateXml {
352        sum,
353        count,
354        group: group.unwrap_or_else(|| GroupXml { column: Vec::new() }),
355        destination_table: attr_string_required(node, "destinationTable")?,
356        date_column: attr_string_required(node, "dateColumn")?,
357        timestamp_column: attr_string_required(node, "timestampColumn")?,
358        frequency: attr_string_required(node, "frequency")?,
359        criteria: attr_string(node, "criteria"),
360    })
361}
362
363fn parse_group_node(node: Node) -> Result<GroupXml, String> {
364    let mut column = Vec::new();
365    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
366        column.push(GroupColumnXml {
367            source: attr_string_required(c, "source")?,
368            destination: attr_string_required(c, "destination")?,
369            source_derived_from: attr_string(c, "sourceDerivedFrom"),
370        });
371    }
372    Ok(GroupXml { column })
373}
374
375fn parse_initial_data_node(node: Node) -> InitialDataXml {
376    let mut sql = Vec::new();
377    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
378        sql.push(InitialSqlXml {
379            database_type: attr_string(s, "databaseType"),
380            sql: collect_text(s),
381        });
382    }
383    InitialDataXml { sql }
384}
385
386// -------- Utils --------
387fn attr_string(node: Node, name: &str) -> Option<String> {
388    node.attribute(name).map(|s| s.to_string())
389}
390
391/// Reads a required attribute. Returns an error (naming the element and attribute)
392/// rather than silently defaulting to `""` when it's absent - a missing `name`/`type`/
393/// `table`/`column`/etc. attribute is a malformed schema definition, and nothing
394/// downstream validates against an empty name, so a silent default would otherwise let
395/// it through as a real (if oddly-named) table/column/relation.
396fn attr_string_required(node: Node, name: &str) -> Result<String, String> {
397    node.attribute(name).map(|s| s.to_string()).ok_or_else(|| {
398        format!(
399            "<{}> element is missing required attribute '{}'",
400            node.tag_name().name(),
401            name
402        )
403    })
404}
405
406/// Reads an optional boolean attribute. Unlike a missing attribute (which is a legitimate
407/// "not specified"), a *present but unparseable* value (`required="yep"`) is a malformed
408/// schema definition - silently falling back to `None`/`false` would hide a typo instead of
409/// reporting it, so this errors instead.
410fn attr_bool(node: Node, name: &str) -> Result<Option<bool>, String> {
411    match node.attribute(name) {
412        None => Ok(None),
413        Some(v) => match v.to_ascii_lowercase().as_str() {
414            "true" | "1" | "yes" | "on" => Ok(Some(true)),
415            "false" | "0" | "no" | "off" => Ok(Some(false)),
416            _ => Err(format!(
417                "<{}> attribute '{}' has invalid boolean value '{}' (expected true/false, 1/0, yes/no, or on/off)",
418                node.tag_name().name(),
419                name,
420                v
421            )),
422        },
423    }
424}
425
426/// Reads an optional integer attribute, erroring (rather than silently defaulting to `None`)
427/// when the attribute is present but not a valid `i32` - a typo like `length="1O0"` or an
428/// overflowing value like `length="99999999999"` should be reported, not turned into 0.
429fn attr_i32(node: Node, name: &str) -> Result<Option<i32>, String> {
430    match node.attribute(name) {
431        None => Ok(None),
432        Some(v) => v.parse::<i32>().map(Some).map_err(|_| {
433            format!(
434                "<{}> attribute '{}' has invalid integer value '{}'",
435                node.tag_name().name(),
436                name,
437                v
438            )
439        }),
440    }
441}
442
443/// Reads an optional numeric attribute, erroring (rather than silently defaulting to `None`)
444/// when the attribute is present but not a finite `f64` - this covers unparseable typos like
445/// `minValue="1o"` as well as `inf`/`nan`, which `f64::parse` otherwise accepts silently.
446fn attr_f64(node: Node, name: &str) -> Result<Option<f64>, String> {
447    match node.attribute(name) {
448        None => Ok(None),
449        Some(v) => match v.parse::<f64>() {
450            Ok(n) if n.is_finite() => Ok(Some(n)),
451            _ => Err(format!(
452                "<{}> attribute '{}' has invalid numeric value '{}'",
453                node.tag_name().name(),
454                name,
455                v
456            )),
457        },
458    }
459}
460
461fn collect_text(node: Node) -> String {
462    let mut out = String::new();
463    for n in node.children() {
464        if n.is_text() {
465            out.push_str(n.text().unwrap_or(""));
466        }
467    }
468    out.trim().to_string()
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use std::fs;
475
476    #[test]
477    fn parse_with_roxmltree_sample() {
478        let xml = fs::read_to_string("tests/resources/schema-parser-test-schema.xml").expect("resource present");
479        let db = parse_database_roxml(&xml).expect("parsed");
480        assert!(!db.tables.is_empty());
481        assert!(db.schemas.is_empty() || !db.schemas[0].tables.is_empty());
482    }
483
484    #[test]
485    fn attr_bool_is_case_insensitive() {
486        let doc = Document::parse(
487            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE" cluster="No"/>"#,
488        )
489        .unwrap();
490        let node = doc.root_element();
491
492        assert_eq!(attr_bool(node, "required"), Ok(Some(true)));
493        assert_eq!(attr_bool(node, "cluster"), Ok(Some(false)));
494    }
495
496    #[test]
497    fn attr_bool_errors_on_unrecognized_value() {
498        let doc = Document::parse(
499            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="yep"/>"#,
500        )
501        .unwrap();
502        let node = doc.root_element();
503
504        let err = attr_bool(node, "required").unwrap_err();
505        assert!(err.contains("required"));
506        assert!(err.contains("yep"));
507    }
508
509    #[test]
510    fn attr_i32_errors_on_unparseable_value() {
511        let doc = Document::parse(
512            r#"<column xmlns="http://stano.com/database" name="x" type="varchar" length="1O0"/>"#,
513        )
514        .unwrap();
515        let node = doc.root_element();
516
517        let err = attr_i32(node, "length").unwrap_err();
518        assert!(err.contains("length"));
519        assert!(err.contains("1O0"));
520    }
521
522    #[test]
523    fn attr_f64_errors_on_unparseable_value() {
524        let doc = Document::parse(
525            r#"<column xmlns="http://stano.com/database" name="x" type="int" minValue="1o"/>"#,
526        )
527        .unwrap();
528        let node = doc.root_element();
529
530        let err = attr_f64(node, "minValue").unwrap_err();
531        assert!(err.contains("minValue"));
532        assert!(err.contains("1o"));
533    }
534
535    #[test]
536    fn attr_f64_errors_on_infinite_value() {
537        let doc = Document::parse(
538            r#"<column xmlns="http://stano.com/database" name="x" type="int" maxValue="inf"/>"#,
539        )
540        .unwrap();
541        let node = doc.root_element();
542
543        let err = attr_f64(node, "maxValue").unwrap_err();
544        assert!(err.contains("maxValue"));
545        assert!(err.contains("inf"));
546    }
547
548    #[test]
549    fn parse_column_node_honors_uppercase_required_attribute() {
550        let doc = Document::parse(
551            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE"/>"#,
552        )
553        .unwrap();
554        let node = doc.root_element();
555
556        let column = parse_column_node(node).expect("parse ok");
557
558        assert_eq!(column.required, Some(true));
559    }
560
561    #[test]
562    fn missing_required_attribute_returns_error_instead_of_defaulting_to_empty_string() {
563        let doc = Document::parse(r#"<column xmlns="http://stano.com/database" type="int"/>"#).unwrap();
564        let node = doc.root_element();
565
566        let err = parse_column_node(node).unwrap_err();
567        assert!(err.contains("column"));
568        assert!(err.contains("name"));
569    }
570}